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(obj->key, 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();
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);
355 void DatabaseSink::setDatabaseFileName(string filename)
357 databaseName = filename;
361 vector<vector<string> > supportedStr = shared->db->select("SELECT DISTINCT key FROM "+tablename);
363 for(int i=0; i < supportedStr.size(); i++)
365 if(!ListPlusPlus<VehicleProperty::Property>(&mSupported).contains(supportedStr[i][0]))
366 mSupported.push_back(supportedStr[i][0]);
372 routingEngine->setSupported(mSupported, this);
375 void DatabaseSink::propertyChanged(VehicleProperty::Property property, AbstractPropertyType *value, std::string uuid)
380 if(!ListPlusPlus<VehicleProperty::Property>(&mSupported).contains(property))
382 mSupported.push_back(property);
383 routingEngine->setSupported(mSupported, this);
386 DBObject* obj = new DBObject;
388 obj->value = value->toString();
390 obj->time = value->timestamp;
391 obj->sequence = value->sequence;
393 shared->queue.append(obj);
397 std::string DatabaseSink::uuid()
399 return "9f88156e-cb92-4472-8775-9c08addf50d3";
402 void DatabaseSink::getPropertyAsync(AsyncPropertyReply *reply)
404 reply->success = false;
406 if(reply->property == DatabaseFile)
408 DatabaseFileType temp(databaseName);
409 reply->value = &temp;
411 reply->success = true;
412 reply->completed(reply);
416 else if(reply->property == DatabaseLogging)
418 DatabaseLoggingType temp = shared;
420 reply->value = &temp;
421 reply->success = true;
422 reply->completed(reply);
427 else if(reply->property == DatabasePlayback)
429 DatabasePlaybackType temp = playback;
430 reply->value = &temp;
431 reply->success = true;
432 reply->completed(reply);
437 reply->completed(reply);
440 void DatabaseSink::getRangePropertyAsync(AsyncRangePropertyReply *reply)
442 BaseDB * db = new BaseDB();
443 db->init(databaseName, tablename, tablecreate);
448 query<<"SELECT * from "<<tablename<<" WHERE key='"<<reply->property<<"' AND";
450 if(reply->timeBegin && reply->timeEnd)
452 query<<" time BETWEEN "<<reply->timeBegin<<" AND "<<reply->timeEnd;
455 if(reply->sequenceBegin >= 0 && reply->sequenceEnd >=0)
457 query<<" AND sequence BETWEEN "<<reply->sequenceBegin<<" AND "<<reply->sequenceEnd;
460 std::vector<std::vector<string>> data = db->select(query.str());
462 std::list<AbstractPropertyType*> cleanup;
464 for(auto i=0;i<data.size();i++)
466 if(data[i].size() != 5)
470 dbobj.key = data[i][0];
471 dbobj.value = data[i][1];
472 dbobj.source = data[i][2];
473 dbobj.time = boost::lexical_cast<double>(data[i][3]);
474 dbobj.sequence = boost::lexical_cast<double>(data[i][4]);
476 AbstractPropertyType* property = VehicleProperty::getPropertyTypeForPropertyNameValue(dbobj.key, dbobj.value);
479 property->timestamp = dbobj.time;
480 property->sequence = dbobj.sequence;
482 reply->values.push_back(property);
483 cleanup.push_back(property);
487 reply->success = true;
488 reply->completed(reply);
493 AsyncPropertyReply *DatabaseSink::setProperty(AsyncSetPropertyRequest request)
495 AsyncPropertyReply* reply = new AsyncPropertyReply(request);
496 reply->success = false;
498 if(request.property == DatabaseLogging)
500 if(request.value->value<bool>())
504 reply->success = true;
505 DatabaseLoggingType temp(true);
506 routingEngine->updateProperty(DatabaseLogging,&temp,uuid());
511 reply->success = true;
512 DatabaseLoggingType temp(false);
513 routingEngine->updateProperty(DatabaseLogging,&temp,uuid());
517 else if(request.property == DatabaseFile)
519 std::string fname = request.value->toString();
521 databaseName = fname;
523 DatabaseFileType temp(databaseName);
525 routingEngine->updateProperty(DatabaseFile,&temp,uuid());
527 reply->success = true;
529 else if( request.property == DatabasePlayback)
531 if(request.value->value<bool>())
536 DatabasePlaybackType temp(playback);
538 routingEngine->updateProperty(DatabasePlayback,&temp,uuid());
543 playbackShared->stop = true;
547 DatabasePlaybackType temp(playback);
549 routingEngine->updateProperty(DatabasePlayback, &temp, uuid());
552 reply->success = true;
558 void DatabaseSink::subscribeToPropertyChanges(VehicleProperty::Property )
563 void DatabaseSink::unsubscribeToPropertyChanges(VehicleProperty::Property )