-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPOPSensor.cc
373 lines (332 loc) · 10.2 KB
/
POPSensor.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/**
*
*
* @author Laurent Winkler based on work by Valentin Bourqui
* @date Dec 2014
* @brief POPSensor class for the POPWIN project. This object handles the data gathering of a group of sensors.
*
*
*/
#include "POPSensor.ph"
#include "SensorProxy.ph"
#include <unistd.h>
#include <fstream>
#include <json/json.h>
#include <json/reader.h>
using namespace std;
/// Constructor (URL of target platteform is specified)
POPSensor::POPSensor(const std::string& x_url, const std::string& x_resourceFileName, const int id)
{
PopSID = 10000*id;
cout<<"Creating POPSensor with id="<< PopSID << popcendl;
Initialize(x_resourceFileName);
}
/// Constructor (power requirement of target platteform is specified)
POPSensor::POPSensor(int x_pow, const std::string& x_resourceFileName, const int id)
{
PopSID = 10000*id;
cout<<"Creating POPSensor with id="<< PopSID << popcendl;
Initialize(x_resourceFileName);
}
/// Destructor
POPSensor::~POPSensor()
{
StopListening();
m_jsonResources = "";
cout<<"Destroying POPSensor and its "<<m_sensorsProxy.size() << " SensorProxy." <<popcendl;
SubscribeToResources(false); // unsubscribe
for(auto it : m_sensorsProxy)
{
it->UnPublish(MSR_SET_GW); // this one is not from JSON file, cf. Initialize()
//delete(it);
}
m_sensorsProxy.clear();
cout<<"Finished destroying POPSensor" << popcendl;
}
/// Initialization using parameters in resource.json
void POPSensor::Initialize(const std::string& x_resourceFileName)
{
// Read json resource file into string
ifstream jif(x_resourceFileName);
if(!jif.is_open())
throw POPException("Cannot open json resource file", argv[1]);
stringstream ss;
ss << jif.rdbuf();
jif.close();
// Read json resource file
m_jsonResources = ss.str();
Json::Reader reader;
Json::Value root;
if (!reader.parse(m_jsonResources, root, false))
{
throw POPException("Error while reading json string"); // , m_jsonResources); // note: JSON string may be too long for buffer
}
int counter = 0;
for(int i = 0 ; i < root["gateways"].size() ; i++)
{
string connectionType = root["gateways"][i].get("connection", "<not found>").asString();
string url = root["gateways"][i].get("url", "localhost").asString();
// TODO: redesigne because in theory multiple GW per POPSensor possible, but not now
string gwID = root["gateways"][i].get("id", "0").asString();
if(connectionType == "usb")
{
for(int j = 0 ; j < 4 ; j++)
{
// Scan usb ports for connected gateways
stringstream port;
port << "/dev/ttyUSB" << j;
try
{
m_sensorsProxy.push_back(new SensorProxy(PopSID + 1000 + counter, url, port.str()));
cout<<"Creating sensor proxy with id="<<(PopSID + 1000 + counter)<<" on port "<<port.str()<<popcendl;
counter++;
}
catch(...)
{
// cout<<"Cannot create a sensor proxy on port "<<port.str()<<popcendl;
}
}
}
else throw POPException("Only \"usb\" connection is supported for gateway", "connection=" + connectionType);
cout<<"Created "<<m_sensorsProxy.size()<<" sensor proxy objects"<<popcendl;
for(auto it : m_sensorsProxy) // should be only one for now, else error
{
it->Publish(MSR_SET_GW);
it->SetAsGateway(stoi(gwID));
}
}
if(m_sensorsProxy.empty())
throw POPException("No sensor proxy could be create. Did you connect the gateway mote via USB ?");
StartListening();
SubscribeToResources(true); // subscribe
// Send a command to the gateway mote to set it as the gateway
// note: since some mote have trouble with the serial line you may need to set it manually later
//for(auto it : m_sensorsProxy)
//{
//it->Publish(MSR_SET_GW);
//it->Publish(PUB_COMMAND, 8); // 8 is the command id for set_as
//it->Notify(MSR_SET_GW, UNT_NONE, 0);
//}
}
/// Return true if the POPSensor is connected to at least one sensor
bool POPSensor::IsConnected()
{
return !m_sensorsProxy.empty();
}
/// Start listening to messages coming from sensors
void POPSensor::StartListening()
{
for(auto it : m_sensorsProxy)
{
it->StartListening();
}
}
/// Stop listening to messages coming from sensors
void POPSensor::StopListening()
{
for(auto it : m_sensorsProxy)
{
it->StopListening();
}
}
/// Return a POPSensorData structure containing the messages received from sensors
POPSensorData POPSensor::Gather()
{
POPSensorData fullData;
for(auto it : m_sensorsProxy)
{
fullData.Insert(it->Gather());
}
return fullData;
}
/// Clear the stored messages
void POPSensor::Clear()
{
for(auto it : m_sensorsProxy)
{
it->Clear();
}
}
/// Broadcast a message to all sensors
/*void POPSensor::Broadcast(int x_publicationType, int x_data)
{
for(auto it : m_sensorsProxy)
{
//it->Publish(x_publicationType, x_data);
}
}*/
/// Broadcast a message to all sensors
void POPSensor::Broadcast(int x_measurementType, int x_measurementUnit, int x_data)
{
for(auto it : m_sensorsProxy)
{
it->Notify(x_measurementType, x_measurementUnit, x_data);
}
}
/// Broadcast a message to all sensors
/*void POPSensor::Broadcast(int x_publicationType, double x_data)
{
for(auto it : m_sensorsProxy)
{
//it->Publish(x_publicationType, x_data);
}
}*/
/// Broadcast a message to all sensors
void POPSensor::Broadcast(int x_measurementType, int x_measurementUnit, double x_data)
{
for(auto it : m_sensorsProxy)
{
it->Notify(x_measurementType, x_measurementUnit, x_data);
}
}
/// Broadcast a message to all sensors
/*void POPSensor::Broadcast(int x_publicationType, const std::string& x_data)
{
for(auto it : m_sensorsProxy)
{
//it->Publish(x_publicationType, x_data);
}
}*/
/// Broadcast a message to all sensors
void POPSensor::Broadcast(int x_measurementType, int x_measurementUnit, const std::string& x_data)
{
for(auto it : m_sensorsProxy)
{
it->Notify(x_measurementType, x_measurementUnit, x_data);
}
}
/// Send a notification to all sensors
void POPSensor::Notify(int x_measurementType, int x_measurementUnit, const std::string& x_message)
{
for(auto it : m_sensorsProxy)
{
it->Notify(x_measurementType, x_measurementUnit, x_message);
}
}
/// Subscribe to messages of given type and data type
void POPSensor::Subscribe(int x_measurementType, int x_dataType)
{
for(auto it : m_sensorsProxy)
{
it->Subscribe(x_measurementType, x_dataType);
}
}
/// Return the size of the stored data
int POPSensor::GetDataSize()
{
int cpt = 0;
for(auto it : m_sensorsProxy)
{
cpt += it->GetDataSize();
}
return cpt;
}
/// Subscribe to all resources contained in resource.json
void POPSensor::SubscribeToResources(bool sub)
{
if(m_jsonResources.empty())
throw POPException("No resources specified. Did you connect ?");
Json::Reader reader;
Json::Value root;
if (!reader.parse(m_jsonResources, root, false))
{
throw POPException("Error while reading json string", m_jsonResources);
}
for(int i = 0 ; i < root["wsns"]["nodes"].size() ; i++)
{
enum MeasurementType mtype;
enum DataType dtype;
//enum PublicationType ptype;
bool incoming = false;
bool outgoing = false;
string str = root["wsns"]["nodes"][i].get("direction", "<not found>").asString();
if(str == "IN")
{
incoming = true;
mtype = translateMeasurementType(root["wsns"]["nodes"][i].get("measurementType", "log").asString().c_str());
dtype = translateDataType(root["wsns"]["nodes"][i].get("dataType", "unknown").asString().c_str());
}
else if(str == "OUT")
{
outgoing = true;
mtype = translateMeasurementType(root["wsns"]["nodes"][i].get("measurementType", "log").asString().c_str());
}
else if(str == "INOUT")
{
incoming = true;
outgoing = true;
mtype = translateMeasurementType(root["wsns"]["nodes"][i].get("measurementType", "log").asString().c_str());
dtype = translateDataType(root["wsns"]["nodes"][i].get("dataType", "unknown").asString().c_str());
}
else
{
throw POPException("Error in JSON: direction must be \"IN\", \"INOUT\" or \"OUT\"");
}
if((str == "IN" || str == "OUT" || str == "INOUT") && mtype == static_cast<int>(MSR_LOG))
throw POPException("measurementType not found in JSON resources description");
// note: dataType is not mandatory
// if(dtype == static_cast<int>(TYPE_UNKNOWN))
// throw POPException("dataType not found in JSON resources description");
int cpt = 0;
for(auto it : m_sensorsProxy)
{
if(!sub)
{
if(incoming)
{
cout << "Gateway " << PopSID + 1000 + cpt << " unsubscribes to " << explainMeasurementType(mtype) << " type:" << explainDataType(dtype) << " direction: IN" << popcendl;
it->UnSubscribe(mtype, dtype);
}
if(outgoing)
{
cout << "Gateway " << PopSID + 1000 + cpt << " cannot publish " << explainMeasurementType(mtype) << " commands anymore," << " direction: OUT" << popcendl;
it->UnPublish(mtype);
}
}
else
{
if(incoming)
{
cout << "Gateway " << PopSID + 1000 + cpt << " subscribes to " << explainMeasurementType(mtype) << " type:" << explainDataType(dtype) << " direction: IN" << popcendl;
it->Subscribe(mtype, dtype);
}
if(outgoing)
{
cout << "Gateway " << PopSID + 1000 + cpt << " can publish " << explainMeasurementType(mtype) << " commands," << " direction: OUT" << popcendl;
it->Publish(mtype);
}
}
cpt++;
}
}
}
/// Apply a reduce operation to the stored data {size, min, max, aver, sum, stdev}
double POPSensor::Reduce(int x_mtype, int x_dataType, int x_fct)
{
std::vector<double> vect;
for(auto it : m_sensorsProxy)
{
vect.push_back(it->Reduce(x_mtype, x_dataType, x_fct));
}
if(vect.empty())
return 0;
switch(x_fct)
{
case POPSensorData::size: return vect.size();
case POPSensorData::min: return *std::min_element(vect.begin(), vect.end());
case POPSensorData::max: return *std::max_element(vect.begin(), vect.end());
case POPSensorData::aver: return std::accumulate(vect.begin(), vect.end(), 0.0) / vect.size();
case POPSensorData::sum: return std::accumulate(vect.begin(), vect.end(), 0.0);
case POPSensorData::stdev:
{
double sum = std::accumulate(vect.begin(), vect.end(), 0.0);
double mean = sum / vect.size();
std::vector<double> diff(vect.size());
std::transform(vect.begin(), vect.end(), diff.begin(),
std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
return std::sqrt(sq_sum / vect.size());
}
}
}
@pack(POPSensor);