added more options to database
[profile/ivi/automotive-message-broker.git] / plugins / database / databasesink.cpp
1 #include "databasesink.h"
2 #include "abstractroutingengine.h"
3 #include "listplusplus.h"
4
5 extern "C" AbstractSinkManager * create(AbstractRoutingEngine* routingengine, map<string, string> config)
6 {
7         return new DatabaseSinkManager(routingengine, config);
8 }
9
10 void * cbFunc(gpointer data)
11 {
12         Shared *shared = static_cast<Shared*>(data);
13
14         if(!shared)
15         {
16                 throw std::runtime_error("Could not cast shared object.");
17         }
18
19         while(1)
20         {
21                 DBObject* obj = shared->queue.pop();
22
23                 if( obj->quit )
24                 {
25                         delete obj;
26                         break;
27                 }
28
29                 DictionaryList<string> dict;
30
31                 NameValuePair<string> one("key", obj->key);
32                 NameValuePair<string> two("value", obj->value);
33                 NameValuePair<string> three("source", obj->source);
34                 NameValuePair<string> four("time", boost::lexical_cast<string>(obj->time));
35                 NameValuePair<string> five("sequence", boost::lexical_cast<string>(obj->sequence));
36
37                 dict.push_back(one);
38                 dict.push_back(two);
39                 dict.push_back(three);
40                 dict.push_back(four);
41                 dict.push_back(five);
42
43                 shared->db->insert(dict);
44                 delete obj;
45         }
46
47         return NULL;
48 }
49
50 int getNextEvent(gpointer data)
51 {
52         PlaybackShared* pbshared = static_cast<PlaybackShared*>(data);
53
54         if(!pbshared)
55                 throw std::runtime_error("failed to cast PlaybackShared object");
56
57         auto itr = pbshared->playbackQueue.begin();
58
59         if(itr == pbshared->playbackQueue.end())
60         {
61                 return 0;
62         }
63
64         DBObject* obj = *itr;
65
66         AbstractPropertyType* value = VehicleProperty::getPropertyTypeForPropertyNameValue(obj->key,obj->value);
67
68         if(value)
69         {
70                 pbshared->routingEngine->updateProperty(obj->key, value, pbshared->uuid);
71                 value->timestamp = obj->time;
72                 value->sequence = obj->sequence;
73         }
74
75         if(++itr != pbshared->playbackQueue.end())
76         {
77                 DBObject *o2 = *itr;
78                 double t = o2->time - obj->time;
79
80                 if(t > 0)
81                         g_timeout_add((t*1000) / pbshared->playBackMultiplier, getNextEvent, pbshared);
82                 else
83                         g_timeout_add(t, getNextEvent, pbshared);
84         }
85
86         pbshared->playbackQueue.remove(obj);
87         delete obj;
88
89         return 0;
90 }
91
92 DatabaseSink::DatabaseSink(AbstractRoutingEngine *engine, map<std::string, std::string> config)
93         :AbstractSource(engine,config),thread(NULL),shared(NULL),playback(false),playbackShared(NULL), playbackMultiplier(1)
94 {
95         databaseName = "storage";
96         tablename = "data";
97         tablecreate = "CREATE TABLE IF NOT EXISTS data (key TEXT, value BLOB, source TEXT, time REAL, sequence REAL)";
98
99         //startDb();
100
101         if(config.find("startOnLoad")!= config.end())
102         {
103                 startDb();
104         }
105
106         if(config.find("playbackMultiplier")!= config.end())
107         {
108                 playbackMultiplier = boost::lexical_cast<uint>(config["playbackMultiplier"]);
109         }
110
111         if(config.find("playbackOnLoad")!= config.end())
112         {
113                 startPlayback();
114         }
115
116         if(config.find("databaseFile") != config.end())
117         {
118                 databaseName = config["databaseFile"];
119         }
120
121         parseConfig();
122
123         for(auto itr=propertiesToSubscribeTo.begin();itr!=propertiesToSubscribeTo.end();itr++)
124         {
125                 engine->subscribeToProperty(*itr,this);
126         }
127
128         mSupported.push_back(DatabaseFileProperty);
129         mSupported.push_back(DatabaseLoggingProperty);
130         mSupported.push_back(DatabasePlaybackProperty);
131
132         routingEngine->setSupported(mSupported,this);
133
134 }
135
136 DatabaseSink::~DatabaseSink()
137 {
138         if(shared)
139         {
140                 DBObject* obj = new DBObject();
141                 obj->quit = true;
142
143                 shared->queue.append(obj);
144
145                 g_thread_join(thread);
146                 g_thread_unref(thread);
147                 delete shared;
148         }
149
150         if(playbackShared)
151         {
152                 delete playbackShared;
153         }
154 }
155
156
157 void DatabaseSink::supportedChanged(PropertyList supportedProperties)
158 {
159
160 }
161
162 PropertyList DatabaseSink::supported()
163 {
164         return mSupported;
165 }
166
167 void DatabaseSink::parseConfig()
168 {
169         json_object *rootobject;
170         json_tokener *tokener = json_tokener_new();
171         enum json_tokener_error err;
172         do
173         {
174                 rootobject = json_tokener_parse_ex(tokener, configuration["properties"].c_str(),configuration["properties"].size());
175         } while ((err = json_tokener_get_error(tokener)) == json_tokener_continue);
176         if (err != json_tokener_success)
177         {
178                 fprintf(stderr, "Error: %s\n", json_tokener_error_desc(err));
179         }
180         if (tokener->char_offset < configuration["properties"].size()) // XXX shouldn't access internal fields
181         {
182                 //Should handle the extra data here sometime...
183         }
184         
185         json_object *propobject = json_object_object_get(rootobject,"properties");
186         
187         g_assert(json_object_get_type(propobject) == json_type_array);
188
189         array_list *proplist = json_object_get_array(propobject);
190         
191         for(int i=0; i < array_list_length(proplist); i++)
192         {
193                 json_object *idxobj = (json_object*)array_list_get_idx(proplist,i);
194                 std::string prop = json_object_get_string(idxobj);
195                 propertiesToSubscribeTo.push_back(prop);
196
197                 DebugOut()<<"DatabaseSink logging: "<<prop<<endl;
198         }
199
200         json_object_put(propobject);
201         json_object_put(rootobject);
202 }
203
204 void DatabaseSink::stopDb()
205 {
206         if(!shared)
207                 return;
208
209         DBObject *obj = new DBObject();
210         obj->quit = true;
211         shared->queue.append(obj);
212
213         g_thread_join(thread);
214
215         delete shared;
216         shared = NULL;
217 }
218
219 void DatabaseSink::startDb()
220 {
221         if(playback)
222         {
223                 DebugOut(0)<<"ERROR: tried to start logging during playback.  Only logging or playback can be used at one time"<<endl;
224                 return;
225         }
226
227         if(shared)
228         {
229                 DebugOut(0)<<"WARNING: logging already started.  doing nothing."<<endl;
230                 return;
231         }
232
233         initDb();
234
235 //      thread = g_thread_new("dbthread", cbFunc, shared);
236 }
237
238 void DatabaseSink::startPlayback()
239 {
240         if(playback)
241                 return;
242
243         playback = true;
244
245         initDb();
246
247         /// get supported:
248
249         vector<vector<string> > supportedStr = shared->db->select("SELECT DISTINCT key FROM "+tablename);
250
251         for(int i=0; i < supportedStr.size(); i++)
252         {
253                 if(!ListPlusPlus<VehicleProperty::Property>(&mSupported).contains(supportedStr[i][0]))
254                         mSupported.push_back(supportedStr[i][0]);
255         }
256
257         routingEngine->setSupported(supported(), this);
258
259         /// populate playback queue:
260
261         vector<vector<string> > results = shared->db->select("SELECT * FROM "+tablename);
262
263         if(playbackShared)
264         {
265                 delete playbackShared;
266         }
267
268         playbackShared = new PlaybackShared(routingEngine, uuid(), playbackMultiplier);
269
270         for(int i=0;i<results.size();i++)
271         {
272                 if(results[i].size() < 5)
273                 {
274                         throw std::runtime_error("column mismatch in query");
275                 }
276
277                 DBObject* obj = new DBObject();
278
279                 obj->key = results[i][0];
280                 obj->value = results[i][1];
281                 obj->source = results[i][2];
282                 obj->time = boost::lexical_cast<double>(results[i][3]);
283 //              obj->sequence = boost::lexical_cast<int>(results[i][4]);
284
285                 playbackShared->playbackQueue.push_back(obj);
286         }
287
288         g_timeout_add(0,getNextEvent,playbackShared);
289 }
290
291 void DatabaseSink::initDb()
292 {
293         if(shared) delete shared;
294
295         shared = new Shared;
296         shared->db->init(databaseName, tablename, tablecreate);
297 }
298
299 void DatabaseSink::propertyChanged(VehicleProperty::Property property, AbstractPropertyType *value, std::string uuid)
300 {
301         if(!shared)
302                 return;
303
304         DBObject* obj = new DBObject;
305         obj->key = property;
306         obj->value = value->toString();
307         obj->source = uuid;
308         obj->time = value->timestamp;
309         obj->sequence = value->sequence;
310
311         shared->queue.append(obj);
312 }
313
314
315 std::string DatabaseSink::uuid()
316 {
317         return "9f88156e-cb92-4472-8775-9c08addf50d3";
318 }
319
320 void DatabaseSink::getPropertyAsync(AsyncPropertyReply *reply)
321 {
322         reply->success = false;
323
324         if(reply->property == DatabaseFileProperty)
325         {
326                 StringPropertyType temp(databaseName);
327                 reply->value = &temp;
328
329                 reply->success = true;
330                 reply->completed(reply);
331
332                 return;
333         }
334         else if(reply->property == DatabaseLoggingProperty)
335         {
336                 BasicPropertyType<bool> temp = shared;
337
338                 reply->value = &temp;
339                 reply->success = true;
340                 reply->completed(reply);
341
342                 return;
343         }
344
345         else if(reply->property == DatabasePlaybackProperty)
346         {
347                 BasicPropertyType<bool> temp = playback;
348                 reply->value = &temp;
349                 reply->success = true;
350                 reply->completed(reply);
351
352                 return;
353         }
354
355         reply->completed(reply);
356 }
357
358 void DatabaseSink::getRangePropertyAsync(AsyncRangePropertyReply *reply)
359 {
360         BaseDB * db = new BaseDB();
361         db->init(databaseName, tablename, tablecreate);
362
363         ostringstream query;
364         query.precision(15);
365
366         query<<"SELECT * from "<<tablename<<" WHERE ";
367
368         if(reply->timeBegin && reply->timeEnd)
369         {
370                 query<<" time BETWEEN "<<reply->timeBegin<<" AND "<<reply->timeEnd;
371         }
372
373         if(reply->sequenceBegin >= 0 && reply->sequenceEnd >=0)
374         {
375                 query<<" AND sequence BETWEEN "<<reply->sequenceBegin<<" AND "<<reply->sequenceEnd;
376         }
377
378         std::vector<std::vector<string>> data = db->select(query.str());
379
380         std::list<AbstractPropertyType*> cleanup;
381
382         for(auto i=0;i<data.size();i++)
383         {
384                 if(data[i].size() != 5)
385                         continue;
386
387                 DBObject dbobj;
388                 dbobj.key = data[i][0];
389                 dbobj.value = data[i][1];
390                 dbobj.source = data[i][2];
391                 dbobj.time = boost::lexical_cast<double>(data[i][3]);
392                 dbobj.sequence = boost::lexical_cast<double>(data[i][4]);
393
394                 AbstractPropertyType* property = VehicleProperty::getPropertyTypeForPropertyNameValue(dbobj.key, dbobj.value);
395                 if(property)
396                 {
397                         property->timestamp = dbobj.time;
398                         property->sequence = dbobj.sequence;
399
400                         reply->values.push_back(property);
401                         cleanup.push_back(property);
402                 }
403         }
404
405         reply->success = true;
406         reply->completed(reply);
407
408         /// reply is owned by the requester of this call.  we own the data:
409         for(auto itr = cleanup.begin(); itr != cleanup.end(); itr++)
410         {
411                 delete *itr;
412         }
413
414         delete db;
415 }
416
417 AsyncPropertyReply *DatabaseSink::setProperty(AsyncSetPropertyRequest request)
418 {
419         AsyncPropertyReply* reply = new AsyncPropertyReply(request);
420         reply->success = false;
421
422         if(request.property == DatabaseLoggingProperty)
423         {
424                 if(request.value->value<bool>())
425                 {
426                         ///TODO: start or stop logging thread
427                         startDb();
428                         reply->success = true;
429                         BasicPropertyType<bool> temp(true);
430                         routingEngine->updateProperty(DatabaseLoggingProperty,&temp,uuid());
431                 }
432                 else
433                 {
434                         stopDb();
435                         reply->success = true;
436                         BasicPropertyType<bool> temp(false);
437                         routingEngine->updateProperty(DatabaseLoggingProperty,&temp,uuid());
438                 }
439         }
440
441         else if(request.property == DatabaseFileProperty)
442         {
443                 std::string fname = request.value->toString();
444
445                 databaseName = fname;
446
447                 StringPropertyType temp(databaseName);
448
449                 routingEngine->updateProperty(DatabaseFileProperty,&temp,uuid());
450
451                 reply->success = true;
452         }
453         else if( request.property == DatabasePlaybackProperty)
454         {
455                 if(request.value->value<bool>())
456                 {
457                         startPlayback();
458
459                         BasicPropertyType<bool> temp(true);
460
461                         routingEngine->updateProperty(DatabasePlaybackProperty,&temp,uuid());
462                 }
463                 else
464                 {
465                         /// TODO: stop playback
466
467                         BasicPropertyType<bool> temp(true);
468
469                         routingEngine->updateProperty(DatabasePlaybackProperty,&temp,uuid());
470                 }
471
472                 reply->success = true;
473         }
474
475         return reply;
476 }
477
478 void DatabaseSink::subscribeToPropertyChanges(VehicleProperty::Property )
479 {
480
481 }
482
483 void DatabaseSink::unsubscribeToPropertyChanges(VehicleProperty::Property )
484 {
485 }