1 #include "databasesink.h"
2 #include "abstractroutingengine.h"
3 #include "listplusplus.h"
5 //#include <json-glib/json-glib.h>
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.");
23 DBObject* obj = shared->queue.pop();
31 DictionaryList<string> dict;
33 NameValuePair<string> one("key", obj->key);
34 NameValuePair<string> two("value", obj->value);
35 NameValuePair<string> three("source", obj->source);
36 NameValuePair<string> four("time", boost::lexical_cast<string>(obj->time));
37 NameValuePair<string> five("sequence", boost::lexical_cast<string>(obj->sequence));
41 dict.push_back(three);
45 shared->db->insert(dict);
52 int getNextEvent(gpointer data)
54 PlaybackShared* pbshared = static_cast<PlaybackShared*>(data);
57 throw std::runtime_error("failed to cast PlaybackShared object");
59 auto itr = pbshared->playbackQueue.begin();
61 if(itr == pbshared->playbackQueue.end())
68 AbstractPropertyType* value = VehicleProperty::getPropertyTypeForPropertyNameValue(obj->key,obj->value);
72 pbshared->routingEngine->updateProperty(obj->key, value, pbshared->uuid);
73 value->timestamp = obj->time;
74 value->sequence = obj->sequence;
77 if(++itr != pbshared->playbackQueue.end())
80 double t = o2->time - obj->time;
83 g_timeout_add(t*1000, getNextEvent, pbshared);
85 g_timeout_add(t, getNextEvent, pbshared);
88 pbshared->playbackQueue.remove(obj);
94 DatabaseSink::DatabaseSink(AbstractRoutingEngine *engine, map<std::string, std::string> config)
95 :AbstractSource(engine,config),thread(NULL),shared(NULL),playback(false),playbackShared(NULL)
97 databaseName = "storage";
99 tablecreate = "CREATE TABLE IF NOT EXISTS data (key TEXT, value BLOB, source TEXT, time REAL, sequence REAL)";
103 if(config.find("startOnLoad")!= config.end())
110 for(auto itr=propertiesToSubscribeTo.begin();itr!=propertiesToSubscribeTo.end();itr++)
112 engine->subscribeToProperty(*itr,this);
115 mSupported.push_back(DatabaseFileProperty);
116 mSupported.push_back(DatabaseLoggingProperty);
117 mSupported.push_back(DatabasePlaybackProperty);
119 routingEngine->setSupported(mSupported,this);
123 DatabaseSink::~DatabaseSink()
127 DBObject* obj = new DBObject();
130 shared->queue.append(obj);
132 g_thread_join(thread);
133 g_thread_unref(thread);
139 void DatabaseSink::supportedChanged(PropertyList supportedProperties)
144 PropertyList DatabaseSink::supported()
149 void DatabaseSink::parseConfig()
151 json_object *rootobject;
152 json_tokener *tokener = json_tokener_new();
153 enum json_tokener_error err;
156 rootobject = json_tokener_parse_ex(tokener, configuration["properties"].c_str(),configuration["properties"].size());
157 } while ((err = json_tokener_get_error(tokener)) == json_tokener_continue);
158 if (err != json_tokener_success)
160 fprintf(stderr, "Error: %s\n", json_tokener_error_desc(err));
162 if (tokener->char_offset < configuration["properties"].size()) // XXX shouldn't access internal fields
164 //Should handle the extra data here sometime...
167 json_object *propobject = json_object_object_get(rootobject,"properties");
169 g_assert(json_object_get_type(propobject) == json_type_array);
171 array_list *proplist = json_object_get_array(propobject);
173 for(int i=0; i < array_list_length(proplist); i++)
175 json_object *idxobj = (json_object*)array_list_get_idx(proplist,i);
176 std::string prop = json_object_get_string(idxobj);
177 propertiesToSubscribeTo.push_back(prop);
179 DebugOut()<<"DatabaseSink logging: "<<prop<<endl;
182 json_object_put(propobject);
183 json_object_put(rootobject);
186 void DatabaseSink::stopDb()
191 DBObject *obj = new DBObject();
193 shared->queue.append(obj);
195 g_thread_join(thread);
201 void DatabaseSink::startDb()
205 DebugOut(0)<<"ERROR: tried to start logging during playback. Only logging or playback can be used at one time"<<endl;
211 DebugOut(0)<<"WARNING: logging already started. doing nothing."<<endl;
217 // thread = g_thread_new("dbthread", cbFunc, shared);
220 void DatabaseSink::startPlayback()
231 vector<vector<string> > supportedStr = shared->db->select("SELECT DISTINCT key FROM "+tablename);
233 for(int i=0; i < supportedStr.size(); i++)
235 if(!ListPlusPlus<VehicleProperty::Property>(&mSupported).contains(supportedStr[i][0]))
236 mSupported.push_back(supportedStr[i][0]);
239 routingEngine->setSupported(supported(), this);
241 /// populate playback queue:
243 vector<vector<string> > results = shared->db->select("SELECT * FROM "+tablename);
247 delete playbackShared;
250 playbackShared = new PlaybackShared(routingEngine,uuid());
252 for(int i=0;i<results.size();i++)
254 if(results[i].size() < 5)
256 throw std::runtime_error("column mismatch in query");
259 DBObject* obj = new DBObject();
261 obj->key = results[i][0];
262 obj->value = results[i][1];
263 obj->source = results[i][2];
264 obj->time = boost::lexical_cast<double>(results[i][3]);
265 // obj->sequence = boost::lexical_cast<int>(results[i][4]);
267 playbackShared->playbackQueue.push_back(obj);
270 g_timeout_add(0,getNextEvent,playbackShared);
273 void DatabaseSink::initDb()
275 if(shared) delete shared;
278 shared->db->init(databaseName, tablename, tablecreate);
281 void DatabaseSink::propertyChanged(VehicleProperty::Property property, AbstractPropertyType *value, std::string uuid)
286 DBObject* obj = new DBObject;
288 obj->value = value->toString();
290 obj->time = value->timestamp;
291 obj->sequence = value->sequence;
293 shared->queue.append(obj);
297 std::string DatabaseSink::uuid()
299 return "9f88156e-cb92-4472-8775-9c08addf50d3";
302 void DatabaseSink::getPropertyAsync(AsyncPropertyReply *reply)
304 reply->success = false;
306 if(reply->property == DatabaseFileProperty)
308 StringPropertyType temp(databaseName);
309 reply->value = &temp;
311 reply->success = true;
312 reply->completed(reply);
316 else if(reply->property == DatabaseLoggingProperty)
318 BasicPropertyType<bool> temp = shared;
320 reply->value = &temp;
321 reply->success = true;
322 reply->completed(reply);
327 else if(reply->property == DatabasePlaybackProperty)
329 BasicPropertyType<bool> temp = playback;
330 reply->value = &temp;
331 reply->success = true;
332 reply->completed(reply);
337 reply->completed(reply);
340 void DatabaseSink::getRangePropertyAsync(AsyncRangePropertyReply *reply)
342 BaseDB * db = new BaseDB();
343 db->init(databaseName, tablename, tablecreate);
348 query<<"SELECT * from "<<tablename<<" WHERE ";
350 if(reply->timeBegin && reply->timeEnd)
352 query<<" time BETWEEN "<<reply->timeBegin<<" AND "<<reply->timeEnd;
355 if(reply->sequenceBegin >= 0 && reply->sequenceEnd >=0)
357 query<<" AND sequence BETWEEN "<<reply->sequenceBegin<<" AND "<<reply->sequenceEnd;
360 std::vector<std::vector<string>> data = db->select(query.str());
362 std::list<AbstractPropertyType*> cleanup;
364 for(auto i=0;i<data.size();i++)
366 if(data[i].size() != 5)
370 dbobj.key = data[i][0];
371 dbobj.value = data[i][1];
372 dbobj.source = data[i][2];
373 dbobj.time = boost::lexical_cast<double>(data[i][3]);
374 dbobj.sequence = boost::lexical_cast<double>(data[i][4]);
376 AbstractPropertyType* property = VehicleProperty::getPropertyTypeForPropertyNameValue(dbobj.key, dbobj.value);
379 property->timestamp = dbobj.time;
380 property->sequence = dbobj.sequence;
382 reply->values.push_back(property);
383 cleanup.push_back(property);
387 reply->success = true;
388 reply->completed(reply);
390 /// reply is owned by the requester of this call. we own the data:
391 for(auto itr = cleanup.begin(); itr != cleanup.end(); itr++)
399 AsyncPropertyReply *DatabaseSink::setProperty(AsyncSetPropertyRequest request)
401 AsyncPropertyReply* reply = new AsyncPropertyReply(request);
402 reply->success = false;
404 if(request.property == DatabaseLoggingProperty)
406 if(request.value->value<bool>())
408 ///TODO: start or stop logging thread
410 reply->success = true;
411 BasicPropertyType<bool> temp(true);
412 routingEngine->updateProperty(DatabaseLoggingProperty,&temp,uuid());
417 reply->success = true;
418 BasicPropertyType<bool> temp(false);
419 routingEngine->updateProperty(DatabaseLoggingProperty,&temp,uuid());
423 else if(request.property == DatabaseFileProperty)
425 std::string fname = request.value->toString();
427 databaseName = fname;
429 StringPropertyType temp(databaseName);
431 routingEngine->updateProperty(DatabaseFileProperty,&temp,uuid());
433 reply->success = true;
435 else if( request.property == DatabasePlaybackProperty)
437 if(request.value->value<bool>())
441 BasicPropertyType<bool> temp(true);
443 routingEngine->updateProperty(DatabasePlaybackProperty,&temp,uuid());
447 /// TODO: stop playback
449 BasicPropertyType<bool> temp(true);
451 routingEngine->updateProperty(DatabasePlaybackProperty,&temp,uuid());
454 reply->success = true;
460 void DatabaseSink::subscribeToPropertyChanges(VehicleProperty::Property )
465 void DatabaseSink::unsubscribeToPropertyChanges(VehicleProperty::Property )