iobroker.influxdb 2.3.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/main.js CHANGED
@@ -20,7 +20,7 @@ function isEqual(a, b) {
20
20
  //console.log('Compare ' + JSON.stringify(a) + ' with ' + JSON.stringify(b));
21
21
  // Create arrays of property names
22
22
  if (a === null || a === undefined || b === null || b === undefined) {
23
- return (a === b);
23
+ return a === b;
24
24
  }
25
25
 
26
26
  const aProps = Object.getOwnPropertyNames(a);
@@ -76,7 +76,7 @@ function startAdapter(options) {
76
76
  if (obj.common.custom && obj.common.custom[adapter.namespace] && obj.common.custom[adapter.namespace].aliasId) {
77
77
  if (obj.common.custom[adapter.namespace].aliasId !== id) {
78
78
  adapter._aliasMap[id] = obj.common.custom[adapter.namespace].aliasId;
79
- adapter.log.debug('Registered Alias: ' + id + ' --> ' + adapter._aliasMap[id]);
79
+ adapter.log.debug(`Registered Alias: ${id} --> ${adapter._aliasMap[id]}`);
80
80
  id = adapter._aliasMap[id];
81
81
  checkForRemove = false;
82
82
  } else {
@@ -85,7 +85,7 @@ function startAdapter(options) {
85
85
  }
86
86
  }
87
87
  if (checkForRemove && adapter._aliasMap[id]) {
88
- adapter.log.debug('Removed Alias: ' + id + ' !-> ' + adapter._aliasMap[id]);
88
+ adapter.log.debug(`Removed Alias: ${id} !-> ${adapter._aliasMap[id]}`);
89
89
  delete adapter._aliasMap[id];
90
90
  }
91
91
 
@@ -228,25 +228,25 @@ function stopPing(adapter) {
228
228
  }
229
229
 
230
230
  function ping(adapter) {
231
- adapter._client.ping && adapter._client.ping(adapter.config.pingInterval - 1000 < 0 ? 1000 : adapter.config.pingInterval - 1000)
232
- .then(
233
- hosts => {
234
- if (!hosts.some(host => host.online)) {
235
- reconnect(adapter);
236
- } else {
237
- adapter.log.debug('PING OK');
238
- }
239
- },
240
- error => {
241
- adapter.log.error(`Error during ping: ${error}. Attempting reconnect.`);
231
+ adapter._client.ping && adapter.config.pingserver !== false && adapter._client.ping(adapter.config.pingInterval - 1000 < 0 ? 1000 : adapter.config.pingInterval - 1000)
232
+ .then(hosts => {
233
+ if (!hosts.some(host => host.online)) {
242
234
  reconnect(adapter);
243
- });
235
+ } else {
236
+ adapter.log.debug('PING OK');
237
+ }
238
+ },
239
+ error => {
240
+ adapter.log.error(`Error during ping: ${error}. Attempting reconnect.`);
241
+ reconnect(adapter);
242
+ });
244
243
  }
245
244
 
246
245
  function connect(adapter) {
247
246
  adapter.log.info(`Connecting ${adapter.config.protocol}://${adapter.config.host}:${adapter.config.port} ...`);
248
247
 
249
248
  adapter.config.dbname = adapter.config.dbname || appName;
249
+ adapter.config.validateSSL = adapter.config.validateSSL !== undefined ? !!adapter.config.validateSSL : true;
250
250
 
251
251
  adapter.config.seriesBufferMax = parseInt(adapter.config.seriesBufferMax, 10) || 0;
252
252
 
@@ -266,15 +266,17 @@ function connect(adapter) {
266
266
  adapter.config.token,
267
267
  adapter.config.organization,
268
268
  adapter.config.dbname,
269
+ adapter.config.requestTimeout,
270
+ adapter.config.validateSSL,
269
271
  adapter.config.usetags
270
272
  )
271
273
  break;
272
274
  case '1.x':
273
275
  default:
274
276
  if (/[\x00-\x08\x0E-\x1F\x80-\xFF]/.test(adapter.config.password)) {
275
- adapter.log.error('Password error: Please re-enter the password in Admin. Stopping');
276
- return;
277
+ return adapter.log.error('Password error: Please re-enter the password in Admin. Stopping');
277
278
  }
279
+
278
280
  adapter._client = new DatabaseInfluxDB1x(
279
281
  adapter.log,
280
282
  adapter.config.host,
@@ -283,12 +285,15 @@ function connect(adapter) {
283
285
  adapter.config.user,
284
286
  adapter.config.password,
285
287
  adapter.config.dbname,
286
- 'ms',
287
- 30000
288
+ adapter.config.requestTimeout,
289
+ 'ms'
288
290
  );
289
291
  break;
290
292
  }
291
293
 
294
+ if (adapter.config.pingserver === false) {
295
+ adapter.log.info('Deactivated DB health checks (ping) via configuration');
296
+ }
292
297
 
293
298
  adapter._client.getDatabaseNames((err, dbNames) => {
294
299
  if (err) {
@@ -381,6 +386,7 @@ function getRetention(adapter, msg) {
381
386
  function testConnection(adapter, msg) {
382
387
  adapter.log.debug('testConnection msg-object: ' + JSON.stringify(msg));
383
388
  msg.message.config.port = parseInt(msg.message.config.port, 10) || 0;
389
+ msg.message.config.requestTimeout = parseInt(msg.message.config.requestTimeout) || 30000;
384
390
 
385
391
  let timeout;
386
392
  try {
@@ -401,7 +407,8 @@ function testConnection(adapter, msg) {
401
407
  msg.message.config.protocol, // optional, default 'http'
402
408
  msg.message.config.token,
403
409
  msg.message.config.organization,
404
- msg.message.config.dbname || appName
410
+ msg.message.config.dbname || appName,
411
+ msg.message.config.requestTimeout
405
412
  )
406
413
  break;
407
414
  default:
@@ -413,7 +420,8 @@ function testConnection(adapter, msg) {
413
420
  msg.message.config.protocol, // optional, default 'http'
414
421
  msg.message.config.user,
415
422
  msg.message.config.password,
416
- msg.message.config.dbname || appName
423
+ msg.message.config.dbname || appName,
424
+ msg.message.config.requestTimeout
417
425
  );
418
426
  break;
419
427
  }
@@ -470,9 +478,25 @@ function destroyDB(adapter, msg) {
470
478
  function processMessage(adapter, msg) {
471
479
  adapter.log.debug(`Incoming message ${msg.command} from ${msg.from}`);
472
480
  if (msg.command === 'features') {
473
- adapter.sendTo(msg.from, msg.command, {supportedFeatures: []}, msg.callback);
474
- } else
475
- if (msg.command === 'getHistory') {
481
+ // influxdb 1
482
+ if (adapter.config.dbversion === '1.x') {
483
+ adapter.sendTo(msg.from, msg.command, {supportedFeatures: ['update', 'delete', 'deleteRange', 'deleteAll', 'storeState']}, msg.callback);
484
+ } else {
485
+ // not yet implemented
486
+ adapter.sendTo(msg.from, msg.command, {supportedFeatures: ['storeState']}, msg.callback);
487
+ }
488
+ }
489
+ else if (msg.command === 'update') {
490
+ updateState(adapter, msg);
491
+ } else if (msg.command === 'delete') {
492
+ deleteState(adapter, msg);
493
+ } else if (msg.command === 'deleteAll') {
494
+ deleteStateAll(adapter, msg);
495
+ } else if (msg.command === 'deleteRange') {
496
+ deleteState(adapter, msg);
497
+ } else if (msg.command === 'storeState') {
498
+ storeState(adapter, msg);
499
+ } else if (msg.command === 'getHistory') {
476
500
  adapter.config.dbversion === '1.x' ? getHistory(adapter, msg) : getHistoryIflx2(adapter, msg);
477
501
  }
478
502
  else if (msg.command === 'test') {
@@ -499,9 +523,6 @@ function processMessage(adapter, msg) {
499
523
  else if (msg.command === 'resetConflictingPoints') {
500
524
  resetConflictingPoints(adapter, msg);
501
525
  }
502
- else if (msg.command === 'storeState') {
503
- storeState(adapter, msg);
504
- }
505
526
  else if (msg.command === 'enableHistory') {
506
527
  enableHistory(adapter, msg);
507
528
  }
@@ -569,6 +590,8 @@ function main(adapter) {
569
590
 
570
591
  adapter.config.seriesBufferFlushInterval = parseInt(adapter.config.seriesBufferFlushInterval, 10) || 600;
571
592
 
593
+ adapter.config.requestTimeout = parseInt(adapter.config.requestTimeout, 10) || 30000;
594
+
572
595
  if (adapter.config.changesMinDelta !== null && adapter.config.changesMinDelta !== undefined) {
573
596
  adapter.config.changesMinDelta = parseFloat(adapter.config.changesMinDelta.toString().replace(/,/g, '.'));
574
597
  } else {
@@ -594,10 +617,11 @@ function main(adapter) {
594
617
 
595
618
  // read all custom settings
596
619
  adapter.getObjectView('system', 'custom', {}, (err, doc) => {
597
- if (err) adapter.log.error('main/getObjectView: ' + err);
620
+ err && adapter.log.error('main/getObjectView: ' + err);
598
621
  let count = 0;
599
622
  if (doc && doc.rows) {
600
- for (let i = 0, l = doc.rows.length; i < l; i++) {
623
+ const l = doc.rows.length;
624
+ for (let i = 0; i < l; i++) {
601
625
  if (doc.rows[i].value) {
602
626
  let id = doc.rows[i].id;
603
627
  const realId = id;
@@ -634,7 +658,8 @@ function main(adapter) {
634
658
  } else {
635
659
  adapter._influxDPs[id][adapter.namespace].changesMinDelta = adapter.config.changesMinDelta;
636
660
  }
637
- if (!adapter._influxDPs[id][adapter.namespace].storageType) adapter._influxDPs[id][adapter.namespace].storageType = false;
661
+
662
+ adapter._influxDPs[id][adapter.namespace].storageType = adapter._influxDPs[id][adapter.namespace].storageType || false;
638
663
 
639
664
  adapter._influxDPs[id].realId = realId;
640
665
  writeInitialValue(adapter, realId, id);
@@ -756,6 +781,7 @@ function pushHistory(adapter, id, state, timerRelog) {
756
781
  // only store state if really changed
757
782
  adapter._influxDPs[id].state = state;
758
783
  }
784
+
759
785
  adapter._influxDPs[id].lastLogTime = state.ts;
760
786
  adapter._influxDPs[id].skipped = null;
761
787
 
@@ -807,6 +833,12 @@ function pushHelper(adapter, _id, cb) {
807
833
  if (adapter._influxDPs[_id].state.val === null) { // InfluxDB can not handle null values
808
834
  return cb && setImmediate(cb, `null value for ${_id} can not be handled`);
809
835
  }
836
+ if (adapter._influxDPs[_id].state.val === null) { // InfluxDB can not handle null values
837
+ return cb && setImmediate(cb, `null value for ${_id} can not be handled`);
838
+ }
839
+ if (typeof adapter._influxDPs[_id].state.val === 'number' && !isFinite(adapter._influxDPs[_id].state.val)) { // InfluxDB can not handle Infinite values
840
+ return cb && setImmediate(cb, `Non Finite value ${adapter._influxDPs[_id].state.val} for ${_id} can not be handled`);
841
+ }
810
842
 
811
843
  if (typeof adapter._influxDPs[_id].state.val === 'object') {
812
844
  adapter._influxDPs[_id].state.val = JSON.stringify(adapter._influxDPs[_id].state.val);
@@ -852,15 +884,15 @@ function pushValueIntoDB(adapter, id, state, cb) {
852
884
  if (state.val === null || state.val === undefined) {
853
885
  return cb && cb('InfluxDB can not handle null/non-existing values');
854
886
  } // InfluxDB can not handle null/non-existing values
855
- if (typeof state.val === 'number' && isNaN(state.val)) {
856
- return cb && cb('InfluxDB can not handle null/non-existing values');
887
+ if (typeof state.val === 'number' && !isFinite(state.val)) {
888
+ return cb && cb(`InfluxDB can not handle non finite values like ${state.val}`);
857
889
  }
858
890
 
859
- if (adapter._influxDPs[id][adapter.namespace].ignoreZero && state.val === 0) {
891
+ if (adapter._influxDPs[id] && adapter._influxDPs[id][adapter.namespace] && adapter._influxDPs[id][adapter.namespace].ignoreZero && state.val === 0) {
860
892
  adapter.log.debug(`pushValueIntoDB called for ${id} was ignored because the value zero or null`);
861
893
  return cb && cb();
862
894
  } else
863
- if (state && adapter._influxDPs[id][adapter.namespace].ignoreBelowZero && typeof state.val === 'number' && state.val < 0) {
895
+ if (state && adapter._influxDPs[id] && adapter._influxDPs[id][adapter.namespace] && adapter._influxDPs[id][adapter.namespace].ignoreBelowZero && typeof state.val === 'number' && state.val < 0) {
864
896
  adapter.log.debug(`pushValueIntoDB called for ${id} and state: ${JSON.stringify(state)} was ignored because the value is below 0`);
865
897
  return cb && cb();
866
898
  }
@@ -999,7 +1031,8 @@ function writeAllSeriesPerID(adapter, series, cb, idList) {
999
1031
  return cb && cb();
1000
1032
  }
1001
1033
  const id = idList.shift();
1002
- writeSeriesPerID(adapter, id, series[id], () => writeAllSeriesPerID(adapter, series, cb, idList));
1034
+ writeSeriesPerID(adapter, id, series[id], () =>
1035
+ writeAllSeriesPerID(adapter, series, cb, idList));
1003
1036
  }
1004
1037
 
1005
1038
  function writeSeriesPerID(adapter, seriesId, points, cb) {
@@ -1065,7 +1098,7 @@ function writeOnePointForID(adapter, pointId, point, directWrite, cb) {
1065
1098
  adapter._client.writePoint(pointId, point, null, (err /* , result */) => {
1066
1099
  if (err) {
1067
1100
  adapter.log.warn(`Error on writePoint("${JSON.stringify(point)}): ${err} / ${JSON.stringify(err.message)}"`);
1068
- if ((adapter._client.request.getHostsAvailable().length === 0) || (err.message && err.message === 'timeout')) {
1101
+ if (!adapter._client.request.getHostsAvailable().length || (err.message && err.message === 'timeout')) {
1069
1102
  reconnect(adapter);
1070
1103
  addPointToSeriesBuffer(adapter, pointId, point);
1071
1104
  } else if (err.message && typeof err.message === 'string' && err.message.includes('field type conflict')) {
@@ -1126,7 +1159,7 @@ function writeOnePointForID(adapter, pointId, point, directWrite, cb) {
1126
1159
  }
1127
1160
  if (!directWrite || !retry) {
1128
1161
  // remember this as a pot. conflicting point and write synchronous
1129
- adapter._conflictingPoints[pointId]=1;
1162
+ adapter._conflictingPoints[pointId] = 1;
1130
1163
  adapter.log.warn(`Add ${pointId} to conflicting Points (${Object.keys(adapter._conflictingPoints).length} now)`);
1131
1164
  }
1132
1165
  } else {
@@ -1136,7 +1169,7 @@ function writeOnePointForID(adapter, pointId, point, directWrite, cb) {
1136
1169
  adapter._errorPoints[pointId]++;
1137
1170
  }
1138
1171
  if (adapter._errorPoints[pointId] < 10) {
1139
- // re-add that point to buffer to try write again
1172
+ // re-add that point to buffer to try to write again
1140
1173
  adapter.log.info(`Add point that had error for ${pointId} to buffer again, error-count=${adapter._errorPoints[pointId]}`);
1141
1174
  addPointToSeriesBuffer(adapter, pointId, point);
1142
1175
  } else {
@@ -1169,7 +1202,334 @@ function writeFileBufferToDisk() {
1169
1202
  adapter._seriesBufferCounter = null;
1170
1203
  }
1171
1204
 
1205
+ function _delete(adapter, id, state, cb) {
1206
+ if (!adapter._connected) {
1207
+ return cb && cb('not connected');
1208
+ }
1209
+
1210
+ if (adapter.config.dbversion === '1.x') {
1211
+ let query;
1212
+ if (state.ts) {
1213
+ query = `DELETE FROM "${id}" WHERE time = '${new Date(state.ts).toISOString()}'`;
1214
+ } else if (state.start) {
1215
+ query = `DELETE FROM "${id}" WHERE time >= '${new Date(state.start).toISOString()}'${state.end ? ` AND time <= '${new Date(state.end).toISOString()}'` : ''}`;
1216
+ } else if (state.end) {
1217
+ query = `DELETE FROM "${id}" WHERE time <= '${new Date(state.end).toISOString()}`;
1218
+ } else {
1219
+ query = `DELETE FROM "${id}" WHERE time >= '2000-01-01T00:00:00.000Z'`; // delete all
1220
+ }
1221
+
1222
+ adapter._client.query(query, err => {
1223
+ if (err) {
1224
+ adapter.log.warn(`Error on delete("${query}): ${err} / ${JSON.stringify(err.message)}"`);
1225
+ cb(err);
1226
+ } else {
1227
+ setConnected(adapter, true);
1228
+ }
1229
+ cb && cb();
1230
+ });
1231
+ } else {
1232
+ cb && cb('not implemented');
1233
+ }
1234
+ }
1235
+
1236
+ function deleteState(adapter, msg) {
1237
+ if (!msg.message) {
1238
+ adapter.log.error('deleteState called with invalid data');
1239
+ return adapter.sendTo(msg.from, msg.command, {
1240
+ error: 'Invalid call: ' + JSON.stringify(msg)
1241
+ }, msg.callback);
1242
+ }
1243
+ let id;
1244
+ if (Array.isArray(msg.message)) {
1245
+ adapter.log.debug(`deleteState ${msg.message.length} items`);
1246
+
1247
+ for (let i = 0; i < msg.message.length; i++) {
1248
+ id = adapter._aliasMap[msg.message[i].id] ? adapter._aliasMap[msg.message[i].id] : msg.message[i].id;
1249
+
1250
+ // {id: 'blabla', ts: 892}
1251
+ if (msg.message[i].ts) {
1252
+ _delete(adapter, id, {ts: msg.message[i].ts});
1253
+ } else
1254
+ if (msg.message[i].start) {
1255
+ if (typeof msg.message[i].start === 'string') {
1256
+ msg.message[i].start = new Date(msg.message[i].start).getTime();
1257
+ }
1258
+ if (typeof msg.message[i].end === 'string') {
1259
+ msg.message[i].end = new Date(msg.message[i].end).getTime();
1260
+ }
1261
+ _delete(adapter, id, {start: msg.message[i].start, end: msg.message[i].end || Date.now()});
1262
+ } else
1263
+ if (typeof msg.message[i].state === 'object' && msg.message[i].state && msg.message[i].state.ts) {
1264
+ _delete(adapter, id, {ts: msg.message[i].state.ts});
1265
+ } else
1266
+ if (typeof msg.message[i].state === 'object' && msg.message[i].state && msg.message[i].state.start) {
1267
+ if (typeof msg.message[i].state.start === 'string') {
1268
+ msg.message[i].state.start = new Date(msg.message[i].state.start).getTime();
1269
+ }
1270
+ if (typeof msg.message[i].state.end === 'string') {
1271
+ msg.message[i].state.end = new Date(msg.message[i].state.end).getTime();
1272
+ }
1273
+ _delete(adapter, id, {start: msg.message[i].state.start, end: msg.message[i].state.end || Date.now()});
1274
+ } else {
1275
+ adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message[i]));
1276
+ }
1277
+ }
1278
+ } else if (msg.message.state && Array.isArray(msg.message.state)) {
1279
+ adapter.log.debug(`deleteState ${msg.message.state.length} items`);
1280
+ id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1281
+
1282
+ for (let j = 0; j < msg.message.state.length; j++) {
1283
+ if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
1284
+ if (msg.message.state[j].ts) {
1285
+ _delete(adapter, id, {ts: msg.message.state[j].ts});
1286
+ } else if (msg.message.state[j].start) {
1287
+ if (typeof msg.message.state[j].start === 'string') {
1288
+ msg.message.state[j].start = new Date(msg.message.state[j].start).getTime();
1289
+ }
1290
+ if (typeof msg.message.state[j].end === 'string') {
1291
+ msg.message.state[j].end = new Date(msg.message.state[j].end).getTime();
1292
+ }
1293
+ _delete(adapter, id, {start: msg.message.state[j].start, end: msg.message.state[j].end || Date.now()});
1294
+ }
1295
+ } else if (msg.message.state[j] && typeof msg.message.state[j] === 'number') {
1296
+ _delete(adapter, id, {ts: msg.message.state[j]});
1297
+ } else {
1298
+ adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message.state[j]));
1299
+ }
1300
+ }
1301
+ } else if (msg.message.ts && Array.isArray(msg.message.ts)) {
1302
+ adapter.log.debug(`deleteState ${msg.message.ts.length} items`);
1303
+ id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1304
+ for (let j = 0; j < msg.message.ts.length; j++) {
1305
+ if (msg.message.ts[j] && typeof msg.message.ts[j] === 'number') {
1306
+ _delete(adapter, id, {ts: msg.message.ts[j]});
1307
+ } else {
1308
+ adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message.ts[j]));
1309
+ }
1310
+ }
1311
+ } else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
1312
+ adapter.log.debug('deleteState 1 item');
1313
+ id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1314
+ return _delete(adapter, id, {ts: msg.message.state.ts}, error => adapter.sendTo(msg.from, msg.command, {
1315
+ success: !error,
1316
+ error,
1317
+ connected: !!adapter._connected
1318
+ }, msg.callback));
1319
+ } else if (msg.message.id && msg.message.ts && typeof msg.message.ts === 'number') {
1320
+ adapter.log.debug('deleteState 1 item');
1321
+ id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1322
+ return _delete(adapter, id, {ts: msg.message.ts}, error => adapter.sendTo(msg.from, msg.command, {
1323
+ success: !error,
1324
+ error,
1325
+ connected: !!adapter._connected
1326
+ }, msg.callback));
1327
+ } else {
1328
+ adapter.log.error('deleteState called with invalid data');
1329
+ return adapter.sendTo(msg.from, msg.command, {error: 'Invalid call: ' + JSON.stringify(msg)}, msg.callback);
1330
+ }
1331
+
1332
+ setTimeout(() => {
1333
+ adapter.sendTo(msg.from, msg.command, {
1334
+ success: true,
1335
+ connected: !!adapter._connected
1336
+ }, msg.callback);
1337
+ }, 300);
1338
+ }
1339
+
1340
+ function deleteStateAll(adapter, msg) {
1341
+ if (!msg.message) {
1342
+ adapter.log.error('deleteState called with invalid data');
1343
+ return adapter.sendTo(msg.from, msg.command, {
1344
+ error: 'Invalid call: ' + JSON.stringify(msg)
1345
+ }, msg.callback);
1346
+ }
1347
+ let id;
1348
+ if (Array.isArray(msg.message)) {
1349
+ adapter.log.debug(`deleteStateAll ${msg.message.length} items`);
1350
+ for (let i = 0; i < msg.message.length; i++) {
1351
+ id = adapter._aliasMap[msg.message[i].id] ? adapter._aliasMap[msg.message[i].id] : msg.message[i].id;
1352
+ _delete(adapter, id, {}, error => {
1353
+ adapter.sendTo(msg.from, msg.command, {
1354
+ success: !error,
1355
+ error,
1356
+ connected: !!adapter._connected
1357
+ }, msg.callback);
1358
+ });
1359
+ }
1360
+ } else if (msg.message.id) {
1361
+ adapter.log.debug('deleteStateAll 1 item');
1362
+ id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1363
+ _delete(adapter, id, {}, error => {
1364
+ adapter.sendTo(msg.from, msg.command, {
1365
+ success: !error,
1366
+ error,
1367
+ connected: !!adapter._connected
1368
+ }, msg.callback);
1369
+ });
1370
+ } else {
1371
+ adapter.log.error('deleteStateAll called with invalid data');
1372
+ return adapter.sendTo(msg.from, msg.command, {error: 'Invalid call: ' + JSON.stringify(msg)}, msg.callback);
1373
+ }
1374
+ }
1375
+
1376
+ function update(adapter, id, state, cb) {
1377
+ if (!adapter._connected) {
1378
+ return cb && cb('not connected');
1379
+ }
1380
+
1381
+ if (adapter.config.dbversion === '1.x') {
1382
+ let query = `SELECT * FROM "${id}" WHERE time = '${new Date(state.ts).toISOString()}'`;
1383
+
1384
+ adapter._client.query(query, (err, result) => {
1385
+ if (err) {
1386
+ adapter.log.warn(`Error on update("${query}): ${err} / ${JSON.stringify(err.message)}"`);
1387
+ cb(err);
1388
+ } else {
1389
+ setConnected(adapter, true);
1390
+
1391
+ console.log(JSON.stringify(result));
1392
+ if (result[0] && result[0][0]) {
1393
+ const stored = result[0][0];
1394
+ if (state.val !== undefined) {
1395
+ stored.val = state.val;
1396
+ }
1397
+ if (state.ack !== undefined) {
1398
+ stored.ack = state.ack;
1399
+ }
1400
+ if (state.q !== undefined) {
1401
+ stored.q = state.q;
1402
+ }
1403
+ if (state.from) {
1404
+ stored.from = state.from;
1405
+ }
1406
+ stored.ts = state.ts;
1407
+ delete stored.time;
1408
+
1409
+ _delete(adapter, id, {ts: stored.ts}, error => {
1410
+ if (error) {
1411
+ adapter.log.error(`Cannot delete value for ${id}: ${JSON.stringify(state)}`);
1412
+ cb(err);
1413
+ } else {
1414
+ pushValueIntoDB(adapter, id, stored);
1415
+ cb && cb();
1416
+ }
1417
+ });
1418
+ } else {
1419
+ adapter.log.error(`Cannot find value to delete for ${id}: ${JSON.stringify(state)}`);
1420
+ cb && cb('not found');
1421
+ }
1422
+ }
1423
+ });
1424
+ } else {
1425
+ cb && cb('not implemented');
1426
+ }
1427
+ }
1428
+
1429
+ function updateState(adapter, msg) {
1430
+ if (!msg.message) {
1431
+ adapter.log.error('updateState called with invalid data');
1432
+ return adapter.sendTo(msg.from, msg.command, {
1433
+ error: 'Invalid call: ' + JSON.stringify(msg)
1434
+ }, msg.callback);
1435
+ }
1436
+ let id;
1437
+ if (Array.isArray(msg.message)) {
1438
+ adapter.log.debug(`updateState ${msg.message.length} items`);
1439
+ for (let i = 0; i < msg.message.length; i++) {
1440
+ id = adapter._aliasMap[msg.message[i].id] ? adapter._aliasMap[msg.message[i].id] : msg.message[i].id;
1441
+
1442
+ if (msg.message[i].state && typeof msg.message[i].state === 'object') {
1443
+ update(adapter, id, msg.message[i].state);
1444
+ } else {
1445
+ adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message[i]));
1446
+ }
1447
+ }
1448
+ adapter.sendTo(msg.from, msg.command, {
1449
+ success: true,
1450
+ connected: !!adapter._connected
1451
+ }, msg.callback);
1452
+ } else if (msg.message.state && Array.isArray(msg.message.state)) {
1453
+ adapter.log.debug('updateState ' + msg.message.state.length + ' items');
1454
+ id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1455
+ for (let j = 0; j < msg.message.state.length; j++) {
1456
+ if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
1457
+ update(adapter, id, msg.message.state[j]);
1458
+ } else {
1459
+ adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message.state[j]));
1460
+ }
1461
+ }
1462
+ adapter.sendTo(msg.from, msg.command, {
1463
+ success: true,
1464
+ connected: !!adapter._connected
1465
+ }, msg.callback);
1466
+ } else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
1467
+ adapter.log.debug('updateState 1 item');
1468
+ id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1469
+ update(adapter, id, msg.message.state, error => adapter.sendTo(msg.from, msg.command, {
1470
+ success: !error,
1471
+ error,
1472
+ connected: !!adapter._connected
1473
+ }, msg.callback));
1474
+ } else {
1475
+ adapter.log.error('updateState called with invalid data');
1476
+ adapter.sendTo(msg.from, msg.command, {
1477
+ error: 'Invalid call: ' + JSON.stringify(msg)
1478
+ }, msg.callback);
1479
+ }
1480
+ }
1481
+
1482
+ function storeState(adapter, msg) {
1483
+ if (!msg.message) {
1484
+ adapter.log.error('storeState called with invalid data');
1485
+ return adapter.sendTo(msg.from, msg.command, {
1486
+ error: 'Invalid call: ' + JSON.stringify(msg)
1487
+ }, msg.callback);
1488
+ }
1489
+
1490
+ let id;
1491
+ if (Array.isArray(msg.message)) {
1492
+ adapter.log.debug(`storeState ${msg.message.length} items`);
1493
+ for (let i = 0; i < msg.message.length; i++) {
1494
+ id = adapter._aliasMap[msg.message[i].id] ? adapter._aliasMap[msg.message[i].id] : msg.message[i].id;
1495
+ if (msg.message[i].state && typeof msg.message[i].state === 'object') {
1496
+ pushValueIntoDB(adapter, id, msg.message[i].state);
1497
+ } else {
1498
+ adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message[i]));
1499
+ }
1500
+ }
1501
+ } else if (msg.message.state && Array.isArray(msg.message.state)) {
1502
+ adapter.log.debug(`storeState ${msg.message.state.length} items`);
1503
+ id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1504
+ for (let j = 0; j < msg.message.state.length; j++) {
1505
+ if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
1506
+ pushValueIntoDB(adapter, id, msg.message.state[j]);
1507
+ } else {
1508
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
1509
+ }
1510
+ }
1511
+ } else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
1512
+ adapter.log.debug('storeState 1 item');
1513
+ id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1514
+ pushValueIntoDB(adapter, id, msg.message.state);
1515
+ } else {
1516
+ adapter.log.error('storeState called with invalid data');
1517
+ return adapter.sendTo(msg.from, msg.command, {
1518
+ error: `Invalid call: ${JSON.stringify(msg)}`
1519
+ }, msg.callback);
1520
+ }
1521
+
1522
+ adapter.sendTo(msg.from, msg.command, {
1523
+ success: true,
1524
+ connected: !!adapter._connected,
1525
+ seriesBufferCounter: adapter._seriesBufferCounter,
1526
+ seriesBufferFlushPlanned: adapter._seriesBufferFlushPlanned
1527
+ }, msg.callback);
1528
+ }
1529
+
1172
1530
  function finish(adapter, callback) {
1531
+ adapter.setState && adapter.setState('info.connection', false, true);
1532
+
1173
1533
  if (!adapter._subscribeAll) {
1174
1534
  // unsubscribe
1175
1535
  for (const _id in adapter._influxDPs) {
@@ -1189,7 +1549,7 @@ function finish(adapter, callback) {
1189
1549
  adapter._pingInterval = null;
1190
1550
  }
1191
1551
  if (adapter._finished) {
1192
- if (callback) callback();
1552
+ callback && callback();
1193
1553
  return;
1194
1554
  }
1195
1555
  adapter._finished = true;
@@ -1199,7 +1559,9 @@ function finish(adapter, callback) {
1199
1559
  }
1200
1560
  let count = 0;
1201
1561
  for (const id in adapter._influxDPs) {
1202
- if (!adapter._influxDPs.hasOwnProperty(id)) continue;
1562
+ if (!adapter._influxDPs.hasOwnProperty(id)) {
1563
+ continue;
1564
+ }
1203
1565
 
1204
1566
  if (adapter._influxDPs[id].relogTimeout) {
1205
1567
  clearTimeout(adapter._influxDPs[id].relogTimeout);
@@ -1242,12 +1604,14 @@ function finish(adapter, callback) {
1242
1604
  if (callback) {
1243
1605
  callback();
1244
1606
  } else {
1245
- adapter.terminate ? adapter.terminate() : process.exit()
1607
+ adapter.terminate ? adapter.terminate() : process.exit();
1246
1608
  }
1247
1609
  }
1248
1610
  }
1249
1611
 
1250
1612
  function getHistory(adapter, msg) {
1613
+ const startTime = Date.now();
1614
+
1251
1615
  const options = {
1252
1616
  id: msg.message.id === '*' ? null : msg.message.id,
1253
1617
  start: msg.message.options.start,
@@ -1303,7 +1667,7 @@ function getHistory(adapter, msg) {
1303
1667
  query += ' *';
1304
1668
  }
1305
1669
 
1306
- query += ' from "' + options.id + '"';
1670
+ query += ` from "${options.id}"`;
1307
1671
 
1308
1672
  if (!adapter._influxDPs[options.id]) {
1309
1673
  adapter.sendTo(msg.from, msg.command, {
@@ -1319,67 +1683,77 @@ function getHistory(adapter, msg) {
1319
1683
  options.end = options.start;
1320
1684
  options.start = _end;
1321
1685
  }
1686
+
1322
1687
  // if less 2000.01.01 00:00:00
1323
- if (options.end && options.end < 946681200000) options.end *= 1000;
1324
- if (options.start && options.start < 946681200000) options.start *= 1000;
1688
+ if (options.end && options.end < 946681200000) {
1689
+ options.end *= 1000;
1690
+ }
1691
+ if (options.start && options.start < 946681200000) {
1692
+ options.start *= 1000;
1693
+ }
1325
1694
 
1326
1695
  if (!options.start && !options.count) {
1327
1696
  options.start = options.end - 86400000; // - 1 day
1328
1697
  }
1329
1698
 
1330
- // query one timegroup-value more then requested originally at start and end
1331
- // to make sure to have no 0 values because of the way InfluxDB doies group by time
1699
+ // query one timegroup-value more than requested originally at start and end
1700
+ // to make sure to have no 0 values because of the way InfluxDB does group by time
1332
1701
  if (options.aggregate !== 'onchange' && options.aggregate !== 'none' && options.aggregate !== 'minmax') {
1333
1702
  if (!options.step) {
1334
1703
  // calculate "step" based on difference between start and end using count
1335
1704
  options.step = parseInt((options.end - options.start) / options.count, 10);
1336
1705
  }
1337
- if (options.start) options.start -= options.step;
1706
+ if (options.start) {
1707
+ options.start -= options.step;
1708
+ }
1338
1709
  options.end += options.step;
1339
1710
  options.limit += 2;
1340
1711
  }
1341
1712
 
1342
- query += " WHERE ";
1713
+ query += ` WHERE `;
1343
1714
  if (options.start) {
1344
- query += " time > '" + new Date(options.start).toISOString() + "' AND ";
1715
+ query += ` time > '${new Date(options.start).toISOString()}' AND `;
1345
1716
  }
1346
- query += " time < '" + new Date(options.end).toISOString() + "'";
1717
+ query += ` time < '${new Date(options.end).toISOString()}'`;
1347
1718
 
1348
1719
  if (!options.start && (options.count || options.limit)) {
1349
- query += " ORDER BY time DESC";
1720
+ query += ` ORDER BY time DESC`;
1350
1721
  }
1351
1722
 
1352
1723
  if (options.aggregate !== 'onchange' && options.aggregate !== 'none' && options.aggregate !== 'minmax') {
1353
- query += ' GROUP BY time(' + options.step + 'ms) fill(previous) LIMIT ' + options.limit;
1724
+ query += ` GROUP BY time(${options.step}ms) fill(previous) LIMIT ${options.limit}`;
1354
1725
  } else if (options.aggregate !== 'minmax') {
1355
- query += ' LIMIT ' + options.count;
1726
+ query += ` LIMIT ${options.count}`;
1356
1727
  }
1357
1728
 
1358
- // select one datapoint more then wanted
1729
+ // select one datapoint more than wanted
1359
1730
  if (options.aggregate === 'minmax' || options.aggregate === 'onchange' || options.aggregate === 'none') {
1360
1731
  let addQuery = '';
1361
1732
  if (options.start) {
1362
- addQuery = 'SELECT value from "' + options.id + '"' + " WHERE time <= '" + new Date(options.start).toISOString() + "' ORDER BY time DESC LIMIT 1;";
1733
+ addQuery = `SELECT value from "${options.id}" WHERE time <= '${new Date(options.start).toISOString()}' ORDER BY time DESC LIMIT 1;`;
1363
1734
  query = addQuery + query;
1364
1735
  }
1365
- addQuery = ';SELECT value from "' + options.id + '"' + " WHERE time >= '" + new Date(options.end).toISOString() + "' LIMIT 1";
1736
+ addQuery = `;SELECT value from "${options.id}" WHERE time >= '${new Date(options.end).toISOString()}' LIMIT 1`;
1366
1737
  query = query + addQuery;
1367
1738
  }
1368
1739
 
1369
1740
  adapter.log.debug(query);
1370
1741
 
1371
1742
  // if specific id requested
1372
- adapter._client.query(query, (err, rows) => {
1373
- if (err) {
1743
+ adapter._client.query(query, (error, rows) => {
1744
+ if (error) {
1374
1745
  if (adapter._client.request.getHostsAvailable().length === 0) {
1375
1746
  setConnected(adapter, false);
1376
1747
  }
1377
- adapter.log.error('getHistory: ' + err);
1748
+ adapter.log.error('getHistory: ' + error);
1378
1749
  } else {
1379
1750
  setConnected(adapter, true);
1380
1751
  }
1752
+
1381
1753
  adapter.log.debug('ROWS:' + JSON.stringify(rows));
1754
+
1382
1755
  let result = [];
1756
+
1383
1757
  if (rows && rows.length) {
1384
1758
  for (let qr = 0; qr < rows.length; qr++) {
1385
1759
  for (let rr = 0; rr < rows[qr].length; rr++) {
@@ -1398,28 +1772,21 @@ function getHistory(adapter, msg) {
1398
1772
  }
1399
1773
  }
1400
1774
  }
1401
- if (options.addId) rows[qr][rr].id = msg.message.id;
1775
+ if (options.addId) {
1776
+ rows[qr][rr].id = msg.message.id;
1777
+ }
1402
1778
  result.push(rows[qr][rr]);
1403
1779
  }
1404
1780
  }
1405
1781
  }
1406
1782
 
1407
- if ((result.length > 0) && (options.aggregate === 'minmax')) {
1408
- Aggregate.initAggregate(options);
1409
- Aggregate.aggregation(options, result);
1410
- Aggregate.finishAggregation(options);
1411
- result = options.result;
1412
- }
1413
-
1414
- adapter.sendTo(msg.from, msg.command, {
1415
- result: result,
1416
- error: err,
1417
- sessionId: options.sessionId
1418
- }, msg.callback);
1783
+ Aggregate.sendResponse(adapter, msg, options, (error ? error.toString() : null) || result, startTime);
1419
1784
  });
1420
1785
  }
1421
1786
 
1422
1787
  function getHistoryIflx2(adapter, msg) {
1788
+ const startTime = Date.now();
1789
+
1423
1790
  const options = {
1424
1791
  id: msg.message.id === '*' ? null : msg.message.id,
1425
1792
  start: msg.message.options.start,
@@ -1437,17 +1804,16 @@ function getHistoryIflx2(adapter, msg) {
1437
1804
  options.id = adapter._aliasMap[options.id];
1438
1805
  }
1439
1806
  const fluxQueries = [];
1440
- let fluxQuery = 'from(bucket: "' + adapter.config.dbname + '") ';
1807
+ let fluxQuery = `from(bucket: "${adapter.config.dbname}") `;
1441
1808
 
1442
1809
  const valueColumn = adapter.config.usetags ? '_value' : 'value';
1443
1810
 
1444
1811
  if (!adapter._influxDPs[options.id]) {
1445
- adapter.sendTo(msg.from, msg.command, {
1812
+ return adapter.sendTo(msg.from, msg.command, {
1446
1813
  result: [],
1447
1814
  step: 0,
1448
1815
  error: 'No connection'
1449
1816
  }, msg.callback);
1450
- return;
1451
1817
  }
1452
1818
 
1453
1819
  if (options.start > options.end) {
@@ -1463,8 +1829,8 @@ function getHistoryIflx2(adapter, msg) {
1463
1829
  options.start = options.end - 86400000; // - 1 day
1464
1830
  }
1465
1831
 
1466
- // query one timegroup-value more then requested originally at start and end
1467
- // to make sure to have no 0 values because of the way InfluxDB doies group by time
1832
+ // query one timegroup-value more than requested originally at start and end
1833
+ // to make sure to have no 0 values because of the way InfluxDB does group by time
1468
1834
  if (options.aggregate !== 'onchange' && options.aggregate !== 'none' && options.aggregate !== 'minmax') {
1469
1835
  if (!options.step) {
1470
1836
  // calculate "step" based on difference between start and end using count
@@ -1475,8 +1841,8 @@ function getHistoryIflx2(adapter, msg) {
1475
1841
  options.limit += 2;
1476
1842
  }
1477
1843
 
1478
- fluxQuery += " |> range(" + ((options.start) ? "start: " + new Date(options.start).toISOString() + ", " : "start: -" + adapter.config.retention +"ms, ") + "stop: " + new Date(options.end).toISOString() + ")";
1479
- fluxQuery += ' |> filter(fn: (r) => r["_measurement"] == "' + options.id + '")';
1844
+ fluxQuery += ` |> range(${(options.start) ? "start: " + new Date(options.start).toISOString() + ", " : "start: -" + adapter.config.retention + "ms, "}stop: ${new Date(options.end).toISOString()})`;
1845
+ fluxQuery += ` |> filter(fn: (r) => r["_measurement"] == "${options.id}")`;
1480
1846
 
1481
1847
  if (adapter.config.usetags)
1482
1848
  fluxQuery += ' |> duplicate(column: "_value", as: "value")';
@@ -1484,100 +1850,98 @@ function getHistoryIflx2(adapter, msg) {
1484
1850
  fluxQuery += ' |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")';
1485
1851
 
1486
1852
  if (!options.start && (options.count || options.limit)) {
1487
- fluxQuery += " |> sort(columns:[\"_time\"], desc: true)";
1853
+ fluxQuery += ` |> sort(columns:["_time"], desc: true)`;
1488
1854
  }
1489
1855
 
1490
1856
  if (options.aggregate !== 'onchange' && options.aggregate !== 'none' && options.aggregate !== 'minmax') {
1491
1857
  if ((options.step !== null) && (options.step > 0))
1492
- fluxQuery += ' |> window(every: ' + options.step + 'ms)';
1493
- fluxQuery += '|> fill(column: "' + valueColumn +'", usePrevious: true)';
1858
+ fluxQuery += ` |> window(every: ${options.step}ms)`;
1859
+ fluxQuery += `|> fill(column: "${valueColumn}", usePrevious: true)`;
1494
1860
  } else if (options.aggregate !== 'minmax') {
1495
- fluxQuery += ' |> group() |> limit(n: ' + options.count + ')';
1861
+ fluxQuery += ` |> group() |> limit(n: ${options.count})`;
1496
1862
  }
1497
1863
 
1498
- //Workaround to detect if measurement is of type bool (to skip non-sensical aggregation options)
1499
- //There seems to be no officially supported way to detect this, so we check it by forcing a type-conflict
1500
- const booleanTypeCheckQuery = '\
1501
- from(bucket: "' + adapter.config.dbname + '")\
1502
- |> range(' + ((options.start) ? 'start: ' + new Date(options.start).toISOString() + ', ' : 'start: -' + adapter.config.retention +'ms, ') + 'stop: ' + new Date(options.end).toISOString() + ')\
1503
- |> filter(fn: (r) => r["_measurement"] == "' + options.id + '" and contains(value: r._value, set: [true, false]))\
1504
- ';
1864
+ // Workaround to detect if measurement is of type bool (to skip non-sensual aggregation options)
1865
+ // There seems to be no officially supported way to detect this, so we check it by forcing a type-conflict
1866
+ const booleanTypeCheckQuery = `
1867
+ from(bucket: "${adapter.config.dbname}")
1868
+ |> range(${(options.start) ? `start: ${new Date(options.start).toISOString()}, ` : `start: -${adapter.config.retention}ms, `}stop: ${new Date(options.end).toISOString()})
1869
+ |> filter(fn: (r) => r["_measurement"] == "${options.id}" and contains(value: r._value, set: [true, false]))
1870
+ `;
1505
1871
 
1506
1872
  adapter._client.query(booleanTypeCheckQuery, (error, _rslt) => {
1507
1873
  let isBoolean;
1508
1874
  if (error) {
1509
- if (error.message.match('.*type conflict: bool.*'))
1875
+ if (error.message.match('.*type conflict: bool.*')) {
1510
1876
  isBoolean = false;
1511
- else {
1512
- adapter.sendTo(msg.from, msg.command, {
1877
+ } else {
1878
+ return adapter.sendTo(msg.from, msg.command, {
1513
1879
  result: [],
1514
1880
  error: error,
1515
1881
  sessionId: options.sessionId
1516
1882
  }, msg.callback);
1517
- return;
1518
1883
  }
1519
1884
  } else {
1520
1885
  isBoolean = true;
1521
1886
  adapter.log.debug(`Measurement ${options.id} is of type Boolean - skipping aggregation options`);
1522
1887
  }
1523
1888
 
1524
-
1525
1889
  if (options.step && !isBoolean) {
1526
1890
 
1527
1891
  switch (options.aggregate) {
1528
1892
  case 'average':
1529
- fluxQuery += ' |> mean(column: "'+ valueColumn +'")';
1893
+ fluxQuery += ` |> mean(column: "${valueColumn}")`;
1530
1894
  break;
1531
1895
 
1532
1896
  case 'max':
1533
- fluxQuery += ' |> max(column: "'+ valueColumn +'")';
1897
+ fluxQuery += ` |> max(column: "${valueColumn}")`;
1534
1898
  break;
1535
1899
 
1536
1900
  case 'min':
1537
- fluxQuery += ' |> min(column: "'+ valueColumn +'")';
1901
+ fluxQuery += ` |> min(column: "${valueColumn}")`;
1538
1902
  break;
1539
1903
 
1540
1904
  case 'total':
1541
- fluxQuery += ' |> sum(column: "'+ valueColumn +'")';
1905
+ fluxQuery += ` |> sum(column: "${valueColumn}")`;
1542
1906
  break;
1543
1907
 
1544
1908
  case 'count':
1545
- fluxQuery += ' |> count(column: "'+ valueColumn +'")';
1909
+ fluxQuery += ` |> count(column: "${valueColumn}")`;
1546
1910
  break;
1547
1911
 
1548
1912
  default:
1549
- fluxQuery += ' |> mean(column: "'+ valueColumn +'")';
1913
+ fluxQuery += ` |> mean(column: "${valueColumn}")`;
1550
1914
  break;
1551
1915
  }
1552
1916
  }
1553
1917
 
1554
1918
  fluxQueries.push(fluxQuery);
1555
1919
 
1556
- // select one datapoint more then wanted
1920
+ // select one datapoint more than wanted
1557
1921
  if (options.aggregate === 'minmax' || options.aggregate === 'onchange' || options.aggregate === 'none') {
1558
1922
  let addFluxQuery = '';
1559
1923
  if (options.start) {
1560
1924
  // get one entry "before" the defined timeframe for displaying purposes
1561
- addFluxQuery = 'from(bucket: "' + adapter.config.dbname + '") \
1562
- |> range(start: ' + new Date(options.start - (adapter.config.retention || 31536000) * 1000).toISOString() + ', stop: ' + new Date(options.start).toISOString() + ') \
1563
- |> filter(fn: (r) => r["_measurement"] == "' + options.id + '") \
1564
- ' + ((!adapter.config.usetags) ? '|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")' : '') + '\
1565
- |> sort(columns: ["_time"], desc: true) \
1566
- |> group() \
1567
- |> limit(n: 1)';
1925
+ addFluxQuery = `from(bucket: "${adapter.config.dbname}")
1926
+ |> range(start: ${new Date(options.start - (adapter.config.retention || 31536000) * 1000).toISOString()}, stop: ${new Date(options.start).toISOString()})
1927
+ |> filter(fn: (r) => r["_measurement"] == "${options.id}")
1928
+ ${(!adapter.config.usetags) ? '|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")' : ''}
1929
+ |> sort(columns: ["_time"], desc: true)
1930
+ |> group()
1931
+ |> limit(n: 1)`;
1568
1932
 
1569
1933
  const mainQuery = fluxQueries.pop();
1570
1934
  fluxQueries.push(addFluxQuery);
1571
1935
  fluxQueries.push(mainQuery);
1572
1936
  }
1573
1937
  // get one entry "after" the defined timeframe for displaying purposes
1574
- addFluxQuery = 'from(bucket: "' + adapter.config.dbname + '") \
1575
- |> range(start: ' + new Date(options.end).toISOString() + ') \
1576
- |> filter(fn: (r) => r["_measurement"] == "' + options.id + '") \
1577
- ' + ((!adapter.config.usetags) ? '|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")' : '') + '\
1578
- |> sort(columns: ["_time"], desc: false) \
1579
- |> group() \
1580
- |> limit(n: 1)';
1938
+ addFluxQuery = `from(bucket: "${adapter.config.dbname}")
1939
+ |> range(start: ${new Date(options.end).toISOString()})
1940
+ |> filter(fn: (r) => r["_measurement"] == "${options.id}")
1941
+ ${(!adapter.config.usetags) ? '|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")' : ''}
1942
+ |> sort(columns: ["_time"], desc: false)
1943
+ |> group()
1944
+ |> limit(n: 1)`;
1581
1945
  //fluxQuery = fluxQuery + addFluxQuery;
1582
1946
  fluxQueries.push(addFluxQuery);
1583
1947
  }
@@ -1594,8 +1958,11 @@ function getHistoryIflx2(adapter, msg) {
1594
1958
  } else {
1595
1959
  setConnected(adapter, true);
1596
1960
  }
1961
+
1597
1962
  adapter.log.debug('Parsing retrieved rows:' + JSON.stringify(rows));
1963
+
1598
1964
  let result = [];
1965
+
1599
1966
  if (rows && rows.length) {
1600
1967
  for (let qr = 0; qr < rows.length; qr++) {
1601
1968
  for (let rr = 0; rr < rows[qr].length; rr++) {
@@ -1603,8 +1970,11 @@ function getHistoryIflx2(adapter, msg) {
1603
1970
  rows[qr][rr].val = rows[qr][rr].value;
1604
1971
  delete rows[qr][rr].value;
1605
1972
  }
1606
- rows[qr][rr].ts = new Date(rows[qr][rr].time).getTime();
1973
+
1974
+ rows[qr][rr].ts = new Date(rows[qr][rr].time).getTime();
1975
+
1607
1976
  delete rows[qr][rr].time;
1977
+
1608
1978
  if (rows[qr][rr].val !== null) {
1609
1979
  const f = parseFloat(rows[qr][rr].val);
1610
1980
  if (f == rows[qr][rr].val) {
@@ -1614,24 +1984,17 @@ function getHistoryIflx2(adapter, msg) {
1614
1984
  }
1615
1985
  }
1616
1986
  }
1617
- if (options.addId) rows[qr][rr].id = msg.message.id;
1987
+
1988
+ if (options.addId) {
1989
+ rows[qr][rr].id = msg.message.id;
1990
+ }
1991
+
1618
1992
  result.push(rows[qr][rr]);
1619
1993
  }
1620
1994
  }
1621
1995
  }
1622
1996
 
1623
- if ((result.length > 0) && (options.aggregate === 'minmax')) {
1624
- Aggregate.initAggregate(options);
1625
- Aggregate.aggregation(options, result);
1626
- Aggregate.finishAggregation(options);
1627
- result = options.result;
1628
- }
1629
-
1630
- adapter.sendTo(msg.from, msg.command, {
1631
- result: result,
1632
- error: err,
1633
- sessionId: options.sessionId
1634
- }, msg.callback);
1997
+ Aggregate.sendResponse(adapter, msg, options, (error ? error.toString() : null) || result, startTime);
1635
1998
  });
1636
1999
  });
1637
2000
  }
@@ -1727,9 +2090,9 @@ function multiQuery(adapter, msg) {
1727
2090
  }
1728
2091
  adapter.log.error('queries: ' + err);
1729
2092
  return adapter.sendTo(msg.from, msg.command, {
1730
- result: [],
1731
- error: 'Invalid call'
1732
- }, msg.callback);
2093
+ result: [],
2094
+ error: 'Invalid call'
2095
+ }, msg.callback);
1733
2096
  } else {
1734
2097
  setConnected(adapter, true);
1735
2098
  }
@@ -1759,42 +2122,6 @@ function multiQuery(adapter, msg) {
1759
2122
  }
1760
2123
  }
1761
2124
 
1762
- function storeState(adapter, msg) {
1763
- if (!msg.message || !msg.message.id || !msg.message.state) {
1764
- adapter.log.error('storeState called with invalid data');
1765
- adapter.sendTo(msg.from, msg.command, {
1766
- error: 'Invalid call'
1767
- }, msg.callback);
1768
- return;
1769
- }
1770
-
1771
- let id;
1772
- if (Array.isArray(msg.message)) {
1773
- adapter.log.debug(`storeState: store ${msg.message.length} states for multiple ids`);
1774
- for (let i = 0; i < msg.message.length; i++) {
1775
- id = adapter._aliasMap[msg.message[i].id] ? adapter._aliasMap[msg.message[i].id] : msg.message[i].id;
1776
- pushValueIntoDB(adapter, id, msg.message[i].state);
1777
- }
1778
- } else if (Array.isArray(msg.message.state)) {
1779
- adapter.log.debug(`storeState: store ${msg.message.state.length} states for ${msg.message.id}`);
1780
- for (let j = 0; j < msg.message.state.length; j++) {
1781
- id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1782
- pushValueIntoDB(adapter, id, msg.message.state[j]);
1783
- }
1784
- } else {
1785
- adapter.log.debug(`storeState: store 1 state for ${msg.message.id}`);
1786
- id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1787
- pushValueIntoDB(adapter, id, msg.message.state);
1788
- }
1789
-
1790
- adapter.sendTo(msg.from, msg.command, {
1791
- success: true,
1792
- connected: adapter._connected,
1793
- seriesBufferCounter: adapter._seriesBufferCounter,
1794
- seriesBufferFlushPlanned: adapter._seriesBufferFlushPlanned
1795
- }, msg.callback);
1796
- }
1797
-
1798
2125
  function enableHistory(adapter, msg) {
1799
2126
  if (!msg.message || !msg.message.id) {
1800
2127
  adapter.log.error('enableHistory called with invalid data');
@@ -1832,17 +2159,13 @@ function disableHistory(adapter, msg) {
1832
2159
  obj.common.custom = {};
1833
2160
  obj.common.custom[adapter.namespace] = {};
1834
2161
  obj.common.custom[adapter.namespace].enabled = false;
1835
- adapter.extendForeignObject(msg.message.id, obj, err => {
1836
- if (err) {
1837
- adapter.log.error('disableHistory: ' + err);
1838
- adapter.sendTo(msg.from, msg.command, {
1839
- error: err
1840
- }, msg.callback);
2162
+ adapter.extendForeignObject(msg.message.id, obj, error => {
2163
+ if (error) {
2164
+ adapter.log.error('disableHistory: ' + error);
2165
+ adapter.sendTo(msg.from, msg.command, {error}, msg.callback);
1841
2166
  } else {
1842
2167
  adapter.log.info(JSON.stringify(obj));
1843
- adapter.sendTo(msg.from, msg.command, {
1844
- success: true
1845
- }, msg.callback);
2168
+ adapter.sendTo(msg.from, msg.command, {success: true}, msg.callback);
1846
2169
  }
1847
2170
  });
1848
2171
  }