added DatabaseLogging property. still needs more completion.
[profile/ivi/automotive-message-broker.git] / plugins / database / databasesink.cpp
1 #include "databasesink.h"
2 #include "abstractroutingengine.h"
3
4 #include <json-glib/json-glib.h>
5
6 extern "C" AbstractSinkManager * create(AbstractRoutingEngine* routingengine, map<string, string> config)
7 {
8         return new DatabaseSinkManager(routingengine, config);
9 }
10
11 DatabaseSink::DatabaseSink(AbstractRoutingEngine *engine, map<std::string, std::string> config)
12         :AbstractSource(engine,config)
13 {
14         databaseName = "storage";
15         tablename = "data";
16         tablecreate = "CREATE TABLE IF NOT EXISTS data (key TEXT, value BLOB, source TEXT, time REAL, sequence REAL)";
17         shared = new Shared;
18         shared->db->init(databaseName, tablename, tablecreate);
19
20         auto cb = [](gpointer data)
21         {
22                 Shared *shared = (Shared*)data;
23
24                 while(1)
25                 {
26                         DBObject* obj = shared->queue.pop();
27
28                         if( obj->quit )
29                         {
30                                 delete obj;
31                                 break;
32                         }
33
34                         DictionaryList<string> dict;
35
36                         NameValuePair<string> one("key", obj->key);
37                         NameValuePair<string> two("value", obj->value);
38                         NameValuePair<string> three("source", obj->source);
39                         NameValuePair<string> four("time", boost::lexical_cast<string>(obj->time));
40                         NameValuePair<string> five("sequence", boost::lexical_cast<string>(obj->sequence));
41
42                         dict.push_back(one);
43                         dict.push_back(two);
44                         dict.push_back(three);
45                         dict.push_back(four);
46                         dict.push_back(five);
47
48                         shared->db->insert(dict);
49                         delete obj;
50                 }
51
52                 void* ret = NULL;
53                 return ret;
54         };
55
56         thread = g_thread_new("dbthread", cb, shared);
57
58         parseConfig();
59
60         for(auto itr=propertiesToSubscribeTo.begin();itr!=propertiesToSubscribeTo.end();itr++)
61         {
62                 engine->subscribeToProperty(*itr,this);
63         }
64
65 }
66
67 DatabaseSink::~DatabaseSink()
68 {
69         DBObject* obj = new DBObject();
70         obj->quit = true;
71
72         shared->queue.append(obj);
73
74         g_thread_join(thread);
75
76         delete shared;
77 }
78
79
80 void DatabaseSink::supportedChanged(PropertyList supportedProperties)
81 {
82
83 }
84
85 PropertyList DatabaseSink::supported()
86 {
87         PropertyList props;
88
89         props.push_back(VehicleProperty::EngineSpeed);
90         props.push_back(VehicleProperty::VehicleSpeed);
91         props.push_back(DatabaseLoggingProperty);
92
93         return props;
94 }
95
96 void DatabaseSink::parseConfig()
97 {
98         JsonParser* parser = json_parser_new();
99         GError* error = nullptr;
100         if(!json_parser_load_from_data(parser, configuration["properties"].c_str(),configuration["properties"].size(), &error))
101         {
102                 DebugOut()<<"Failed to load config: "<<error->message;
103                 throw std::runtime_error("Failed to load config");
104         }
105
106         JsonNode* node = json_parser_get_root(parser);
107
108         if(node == nullptr)
109                 throw std::runtime_error("Unable to get JSON root object");
110
111         JsonReader* reader = json_reader_new(node);
112
113         if(reader == nullptr)
114                 throw std::runtime_error("Unable to create JSON reader");
115
116         json_reader_read_member(reader,"properties");
117
118         g_assert(json_reader_is_array(reader));
119
120         for(int i=0; i < json_reader_count_elements(reader); i++)
121         {
122                 json_reader_read_element(reader, i);
123                 std::string prop = json_reader_get_string_value(reader);
124                 propertiesToSubscribeTo.push_back(prop);
125                 json_reader_end_element(reader);
126
127                 DebugOut()<<"DatabaseSink logging: "<<prop<<endl;
128         }
129
130         if(error) g_error_free(error);
131
132         g_object_unref(reader);
133         g_object_unref(parser);
134 }
135
136 void DatabaseSink::propertyChanged(VehicleProperty::Property property, AbstractPropertyType *value, std::string uuid)
137 {
138         DBObject* obj = new DBObject;
139         obj->key = property;
140         obj->value = value->toString();
141         obj->source = uuid;
142         obj->time = value->timestamp;
143         obj->sequence = value->sequence;
144
145         shared->queue.append(obj);
146 }
147
148
149 std::string DatabaseSink::uuid()
150 {
151         return "9f88156e-cb92-4472-8775-9c08addf50d3";
152 }
153
154 void DatabaseSink::getPropertyAsync(AsyncPropertyReply *reply)
155 {
156
157 }
158
159 void DatabaseSink::getRangePropertyAsync(AsyncRangePropertyReply *reply)
160 {
161         BaseDB * db = new BaseDB();
162         db->init(databaseName, tablename, tablecreate);
163
164         ostringstream query;
165         query.precision(15);
166
167         query<<"SELECT * from "<<tablename<<" WHERE ";
168
169         if(reply->timeBegin && reply->timeEnd)
170         {
171                 query<<" time BETWEEN "<<reply->timeBegin<<" AND "<<reply->timeEnd;
172         }
173
174         if(reply->sequenceBegin >= 0 && reply->sequenceEnd >=0)
175         {
176                 query<<" AND sequence BETWEEN "<<reply->sequenceBegin<<" AND "<<reply->sequenceEnd;
177         }
178
179         std::vector<std::vector<string>> data = db->select(query.str());
180
181         std::list<AbstractPropertyType*> cleanup;
182
183         for(auto i=0;i<data.size();i++)
184         {
185                 if(data[i].size() != 5)
186                         continue;
187
188                 DBObject dbobj;
189                 dbobj.key = data[i][0];
190                 dbobj.value = data[i][1];
191                 dbobj.source = data[i][2];
192                 dbobj.time = boost::lexical_cast<double>(data[i][3]);
193                 dbobj.sequence = boost::lexical_cast<double>(data[i][4]);
194
195                 AbstractPropertyType* property = VehicleProperty::getPropertyTypeForPropertyNameValue(dbobj.key, dbobj.value);
196                 if(property)
197                 {
198                         property->timestamp = dbobj.time;
199                         property->sequence = dbobj.sequence;
200
201                         reply->values.push_back(property);
202                         cleanup.push_back(property);
203                 }
204         }
205
206         reply->success = true;
207         reply->completed(reply);
208
209         /// reply is owned by the requester of this call.  we own the data:
210         for(auto itr = cleanup.begin(); itr != cleanup.end(); itr++)
211         {
212                 delete *itr;
213         }
214
215         delete db;
216 }
217
218 AsyncPropertyReply *DatabaseSink::setProperty(AsyncSetPropertyRequest request)
219 {
220         AsyncPropertyReply* reply = new AsyncPropertyReply(request);
221         reply->success = false;
222
223         if(request.property == DatabaseLoggingProperty)
224         {
225                 if(request.value->value<bool>())
226                 {
227                         ///TODO: start or stop logging thread
228                 }
229         }
230
231         return reply;
232 }
233
234 void DatabaseSink::subscribeToPropertyChanges(VehicleProperty::Property )
235 {
236
237 }
238
239 void DatabaseSink::unsubscribeToPropertyChanges(VehicleProperty::Property )
240 {
241 }