virtualsensor.cpp 15 KB
Newer Older
1
2
3
4
5
6
7
8
9
/*
 * virtualsensor.cpp
 *
 *  Created on: Jan 15, 2016
 *      Author: Axel Auweter
 */

#include "virtualsensor.h"
#include "virtualsensor_internal.h"
10
11
12
13
14
15
16
#include "sensorconfig.h"
#include "dcdbglobals.h"

#include <iostream>
#include <iomanip>
#include <numeric>
#include <cstdlib>
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

namespace DCDB {

/*
 * Implementations for VSExpressionParserException class.
 */
std::string VSExpressionParserException::msg_;
const char* VSExpressionParserException::what() const throw() {
   msg_ = runtime_error::what();
   msg_ += where_;
   msg_ += "\n";
   return msg_.c_str();
}

/*
32
 * Implementations for VSensorExpression class.
33
 */
34
35
36
37
38
39
40
41
42
43
44
45
void VSensorExpression::getInputs(std::unordered_set<std::string>& inputSet)
{
  impl->getInputs(inputSet);
}

void VSensorExpression::getInputsRecursive(std::unordered_set<std::string>& inputSet, bool virtualOnly)
{
  return impl->getInputsRecursive(inputSet, virtualOnly);
}

VSensorExpression::VSensorExpression(Connection* conn, std::string expr) {
  impl = new VirtualSensor::VSensorExpressionImpl(conn, expr);
46
47
}

48
VSensorExpression::~VSensorExpression() {
49
50
51
52
53
  if (impl) {
    delete impl;
  }
}

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
/*
 * Implementations for VSensor class.
 */
VSError VSensor::query(std::list<SensorDataStoreReading>& result, TimeStamp& start, TimeStamp& end)
{
  return impl->query(result, start, end);
}

VSensor::VSensor(Connection *conn, std::string name)
{
  impl = new VirtualSensor::VSensorImpl(conn, name);
}

VSensor::VSensor(Connection *conn, PublicSensor sensor)
{
  impl = new VirtualSensor::VSensorImpl(conn, sensor);
}

VSensor::~VSensor()
{
  if (impl) {
      delete impl;
  }
}

79
80
namespace VirtualSensor {
/*
81
 * Implementations for VSensorExpressionImpl class.
82
 */
83
void VSensorExpressionImpl::generateAST(std::string expr)
84
85
86
87
88
89
90
91
{
  /* Try to generate AST */
  typedef std::string::const_iterator StringIterator;
  typedef ExpressionGrammar<StringIterator> Grammar;

  ascii::space_type space;
  Grammar grammar;

92
93
94
95
96
97
  /* Add the list of known sensors to the grammar */
  std::list<std::string> sensorNames;
  SensorConfig sc(connection);
  sc.getPublicSensorNames(sensorNames);
  grammar.addSensorNames(sensorNames);

98
99
100
101
102
103
104
105
106
107
108
109
  StringIterator it = expr.begin();
  StringIterator end = expr.end();
  bool success = phrase_parse(it, end, grammar, space, opseq);

  if ((!success) || (it != end)) {
      std::string rest(it, end);
      throw VSExpressionParserException(rest);
  }

  /* Success - opseq now represents the top level of our AST */
}

110
void VSensorExpressionImpl::dumpAST()
111
112
113
114
115
116
{
  /* Declare a struct describing the action for each object in the AST when it comes to printing */
  struct ASTPrinter {
    typedef void result_type;
    void operator()(AST::Nil) const {}
    void operator()(unsigned int n) const { std::cout << n; }
117
    void operator()(std::string s) const { std::cout << "sensor(" << s << ")"; }
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
    void operator()(AST::Op const& x) const {
      boost::apply_visitor(*this, x.oprnd);
      switch (x.oprtr) {
      case '+': std::cout << " add"; break;
      case '-': std::cout << " sub"; break;
      case '*': std::cout << " mul"; break;
      case '/': std::cout << " div"; break;
      }
    }
    void operator()(AST::Signd const& x) const {
      boost::apply_visitor(*this, x.oprnd);
      switch (x.sgn) {
      case '-': std::cout << " neg"; break;
      case '+': std::cout << " pos"; break;
      }
    }
    void operator()(AST::Opseq const& x) const {
      boost::apply_visitor(*this, x.frst);
      BOOST_FOREACH(AST::Op const& o, x.rst) {
        std::cout << ' ';
        (*this)(o);
      }
    }
  };

  ASTPrinter printer;
  printer(opseq);
  std::cout << std::endl;
}

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
int64_t VSensorExpressionImpl::physicalSensorInterpolator(Connection* connection, SensorConfig& sc, PublicSensor& sensor, TimeStamp t)
{
  /*
   * FIXME: Very naive and inefficient implementation here requiring 2 queries per request.
   * In a proper implementation, we would query the full series for every physical input sensor
   * and keep them in memory to be evaluated here.
   */
  CassSession* session = connection->getSessionHandle();

  /* Expand the sensor's public name into its internal SensorId */
  /* FIXME: Should do proper error handling. Returning 0 is probably wrong! */
  std::list<DCDB::SensorId> sensorIds;
  switch (sc.getSensorListForPattern(sensorIds, sensor.pattern, t, t)) {
  case DCDB::SC_OK:
    break;
  case DCDB::SC_INVALIDPATTERN:
    std::cout << "Invalid pattern." << std::endl;
    return 0;
  default:
    std::cout << "Unknown error." << std::endl;
    return 0;
  }

  /* The sensorIds list should only contain one entry */
  std::list<DCDB::SensorId>::iterator sit = sensorIds.begin();
//  std::cout << "Raw sensor id: " << std::hex << std::setfill('0') << std::setw(16) << sit->getRaw()[0] << " " << std::hex << std::setfill('0') << std::setw(16) << sit->getRaw()[1] << std::dec << std::endl;

  /* Find the readings just before and just after time t */
  CassError rc = CASS_OK;
  CassStatement* statement = NULL;
  CassFuture *future = NULL;
  const CassPrepared* prepared = nullptr;
  const char* queryBefore = "SELECT * FROM " KEYSPACE_NAME "." CF_SENSORDATA " WHERE sid = ? AND ts <= ? ORDER BY ts DESC LIMIT 1;";
  const char* queryAfter = "SELECT * FROM " KEYSPACE_NAME "." CF_SENSORDATA " WHERE sid = ? AND ts > ? LIMIT 1;";

  SensorDataStoreReading readingBefore, readingAfter;
  std::string key = sit->serialize();

  /* Query before... */
  future = cass_session_prepare(session, queryBefore);
  cass_future_wait(future);

  rc = cass_future_error_code(future);
  if (rc != CASS_OK) {
    connection->printError(future);
    cass_future_free(future);
    return 0;
  }

  prepared = cass_future_get_prepared(future);
  cass_future_free(future);

  statement = cass_prepared_bind(prepared);
  cass_statement_bind_bytes(statement, 0, (const cass_byte_t*)(key.c_str()), 16);
  cass_statement_bind_int64(statement, 1, t.getRaw());

  future = cass_session_execute(session, statement);
  cass_future_wait(future);

  if (cass_future_error_code(future) == CASS_OK) {
      const CassResult* cresult = cass_future_get_result(future);
      CassIterator* rows = cass_iterator_from_result(cresult);

      if (cass_iterator_next(rows)) {
          const CassRow* row = cass_iterator_get_row(rows);

          cass_int64_t ts, value;
          cass_value_get_int64(cass_row_get_column_by_name(row, "ts"), &ts);
          cass_value_get_int64(cass_row_get_column_by_name(row, "value"), &value);

          readingBefore.timeStamp = (uint64_t)ts;
          readingBefore.value = (int64_t)value;
      }
      else {
          std::cout << "Cannot find reading for sensor " << sensor.name << " prior to time " << t.getString() << "(" << t.getRaw() << ")" << std::endl;
      }
      cass_iterator_free(rows);
      cass_result_free(cresult);
  }

  cass_statement_free(statement);
  cass_future_free(future);
  cass_prepared_free(prepared);

  /* Query after... */
  future = cass_session_prepare(session, queryAfter);
  cass_future_wait(future);

  rc = cass_future_error_code(future);
  if (rc != CASS_OK) {
    connection->printError(future);
    cass_future_free(future);
    return 0;
  }

  prepared = cass_future_get_prepared(future);
  cass_future_free(future);

  statement = cass_prepared_bind(prepared);
  cass_statement_bind_bytes(statement, 0, (const cass_byte_t*)(key.c_str()), 16);
  cass_statement_bind_int64(statement, 1, t.getRaw());

  future = cass_session_execute(session, statement);
  cass_future_wait(future);

  if (cass_future_error_code(future) == CASS_OK) {
      const CassResult* cresult = cass_future_get_result(future);
      CassIterator* rows = cass_iterator_from_result(cresult);

      if (cass_iterator_next(rows)) {
          const CassRow* row = cass_iterator_get_row(rows);

          cass_int64_t ts, value;
          cass_value_get_int64(cass_row_get_column_by_name(row, "ts"), &ts);
          cass_value_get_int64(cass_row_get_column_by_name(row, "value"), &value);

          readingAfter.timeStamp = (uint64_t)ts;
          readingAfter.value = (int64_t)value;
      }
      else {
          std::cout << "Cannot find reading for sensor " << sensor.name << " following time " << t.getString() << "(" << t.getRaw() << ")" << std::endl;
      }
      cass_iterator_free(rows);
      cass_result_free(cresult);
  }

  cass_statement_free(statement);
  cass_future_free(future);
  cass_prepared_free(prepared);

  /*
   * Linearly interpolate between the readings using the following equation:
   *
   *     y2 - y1       x2y1 - x1y2
   * y = ------- * x + -----------
   *     x2 - x1         x2 - x1
   */
  typedef double eval_type;
  eval_type x1 = readingBefore.timeStamp.getRaw();
  eval_type x2 = readingAfter.timeStamp.getRaw();
  eval_type y1 = readingBefore.value;
  eval_type y2 = readingAfter.value;
  eval_type x = t.getRaw();

  return (((y2 - y1) / (x2 - x1)) * x) + (((x2 * y1) - (x1 * y2)) / (x2 - x1));
}

void VSensorExpressionImpl::getInputs(std::unordered_set<std::string>& inputSet)
{
  /* Declare a struct describing the action for each object in the AST when it comes to collecting the sensor inputs */
  struct ASTInputCollector {
    typedef void result_type;
    void operator()(AST::Nil) const {}
    void operator()(unsigned int n) const { }
    void operator()(std::string s) const { is.insert(s); }
    void operator()(AST::Op const& x) const {
      boost::apply_visitor(*this, x.oprnd);
    }
    void operator()(AST::Signd const& x) const {
      boost::apply_visitor(*this, x.oprnd);
    }
    void operator()(AST::Opseq const& x) const {
      boost::apply_visitor(*this, x.frst);
      BOOST_FOREACH(AST::Op const& o, x.rst) {
        (*this)(o);
      }
    }

    ASTInputCollector(std::unordered_set<std::string>& inputSet) : is(inputSet) {}

    std::unordered_set<std::string>& is;
  };

  ASTInputCollector inputCollector(inputSet);
  inputCollector(opseq);
}

void VSensorExpressionImpl::getInputsRecursive(std::unordered_set<std::string>& inputSet, bool virtualOnly)
326
{
327
328
329
330
331
332
333
334
335
336
337
  /* Get our own inputs */
  std::unordered_set<std::string> myInputs;
  getInputs(myInputs);

  /* Iterate over inputs and append to set */
  for (std::unordered_set<std::string>::iterator it = myInputs.begin(); it != myInputs.end(); it++ ) {

      /* Get information for this sensor */
      SensorConfig sc(connection);
      PublicSensor psen;
      sc.getPublicSensorByName(psen, it->c_str());
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
      /* Check if the sensor is physical and whether we only append virtual sensors */
      if (!psen.is_virtual && virtualOnly) {
          continue;
      }

      /* Append the sensor to the set */
      inputSet.insert(*it);

      /* If the sensor is physical, we're done */
      if (!psen.is_virtual) {
          continue;
      }

      /* Recurse into this sensor's list of inputs */
      VSensorExpressionImpl vsen(connection, psen.expression);
      vsen.getInputsRecursive(inputSet, virtualOnly);
  }
}

int64_t VSensorExpressionImpl::evaluateAt(TimeStamp time)
{
  /* Declare a struct describing the action for each object in the AST when it comes to evaluation */
  struct ASTEvaluator {
    typedef int64_t result_type;
    int64_t operator()(AST::Nil) const { return 0; }
    int64_t operator()(unsigned int n) const { return n; }
    int64_t operator()(std::string s) const {

      /* Evaluate sensor s at time t */
      SensorConfig sc(c);
      PublicSensor sen;
      if (sc.getPublicSensorByName(sen, s.c_str()) != SC_OK) {
          std::cout << "Internal error on getPublicSensorByName while trying to evaluate " << s << " at " << t.getString() << std::endl;
          return 0;
      }

      /* Things are easy if the sensor is virtual */
      if (sen.is_virtual) {
          VSensorExpressionImpl vSen(c, sen.expression);
          return vSen.evaluateAt(t);
      }
      else {
          /* Physical sensors need a little bit more thinkin' */
          return physicalSensorInterpolator(c, sc, sen, t);
      }

      return 0;
    }
    int64_t operator()(int64_t lhs, AST::Op const& x) const {
      int64_t rhs = boost::apply_visitor(*this, x.oprnd);
      switch (x.oprtr) {
      case '+': return lhs + rhs; break;
      case '-': return lhs - rhs; break;
      case '*': return lhs * rhs; break;
      case '/': return lhs / rhs; break;
      }
      return 0;
    }
    int64_t operator()(AST::Signd const& x) const {
      int64_t rhs = boost::apply_visitor(*this, x.oprnd);
      switch (x.sgn) {
      case '-': return -rhs; break;
      case '+': return +rhs; break;
      }
      return 0;
    }
    int64_t operator()(AST::Opseq const& x) const {
      return std::accumulate(
          x.rst.begin(), x.rst.end(),
          boost::apply_visitor(*this, x.frst),
          *this
          );
    }

    ASTEvaluator(Connection* conn, TimeStamp time) : c(conn), t(time) {}

    Connection* c;
    TimeStamp t;
  };

  ASTEvaluator eval(connection, time);
  return eval(opseq);
}

VSensorExpressionImpl::VSensorExpressionImpl(Connection* conn, std::string expr)
{
  /* Assign connection variable */
  connection = conn;

  /* Generate the AST for the expression */
  generateAST(expr);
}

VSensorExpressionImpl::~VSensorExpressionImpl()
{
}

/*
 * Implementations for VSensorImpl class.
 */
VSError VSensorImpl::query(std::list<SensorDataStoreReading>& result, TimeStamp& start, TimeStamp& end)
{
  /*
   * Calculate first and last time stamp at which this virtual sensor fires:
   * Each virtual sensor fires at t0 + n*frequency (n=0,1,2,....)
   */
  uint64_t n_start, n_end;
  n_start = (start.getRaw() - tzero.getRaw()) / frequency;
  n_end = (end.getRaw() - tzero.getRaw()) / frequency;

  /* Clear the result set */
  result.clear();

  /* Iterate over all time steps at which this sensor fires. */
  for (
      uint64_t i = (tzero.getRaw() + (n_start * frequency));
      i <= (tzero.getRaw() + (n_end * frequency));
      i += frequency)
  {
    int64_t eval = expression->evaluateAt(i);
    TimeStamp t(i);
    SensorDataStoreReading r;
    r.timeStamp = t;
    r.value = eval;
    result.push_back(r);
  }

  return VS_OK;
}

VSensorImpl::VSensorImpl(Connection *conn, std::string name)
{
  SensorConfig sc(conn);
  PublicSensor sen;

  /* TODO: How to behave if sensor not found? */
  if (sc.getPublicSensorByName(sen, name.c_str()) != SC_OK) {
      std::cout << "Internal error: getPublicSensorByName(" << name << ") failed." << std::endl;
      exit(EXIT_FAILURE);
  }

  /* The rest is done by the constructor working on the PublicSensor object */
  VSensorImpl(conn, sen);
}

VSensorImpl::VSensorImpl(Connection *conn, PublicSensor sensor)
{
  /* TODO: How to behave if sensor is a physical public sensor? Exception? */
  if (!sensor.is_virtual) {
      std::cout << "Internal error: Trying to populate VSensorImpl with physical sensor data." << std::endl;
      exit(EXIT_FAILURE);
  }

  /* Assign the connection variable */
  connection = conn;

  /* Populate the local fields from the PublicSensor struct */
  name = sensor.name;
  expression = new VSensorExpressionImpl(connection, sensor.expression);
  vsensorid = new SensorId(sensor.v_sensorid);
  tzero = sensor.t_zero;
  frequency = sensor.frequency;
501
502
503
504
}

VSensorImpl::~VSensorImpl()
{
505
506
507
508
509
510
  if (expression) {
      delete expression;
  }
  if (vsensorid) {
      delete vsensorid;
  }
511
512
513
514
}

} /* End of namespace VirtualSensor */
} /* End of namespace DCDB */