X-Git-Url: http://review.tizen.org/git/?a=blobdiff_plain;f=plugins%2Fdatabase%2Fdatabasesink.cpp;h=8b3b0c6ddac7477ed08cfb0603061555b5cce48d;hb=c29570fe11555e886f92215b4338de8fca527faa;hp=abb7befd2302390a775a19fd52990188b4c3e4e6;hpb=40f12a897644a69f5b08d957cc4047421d9f1979;p=profile%2Fivi%2Fautomotive-message-broker.git diff --git a/plugins/database/databasesink.cpp b/plugins/database/databasesink.cpp index abb7bef..8b3b0c6 100644 --- a/plugins/database/databasesink.cpp +++ b/plugins/database/databasesink.cpp @@ -1,80 +1,533 @@ #include "databasesink.h" +#include "abstractroutingengine.h" +#include "listplusplus.h" +#include "superptr.hpp" +#include "uuidhelper.h" +#include "ambplugin.h" -DatabaseSink::DatabaseSink(AbstractRoutingEngine *engine, map config) - :AbstractSink(engine,config) +#include + +int bufferLength = 100; +int timeout=1000; + +extern "C" void create(AbstractRoutingEngine* routingengine, map config) { - shared = new Shared; - shared->db->init("storage","data","CREATE TABLE IF NOT EXISTS vehicledata (key TEXT, value BLOB, time REAL, source TEXT"); + auto plugin = new AmbPlugin(routingengine, config); + plugin->init(); +} + +static void * cbFunc(Shared* shared) +{ + if(!shared) + { + throw std::runtime_error("Could not cast shared object."); + } + + ///new tripID: + shared->tripId = amb::createUuid(); + + vector > insertList; - auto cb = [](gpointer data) + while(1) { - Shared *shared = (Shared*)data; + usleep(timeout*1000); - while(1) + DBObject obj = shared->queue.pop(); + + if( obj.quit ) { - DBObject* obj = shared->queue.pop(); + break; + } + + DictionaryList dict; - if( obj->quit ) + NameValuePair one("key", obj.key); + NameValuePair two("value", obj.value); + NameValuePair three("source", obj.source); + NameValuePair zone("zone", boost::lexical_cast(obj.zone)); + NameValuePair four("time", boost::lexical_cast(obj.time)); + NameValuePair five("sequence", boost::lexical_cast(obj.sequence)); + NameValuePair six("tripId", boost::lexical_cast(shared->tripId)); + + dict.push_back(one); + dict.push_back(two); + dict.push_back(three); + dict.push_back(zone); + dict.push_back(four); + dict.push_back(five); + dict.push_back(six); + + insertList.push_back(dict); + + if(insertList.size() > bufferLength) + { + shared->db->exec("BEGIN IMMEDIATE TRANSACTION"); + for(int i=0; i< insertList.size(); i++) { - break; + DictionaryList d = insertList[i]; + shared->db->insert(d); } + shared->db->exec("END TRANSACTION"); + insertList.clear(); + } + //delete obj; + } + + /// final flush of whatever is still in the queue: - DictionaryList dict; + shared->db->exec("BEGIN IMMEDIATE TRANSACTION"); + for(int i=0; i< insertList.size(); i++) + { + DictionaryList d = insertList[i]; + shared->db->insert(d); + } + shared->db->exec("END TRANSACTION"); + + return NULL; +} + +int getNextEvent(gpointer data) +{ + PlaybackShared* pbshared = static_cast(data); - NameValuePair one("key", obj->key); - NameValuePair two("value", obj->value); - NameValuePair three("source", obj->source); - NameValuePair four("time", boost::lexical_cast(obj->time)); - NameValuePair five("sequence", boost::lexical_cast(obj->sequence)); + if(!pbshared) + throw std::runtime_error("failed to cast PlaybackShared object"); - dict.push_back(one); - dict.push_back(two); - dict.push_back(three); - dict.push_back(four); - dict.push_back(five); + if(pbshared->stop) + return 0; - shared->db->insert(dict); - delete obj; + auto itr = pbshared->playbackQueue.begin(); + + if(itr == pbshared->playbackQueue.end()) + { + return 0; + } + + DBObject obj = *itr; + + auto value = amb::make_unique(VehicleProperty::getPropertyTypeForPropertyNameValue(obj.key, obj.value)); + + if(value) + { + value->priority = AbstractPropertyType::Instant; + value->timestamp = obj.time; + value->sequence = obj.sequence; + value->sourceUuid = obj.source; + value->zone = obj.zone; + pbshared->routingEngine->updateProperty(value.get(), pbshared->uuid); + } + + if(++itr != pbshared->playbackQueue.end()) + { + DBObject o2 = *itr; + double t = o2.time - obj.time; + + if(t > 0) + g_timeout_add((t*1000) / pbshared->playBackMultiplier, getNextEvent, pbshared); + else + g_timeout_add(1, getNextEvent, pbshared); + } + + pbshared->playbackQueue.remove(obj); + DebugOut()<<"playback Queue size: "<playbackQueue.size()< config, AbstractSource &parent) + :AmbPluginImpl(engine, config, parent), shared(nullptr), playback(false), playbackShared(nullptr), playbackMultiplier(1) +{ + tablename = "data"; + tablecreate = database_table_create; + + if(config.find("bufferLength") != config.end()) + { + bufferLength = boost::lexical_cast(config["bufferLength"]); + } + + if(config.find("frequency") != config.end()) + { + try + { + int t = boost::lexical_cast(config["frequency"]); + timeout = 1000 / t; + }catch(...) + { + DebugOut(DebugOut::Error)<<"Failed to parse frequency: Invalid value "<subscribeToProperty(itr, &parent); + } + databaseName = addPropertySupport(Zone::None, [](){ return new DatabaseFileType("storage"); }); + playback = addPropertySupport(Zone::None, [](){ return new DatabasePlaybackType(false); }); + databaseLogging = addPropertySupport(Zone::None, [](){ return new DatabaseLoggingType(false); }); + + if(config.find("startOnLoad")!= config.end()) + { + databaseLogging->setValue(config["startOnLoad"] == "true"); + } + + if(config.find("playbackMultiplier")!= config.end()) + { + playbackMultiplier = boost::lexical_cast(config["playbackMultiplier"]); + } + + if(config.find("playbackOnLoad")!= config.end()) + { + playback->setValue(config["playbackOnLoad"] == "true"); + } } DatabaseSink::~DatabaseSink() { + if(shared) + { + stopDb(); + } + if(playbackShared) + { + delete playbackShared; + } } -PropertyList DatabaseSink::subscriptions() +void DatabaseSink::supportedChanged(const PropertyList &supportedProperties) { } +void DatabaseSink::parseConfig() +{ + json_object *rootobject; + json_tokener *tokener = json_tokener_new(); + enum json_tokener_error err; + do + { + rootobject = json_tokener_parse_ex(tokener, configuration["properties"].c_str(),configuration["properties"].size()); + } while ((err = json_tokener_get_error(tokener)) == json_tokener_continue); + if (err != json_tokener_success) + { + fprintf(stderr, "Error: %s\n", json_tokener_error_desc(err)); + } + if (tokener->char_offset < configuration["properties"].size()) // XXX shouldn't access internal fields + { + //Should handle the extra data here sometime... + } + + json_object *propobject = json_object_object_get(rootobject,"properties"); + + g_assert(json_object_get_type(propobject) == json_type_array); + + array_list *proplist = json_object_get_array(propobject); + + for(int i=0; i < array_list_length(proplist); i++) + { + json_object *idxobj = (json_object*)array_list_get_idx(proplist,i); + std::string prop = json_object_get_string(idxobj); + propertiesToSubscribeTo.push_back(prop); -void DatabaseSink::supportedChanged(PropertyList supportedProperties) + DebugOut()<<"DatabaseSink logging: "<queue.append(obj); + + if(thread && thread->joinable()) + thread->join(); + delete shared; + shared = NULL; } +void DatabaseSink::startDb() +{ + if(playback->value()) + { + DebugOut(0)<<"ERROR: tried to start logging during playback. Only logging or playback can be used at one time"<joinable()) + thread->detach(); -void DatabaseSink::propertyChanged(VehicleProperty::Property property, AbstractPropertyType *value, std::string uuid) + thread = amb::make_unique(new std::thread(cbFunc, shared)); +} + +void DatabaseSink::startPlayback() { - DBObject* obj = new DBObject; - obj->key = property; - obj->value = value->toString(); - obj->source = uuid; - obj->time = value->timestamp; - obj->sequence = value->sequence; + if(playback->value()) + return; + + playback->setValue(true); + + initDb(); + + /// populate playback queue: + + vector > results = shared->db->select("SELECT * FROM "+tablename); + + /// we are done with shared. clean up: + delete shared; + shared = NULL; + + if(playbackShared) + { + delete playbackShared; + } + + playbackShared = new PlaybackShared(routingEngine, uuid(), playbackMultiplier); + + for(int i=0;i(results[i][3]); + obj.time = boost::lexical_cast(results[i][4]); + obj.sequence = boost::lexical_cast(results[i][5]); + + playbackShared->playbackQueue.push_back(obj); + } + + g_timeout_add(0, getNextEvent, playbackShared); +} + +void DatabaseSink::initDb() +{ + if(shared) delete shared; + + shared = new Shared; + shared->db->init(databaseName->value(), tablename, tablecreate); +} + +void DatabaseSink::setDatabaseFileName(string filename) +{ + initDb(); + + vector > supportedStr = shared->db->select("SELECT DISTINCT key, zone, source FROM " + tablename); + + for(int i=0; i < supportedStr.size(); i++) + { + std::string name = supportedStr[i][0]; + + if(!contains(supported(), name)) + { + std::string zoneStr = supportedStr[i][1]; + std::string sourceStr = supportedStr[i][2]; + + DebugOut() << "adding property " << name << " in zone: " << zoneStr << "for source: " << sourceStr << endl; + + Zone::Type zone = boost::lexical_cast(zoneStr); + auto property = addPropertySupport(zone, [name]() { return VehicleProperty::getPropertyTypeForPropertyNameValue(name); }); + property->sourceUuid = sourceStr; + } + } + + delete shared; + shared = NULL; + + routingEngine->updateSupported(supported(), PropertyList(), &source); +} + +void DatabaseSink::propertyChanged(AbstractPropertyType *value) +{ + VehicleProperty::Property property = value->name; + + if(!shared) + return; + + if(!contains(supported(), property)) + { + addPropertySupport(value->zone, [property]() { return VehicleProperty::getPropertyTypeForPropertyNameValue(property);}); + routingEngine->updateSupported(supported(), PropertyList(), &source); + } + + DBObject obj; + obj.key = property; + obj.value = value->toString(); + obj.source = value->sourceUuid; + obj.time = value->timestamp; + obj.sequence = value->sequence; + obj.zone = value->zone; + + shared->queue.append(obj); } -std::string DatabaseSink::uuid() +const std::string DatabaseSink::uuid() const { return "9f88156e-cb92-4472-8775-9c08addf50d3"; } + +void DatabaseSink::init() +{ + if(configuration.find("databaseFile") != configuration.end()) + { + databaseName->setValue(configuration["databaseFile"]); + setDatabaseFileName(configuration["databaseFile"]); + } + + routingEngine->updateSupported(supported(), PropertyList(), &source); +} + +void DatabaseSink::getRangePropertyAsync(AsyncRangePropertyReply *reply) +{ + BaseDB * db = new BaseDB(); + db->init(databaseName->value(), tablename, tablecreate); + + ostringstream query; + query.precision(15); + + query<<"SELECT * from "<properties.begin(); itr != reply->properties.end(); itr++) + { + DebugOut() << "prop: " << (*itr) << endl; + if(itr != reply->properties.begin()) + query<<" OR "; + + query<<"key='"<<(*itr)<<"'"; + } + + query<<")"; + + if(reply->timeEnd) + { + query<<" AND time BETWEEN "<timeBegin<<" AND "<timeEnd; + } + + if(reply->sequenceBegin >= 0 && reply->sequenceEnd >=0) + { + query<<" AND sequence BETWEEN "<sequenceBegin<<" AND "<sequenceEnd; + } + + if(reply->sourceUuid != "") + query<<" AND source='"<sourceUuid<<"'"; + + query<<" AND zone="<zone; + + std::vector> data = db->select(query.str()); + + DebugOut()<<"Dataset size "<success = false; + reply->error = AsyncPropertyReply::InvalidOperation; + } + else + { + reply->success = true; + } + + for(auto i=0; i(data[i][3]); + dbobj.time = boost::lexical_cast(data[i][4]); + dbobj.sequence = boost::lexical_cast(data[i][5]); + dbobj.tripId = data[i][6]; + + AbstractPropertyType* property = VehicleProperty::getPropertyTypeForPropertyNameValue(dbobj.key, dbobj.value); + if(property) + { + property->timestamp = dbobj.time; + property->sequence = dbobj.sequence; + + reply->values.push_back(property); + } + } + + + reply->completed(reply); + + delete db; +} + +AsyncPropertyReply *DatabaseSink::setProperty(AsyncSetPropertyRequest request) +{ + AsyncPropertyReply* reply = AmbPluginImpl::setProperty(request); + + if(request.property == DatabaseLogging) + { + if(request.value->value()) + { + startDb(); + } + else + { + stopDb(); + } + } + else if(request.property == DatabaseFile) + { + setDatabaseFileName(databaseName->value()); + } + else if( request.property == DatabasePlayback) + { + if(request.value->value()) + { + startPlayback(); + } + else + { + if(playbackShared) + playbackShared->stop = true; + + playback = false; + } + } + + return reply; +} + +void DatabaseSink::subscribeToPropertyChanges(VehicleProperty::Property ) +{ + +} + +void DatabaseSink::unsubscribeToPropertyChanges(VehicleProperty::Property ) +{ +} +