1 #include "databasesink.h"
2 #include "abstractroutingengine.h"
3 #include "listplusplus.h"
5 int bufferLength = 100;
7 extern "C" AbstractSinkManager * create(AbstractRoutingEngine* routingengine, map<string, string> config)
9 return new DatabaseSinkManager(routingengine, config);
12 void * cbFunc(gpointer data)
14 Shared *shared = static_cast<Shared*>(data);
18 throw std::runtime_error("Could not cast shared object.");
21 vector<DictionaryList<string> > insertList;
25 DBObject* obj = shared->queue.pop();
33 DictionaryList<string> dict;
35 NameValuePair<string> one("key", obj->key);
36 NameValuePair<string> two("value", obj->value);
37 NameValuePair<string> three("source", obj->source);
38 NameValuePair<string> four("time", boost::lexical_cast<string>(obj->time));
39 NameValuePair<string> five("sequence", boost::lexical_cast<string>(obj->sequence));
43 dict.push_back(three);
47 insertList.push_back(dict);
49 if(insertList.size() > bufferLength)
51 shared->db->exec("BEGIN IMMEDIATE TRANSACTION");
52 for(int i=0; i< insertList.size(); i++)
54 DictionaryList<string> d = insertList[i];
55 shared->db->insert(d);
57 shared->db->exec("END TRANSACTION");
63 /// final flush of whatever is still in the queue:
65 shared->db->exec("BEGIN IMMEDIATE TRANSACTION");
66 for(int i=0; i< insertList.size(); i++)
68 DictionaryList<string> d = insertList[i];
69 shared->db->insert(d);
71 shared->db->exec("END TRANSACTION");
76 int getNextEvent(gpointer data)
78 PlaybackShared* pbshared = static_cast<PlaybackShared*>(data);
81 throw std::runtime_error("failed to cast PlaybackShared object");
86 auto itr = pbshared->playbackQueue.begin();
88 if(itr == pbshared->playbackQueue.end())
95 AbstractPropertyType* value = VehicleProperty::getPropertyTypeForPropertyNameValue(obj->key,obj->value);
99 pbshared->routingEngine->updateProperty(value, pbshared->uuid);
100 value->timestamp = obj->time;
101 //value->sequence = obj->sequence;
104 if(++itr != pbshared->playbackQueue.end())
107 double t = o2->time - obj->time;
110 g_timeout_add((t*1000) / pbshared->playBackMultiplier, getNextEvent, pbshared);
112 g_timeout_add(1, getNextEvent, pbshared);
115 pbshared->playbackQueue.remove(obj);
116 DebugOut()<<"playback Queue size: "<<pbshared->playbackQueue.size()<<endl;
122 DatabaseSink::DatabaseSink(AbstractRoutingEngine *engine, map<std::string, std::string> config)
123 :AbstractSource(engine,config),thread(NULL),shared(NULL),playback(false),playbackShared(NULL), playbackMultiplier(1)
125 databaseName = "storage";
127 tablecreate = "CREATE TABLE IF NOT EXISTS data (key TEXT, value BLOB, source TEXT, time REAL, sequence REAL)";
129 if(config.find("databaseFile") != config.end())
131 setDatabaseFileName(config["databaseFile"]);
134 if(config.find("bufferLength") != config.end())
136 bufferLength = atoi(config["bufferLength"].c_str());
139 if(config.find("properties") != config.end())
144 for(auto itr=propertiesToSubscribeTo.begin();itr!=propertiesToSubscribeTo.end();itr++)
146 engine->subscribeToProperty(*itr,this);
149 mSupported.push_back(DatabaseFile);
150 mSupported.push_back(DatabaseLogging);
151 mSupported.push_back(DatabasePlayback);
153 routingEngine->setSupported(supported(), this);
155 if(config.find("startOnLoad")!= config.end())
160 if(config.find("playbackMultiplier")!= config.end())
162 playbackMultiplier = boost::lexical_cast<uint>(config["playbackMultiplier"]);
165 if(config.find("playbackOnLoad")!= config.end())
173 DatabaseSink::~DatabaseSink()
177 DBObject* obj = new DBObject();
180 shared->queue.append(obj);
182 g_thread_join(thread);
183 // g_thread_unref(thread);
189 delete playbackShared;
194 void DatabaseSink::supportedChanged(PropertyList supportedProperties)
199 PropertyList DatabaseSink::supported()
204 PropertyInfo DatabaseSink::getPropertyInfo(VehicleProperty::Property property)
206 /// TODO: Compute update frequency for properties in the database
207 return PropertyInfo::invalid();
210 void DatabaseSink::parseConfig()
212 json_object *rootobject;
213 json_tokener *tokener = json_tokener_new();
214 enum json_tokener_error err;
217 rootobject = json_tokener_parse_ex(tokener, configuration["properties"].c_str(),configuration["properties"].size());
218 } while ((err = json_tokener_get_error(tokener)) == json_tokener_continue);
219 if (err != json_tokener_success)
221 fprintf(stderr, "Error: %s\n", json_tokener_error_desc(err));
223 if (tokener->char_offset < configuration["properties"].size()) // XXX shouldn't access internal fields
225 //Should handle the extra data here sometime...
228 json_object *propobject = json_object_object_get(rootobject,"properties");
230 g_assert(json_object_get_type(propobject) == json_type_array);
232 array_list *proplist = json_object_get_array(propobject);
234 for(int i=0; i < array_list_length(proplist); i++)
236 json_object *idxobj = (json_object*)array_list_get_idx(proplist,i);
237 std::string prop = json_object_get_string(idxobj);
238 propertiesToSubscribeTo.push_back(prop);
240 DebugOut()<<"DatabaseSink logging: "<<prop<<endl;
243 //json_object_put(propobject);
244 json_object_put(rootobject);
247 void DatabaseSink::stopDb()
252 DBObject *obj = new DBObject();
254 shared->queue.append(obj);
256 g_thread_join(thread);
262 void DatabaseSink::startDb()
266 DebugOut(0)<<"ERROR: tried to start logging during playback. Only logging or playback can be used at one time"<<endl;
272 DebugOut(0)<<"WARNING: logging already started. doing nothing."<<endl;
278 thread = g_thread_new("dbthread", cbFunc, shared);
281 void DatabaseSink::startPlayback()
290 /// populate playback queue:
292 vector<vector<string> > results = shared->db->select("SELECT * FROM "+tablename);
294 /// we are done with shared. clean up:
300 delete playbackShared;
303 playbackShared = new PlaybackShared(routingEngine, uuid(), playbackMultiplier);
305 for(int i=0;i<results.size();i++)
307 if(results[i].size() < 5)
309 throw std::runtime_error("column mismatch in query");
312 DBObject* obj = new DBObject();
314 obj->key = results[i][0];
315 obj->value = results[i][1];
316 obj->source = results[i][2];
317 obj->time = boost::lexical_cast<double>(results[i][3]);
319 /// TODO: figure out why sequence is broken:
321 // obj->sequence = boost::lexical_cast<int>(results[i][4]);
323 playbackShared->playbackQueue.push_back(obj);
326 g_timeout_add(0,getNextEvent,playbackShared);
329 void DatabaseSink::initDb()
331 if(shared) delete shared;
334 shared->db->init(databaseName, tablename, tablecreate);
337 void DatabaseSink::setPlayback(bool v)
339 AsyncSetPropertyRequest request;
340 request.property = DatabasePlayback;
341 request.value = new DatabasePlaybackType(v);
343 setProperty(request);
346 void DatabaseSink::setLogging(bool b)
348 AsyncSetPropertyRequest request;
349 request.property = DatabaseLogging;
350 request.value = new DatabaseLoggingType(b);
352 setProperty(request);
354 delete request.value;
357 void DatabaseSink::setDatabaseFileName(string filename)
359 databaseName = filename;
363 vector<vector<string> > supportedStr = shared->db->select("SELECT DISTINCT key FROM "+tablename);
365 for(int i=0; i < supportedStr.size(); i++)
367 if(!ListPlusPlus<VehicleProperty::Property>(&mSupported).contains(supportedStr[i][0]))
368 mSupported.push_back(supportedStr[i][0]);
374 routingEngine->setSupported(mSupported, this);
377 void DatabaseSink::propertyChanged(AbstractPropertyType *value)
379 VehicleProperty::Property property = value->name;
384 if(!ListPlusPlus<VehicleProperty::Property>(&mSupported).contains(property))
386 mSupported.push_back(property);
387 routingEngine->setSupported(mSupported, this);
390 DBObject* obj = new DBObject;
392 obj->value = value->toString();
393 obj->source = value->sourceUuid;
394 obj->time = value->timestamp;
395 obj->sequence = value->sequence;
397 shared->queue.append(obj);
401 const string DatabaseSink::uuid()
403 return "9f88156e-cb92-4472-8775-9c08addf50d3";
406 void DatabaseSink::getPropertyAsync(AsyncPropertyReply *reply)
408 reply->success = false;
410 if(reply->property == DatabaseFile)
412 DatabaseFileType temp(databaseName);
413 reply->value = &temp;
415 reply->success = true;
416 reply->completed(reply);
420 else if(reply->property == DatabaseLogging)
422 DatabaseLoggingType temp = shared;
424 reply->value = &temp;
425 reply->success = true;
426 reply->completed(reply);
431 else if(reply->property == DatabasePlayback)
433 DatabasePlaybackType temp = playback;
434 reply->value = &temp;
435 reply->success = true;
436 reply->completed(reply);
441 reply->completed(reply);
444 void DatabaseSink::getRangePropertyAsync(AsyncRangePropertyReply *reply)
446 BaseDB * db = new BaseDB();
447 db->init(databaseName, tablename, tablecreate);
452 query<<"SELECT * from "<<tablename<<" WHERE (";
454 for(auto itr = reply->properties.begin(); itr != reply->properties.end(); itr++)
456 if(itr != reply->properties.begin())
459 query<<"key='"<<(*itr)<<"'";
464 if(reply->timeBegin && reply->timeEnd)
466 query<<" time BETWEEN "<<reply->timeBegin<<" AND "<<reply->timeEnd;
469 if(reply->sequenceBegin >= 0 && reply->sequenceEnd >=0)
471 query<<" AND sequence BETWEEN "<<reply->sequenceBegin<<" AND "<<reply->sequenceEnd;
474 std::vector<std::vector<string>> data = db->select(query.str());
476 DebugOut()<<"Dataset size "<<data.size()<<endl;
478 for(auto i=0;i<data.size();i++)
480 if(data[i].size() != 5)
484 dbobj.key = data[i][0];
485 dbobj.value = data[i][1];
486 dbobj.source = data[i][2];
487 dbobj.time = boost::lexical_cast<double>(data[i][3]);
488 dbobj.sequence = boost::lexical_cast<double>(data[i][4]);
490 AbstractPropertyType* property = VehicleProperty::getPropertyTypeForPropertyNameValue(dbobj.key, dbobj.value);
493 property->timestamp = dbobj.time;
494 property->sequence = dbobj.sequence;
496 reply->values.push_back(property);
500 reply->success = true;
501 reply->completed(reply);
506 AsyncPropertyReply *DatabaseSink::setProperty(AsyncSetPropertyRequest request)
508 AsyncPropertyReply* reply = new AsyncPropertyReply(request);
509 reply->success = false;
511 if(request.property == DatabaseLogging)
513 if(request.value->value<bool>())
517 reply->success = true;
518 DatabaseLoggingType temp(true);
519 routingEngine->updateProperty(&temp,uuid());
524 reply->success = true;
525 DatabaseLoggingType temp(false);
526 routingEngine->updateProperty(&temp,uuid());
530 else if(request.property == DatabaseFile)
532 std::string fname = request.value->toString();
534 databaseName = fname;
536 DatabaseFileType temp(databaseName);
538 routingEngine->updateProperty(&temp,uuid());
540 reply->success = true;
542 else if( request.property == DatabasePlayback)
544 if(request.value->value<bool>())
549 DatabasePlaybackType temp(playback);
551 routingEngine->updateProperty(&temp,uuid());
556 playbackShared->stop = true;
560 DatabasePlaybackType temp(playback);
562 routingEngine->updateProperty(&temp,uuid());
565 reply->success = true;
571 void DatabaseSink::subscribeToPropertyChanges(VehicleProperty::Property )
576 void DatabaseSink::unsubscribeToPropertyChanges(VehicleProperty::Property )