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