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