added playback multiplier
[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         parseConfig();
112
113         for(auto itr=propertiesToSubscribeTo.begin();itr!=propertiesToSubscribeTo.end();itr++)
114         {
115                 engine->subscribeToProperty(*itr,this);
116         }
117
118         mSupported.push_back(DatabaseFileProperty);
119         mSupported.push_back(DatabaseLoggingProperty);
120         mSupported.push_back(DatabasePlaybackProperty);
121
122         routingEngine->setSupported(mSupported,this);
123
124 }
125
126 DatabaseSink::~DatabaseSink()
127 {
128         if(shared)
129         {
130                 DBObject* obj = new DBObject();
131                 obj->quit = true;
132
133                 shared->queue.append(obj);
134
135                 g_thread_join(thread);
136                 g_thread_unref(thread);
137                 delete shared;
138         }
139
140         if(playbackShared)
141         {
142                 delete playbackShared;
143         }
144 }
145
146
147 void DatabaseSink::supportedChanged(PropertyList supportedProperties)
148 {
149
150 }
151
152 PropertyList DatabaseSink::supported()
153 {
154         return mSupported;
155 }
156
157 void DatabaseSink::parseConfig()
158 {
159         json_object *rootobject;
160         json_tokener *tokener = json_tokener_new();
161         enum json_tokener_error err;
162         do
163         {
164                 rootobject = json_tokener_parse_ex(tokener, configuration["properties"].c_str(),configuration["properties"].size());
165         } while ((err = json_tokener_get_error(tokener)) == json_tokener_continue);
166         if (err != json_tokener_success)
167         {
168                 fprintf(stderr, "Error: %s\n", json_tokener_error_desc(err));
169         }
170         if (tokener->char_offset < configuration["properties"].size()) // XXX shouldn't access internal fields
171         {
172                 //Should handle the extra data here sometime...
173         }
174         
175         json_object *propobject = json_object_object_get(rootobject,"properties");
176         
177         g_assert(json_object_get_type(propobject) == json_type_array);
178
179         array_list *proplist = json_object_get_array(propobject);
180         
181         for(int i=0; i < array_list_length(proplist); i++)
182         {
183                 json_object *idxobj = (json_object*)array_list_get_idx(proplist,i);
184                 std::string prop = json_object_get_string(idxobj);
185                 propertiesToSubscribeTo.push_back(prop);
186
187                 DebugOut()<<"DatabaseSink logging: "<<prop<<endl;
188         }
189
190         json_object_put(propobject);
191         json_object_put(rootobject);
192 }
193
194 void DatabaseSink::stopDb()
195 {
196         if(!shared)
197                 return;
198
199         DBObject *obj = new DBObject();
200         obj->quit = true;
201         shared->queue.append(obj);
202
203         g_thread_join(thread);
204
205         delete shared;
206         shared = NULL;
207 }
208
209 void DatabaseSink::startDb()
210 {
211         if(playback)
212         {
213                 DebugOut(0)<<"ERROR: tried to start logging during playback.  Only logging or playback can be used at one time"<<endl;
214                 return;
215         }
216
217         if(shared)
218         {
219                 DebugOut(0)<<"WARNING: logging already started.  doing nothing."<<endl;
220                 return;
221         }
222
223         initDb();
224
225 //      thread = g_thread_new("dbthread", cbFunc, shared);
226 }
227
228 void DatabaseSink::startPlayback()
229 {
230         if(playback)
231                 return;
232
233         playback = true;
234
235         initDb();
236
237         /// get supported:
238
239         vector<vector<string> > supportedStr = shared->db->select("SELECT DISTINCT key FROM "+tablename);
240
241         for(int i=0; i < supportedStr.size(); i++)
242         {
243                 if(!ListPlusPlus<VehicleProperty::Property>(&mSupported).contains(supportedStr[i][0]))
244                         mSupported.push_back(supportedStr[i][0]);
245         }
246
247         routingEngine->setSupported(supported(), this);
248
249         /// populate playback queue:
250
251         vector<vector<string> > results = shared->db->select("SELECT * FROM "+tablename);
252
253         if(playbackShared)
254         {
255                 delete playbackShared;
256         }
257
258         playbackShared = new PlaybackShared(routingEngine, uuid(), playbackMultiplier);
259
260         for(int i=0;i<results.size();i++)
261         {
262                 if(results[i].size() < 5)
263                 {
264                         throw std::runtime_error("column mismatch in query");
265                 }
266
267                 DBObject* obj = new DBObject();
268
269                 obj->key = results[i][0];
270                 obj->value = results[i][1];
271                 obj->source = results[i][2];
272                 obj->time = boost::lexical_cast<double>(results[i][3]);
273 //              obj->sequence = boost::lexical_cast<int>(results[i][4]);
274
275                 playbackShared->playbackQueue.push_back(obj);
276         }
277
278         g_timeout_add(0,getNextEvent,playbackShared);
279 }
280
281 void DatabaseSink::initDb()
282 {
283         if(shared) delete shared;
284
285         shared = new Shared;
286         shared->db->init(databaseName, tablename, tablecreate);
287 }
288
289 void DatabaseSink::propertyChanged(VehicleProperty::Property property, AbstractPropertyType *value, std::string uuid)
290 {
291         if(!shared)
292                 return;
293
294         DBObject* obj = new DBObject;
295         obj->key = property;
296         obj->value = value->toString();
297         obj->source = uuid;
298         obj->time = value->timestamp;
299         obj->sequence = value->sequence;
300
301         shared->queue.append(obj);
302 }
303
304
305 std::string DatabaseSink::uuid()
306 {
307         return "9f88156e-cb92-4472-8775-9c08addf50d3";
308 }
309
310 void DatabaseSink::getPropertyAsync(AsyncPropertyReply *reply)
311 {
312         reply->success = false;
313
314         if(reply->property == DatabaseFileProperty)
315         {
316                 StringPropertyType temp(databaseName);
317                 reply->value = &temp;
318
319                 reply->success = true;
320                 reply->completed(reply);
321
322                 return;
323         }
324         else if(reply->property == DatabaseLoggingProperty)
325         {
326                 BasicPropertyType<bool> temp = shared;
327
328                 reply->value = &temp;
329                 reply->success = true;
330                 reply->completed(reply);
331
332                 return;
333         }
334
335         else if(reply->property == DatabasePlaybackProperty)
336         {
337                 BasicPropertyType<bool> temp = playback;
338                 reply->value = &temp;
339                 reply->success = true;
340                 reply->completed(reply);
341
342                 return;
343         }
344
345         reply->completed(reply);
346 }
347
348 void DatabaseSink::getRangePropertyAsync(AsyncRangePropertyReply *reply)
349 {
350         BaseDB * db = new BaseDB();
351         db->init(databaseName, tablename, tablecreate);
352
353         ostringstream query;
354         query.precision(15);
355
356         query<<"SELECT * from "<<tablename<<" WHERE ";
357
358         if(reply->timeBegin && reply->timeEnd)
359         {
360                 query<<" time BETWEEN "<<reply->timeBegin<<" AND "<<reply->timeEnd;
361         }
362
363         if(reply->sequenceBegin >= 0 && reply->sequenceEnd >=0)
364         {
365                 query<<" AND sequence BETWEEN "<<reply->sequenceBegin<<" AND "<<reply->sequenceEnd;
366         }
367
368         std::vector<std::vector<string>> data = db->select(query.str());
369
370         std::list<AbstractPropertyType*> cleanup;
371
372         for(auto i=0;i<data.size();i++)
373         {
374                 if(data[i].size() != 5)
375                         continue;
376
377                 DBObject dbobj;
378                 dbobj.key = data[i][0];
379                 dbobj.value = data[i][1];
380                 dbobj.source = data[i][2];
381                 dbobj.time = boost::lexical_cast<double>(data[i][3]);
382                 dbobj.sequence = boost::lexical_cast<double>(data[i][4]);
383
384                 AbstractPropertyType* property = VehicleProperty::getPropertyTypeForPropertyNameValue(dbobj.key, dbobj.value);
385                 if(property)
386                 {
387                         property->timestamp = dbobj.time;
388                         property->sequence = dbobj.sequence;
389
390                         reply->values.push_back(property);
391                         cleanup.push_back(property);
392                 }
393         }
394
395         reply->success = true;
396         reply->completed(reply);
397
398         /// reply is owned by the requester of this call.  we own the data:
399         for(auto itr = cleanup.begin(); itr != cleanup.end(); itr++)
400         {
401                 delete *itr;
402         }
403
404         delete db;
405 }
406
407 AsyncPropertyReply *DatabaseSink::setProperty(AsyncSetPropertyRequest request)
408 {
409         AsyncPropertyReply* reply = new AsyncPropertyReply(request);
410         reply->success = false;
411
412         if(request.property == DatabaseLoggingProperty)
413         {
414                 if(request.value->value<bool>())
415                 {
416                         ///TODO: start or stop logging thread
417                         startDb();
418                         reply->success = true;
419                         BasicPropertyType<bool> temp(true);
420                         routingEngine->updateProperty(DatabaseLoggingProperty,&temp,uuid());
421                 }
422                 else
423                 {
424                         stopDb();
425                         reply->success = true;
426                         BasicPropertyType<bool> temp(false);
427                         routingEngine->updateProperty(DatabaseLoggingProperty,&temp,uuid());
428                 }
429         }
430
431         else if(request.property == DatabaseFileProperty)
432         {
433                 std::string fname = request.value->toString();
434
435                 databaseName = fname;
436
437                 StringPropertyType temp(databaseName);
438
439                 routingEngine->updateProperty(DatabaseFileProperty,&temp,uuid());
440
441                 reply->success = true;
442         }
443         else if( request.property == DatabasePlaybackProperty)
444         {
445                 if(request.value->value<bool>())
446                 {
447                         startPlayback();
448
449                         BasicPropertyType<bool> temp(true);
450
451                         routingEngine->updateProperty(DatabasePlaybackProperty,&temp,uuid());
452                 }
453                 else
454                 {
455                         /// TODO: stop playback
456
457                         BasicPropertyType<bool> temp(true);
458
459                         routingEngine->updateProperty(DatabasePlaybackProperty,&temp,uuid());
460                 }
461
462                 reply->success = true;
463         }
464
465         return reply;
466 }
467
468 void DatabaseSink::subscribeToPropertyChanges(VehicleProperty::Property )
469 {
470
471 }
472
473 void DatabaseSink::unsubscribeToPropertyChanges(VehicleProperty::Property )
474 {
475 }