iobroker.influxdb 2.6.2 → 3.0.2

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
@@ -11,8 +11,8 @@ const fs = require('fs');
11
11
  const path = require('path');
12
12
  const [appName, adapterName] = require('./package.json').name.split('.');
13
13
  const Aggregate = require('./lib/aggregate.js');
14
- const dataDir = path.normalize(utils.controllerDir + '/' + require(utils.controllerDir + '/lib/tools').getDefaultDataDir());
15
- const cacheFile = dataDir + 'influxdata.json';
14
+ const dataDir = path.normalize(`${utils.controllerDir}/${require(`${utils.controllerDir}/lib/tools`).getDefaultDataDir()}`);
15
+ const cacheFile = `${dataDir}influxdata.json`;
16
16
 
17
17
  let adapter;
18
18
 
@@ -80,7 +80,7 @@ function startAdapter(options) {
80
80
  id = adapter._aliasMap[id];
81
81
  checkForRemove = false;
82
82
  } else {
83
- adapter.log.warn('Ignoring Alias-ID because identical to ID for ' + id);
83
+ adapter.log.warn(`Ignoring Alias-ID because identical to ID for ${id}`);
84
84
  obj.common.custom[adapter.namespace].aliasId = '';
85
85
  }
86
86
  }
@@ -98,44 +98,106 @@ function startAdapter(options) {
98
98
  adapter.subscribeForeignStates('*');
99
99
  }
100
100
 
101
- if (obj.common.custom[adapter.namespace].debounce !== undefined && obj.common.custom[adapter.namespace].debounce !== null && obj.common.custom[adapter.namespace].debounce !== '') {
102
- obj.common.custom[adapter.namespace].debounce = parseInt(obj.common.custom[adapter.namespace].debounce, 10) || 0;
101
+ // debounceTime and debounce compatibility handling
102
+ if (!obj.common.custom[adapter.namespace].blockTime && obj.common.custom[adapter.namespace].blockTime !== '0' && obj.common.custom[adapter.namespace].blockTime !== 0) {
103
+ if (!obj.common.custom[adapter.namespace].debounce && obj.common.custom[adapter.namespace].debounce !== '0' && obj.common.custom[adapter.namespace].debounce !== 0) {
104
+ obj.common.custom[adapter.namespace].blockTime = parseInt(adapter.config.blockTime, 10) || 0;
105
+ } else {
106
+ obj.common.custom[adapter.namespace].blockTime = parseInt(obj.common.custom[adapter.namespace].debounce, 10) || 0;
107
+ }
108
+ } else {
109
+ obj.common.custom[adapter.namespace].blockTime = parseInt(obj.common.custom[adapter.namespace].blockTime, 10) || 0;
110
+ }
111
+ if (!obj.common.custom[adapter.namespace].debounceTime && obj.common.custom[adapter.namespace].debounceTime !== '0' && obj.common.custom[adapter.namespace].debounceTime !== 0) {
112
+ obj.common.custom[adapter.namespace].debounceTime = parseInt(adapter.config.debounceTime, 10) || 0;
103
113
  } else {
104
- obj.common.custom[adapter.namespace].debounce = adapter.config.debounce;
114
+ obj.common.custom[adapter.namespace].debounceTime = parseInt(obj.common.custom[adapter.namespace].debounceTime, 10) || 0;
105
115
  }
106
116
 
117
+ // changesOnly
107
118
  obj.common.custom[adapter.namespace].changesOnly = obj.common.custom[adapter.namespace].changesOnly === 'true' || obj.common.custom[adapter.namespace].changesOnly === true;
108
- obj.common.custom[adapter.namespace].ignoreZero = obj.common.custom[adapter.namespace].ignoreZero === 'true' || obj.common.custom[adapter.namespace].ignoreZero === true;
109
- obj.common.custom[adapter.namespace].ignoreBelowZero = obj.common.custom[adapter.namespace].ignoreBelowZero === 'true' || obj.common.custom[adapter.namespace].ignoreBelowZero === true;
110
119
 
111
- if (obj.common.custom[adapter.namespace].changesRelogInterval !== undefined && obj.common.custom[adapter.namespace].changesRelogInterval !== null && obj.common.custom[adapter.namespace].changesRelogInterval !== '') {
120
+ // ignoreZero
121
+ obj.common.custom[adapter.namespace].ignoreZero = obj.common.custom[adapter.namespace].ignoreZero === 'true' || obj.common.custom[adapter.namespace].ignoreZero === true;
122
+
123
+ // round
124
+ if (obj.common.custom[adapter.namespace].round !== null && obj.common.custom[adapter.namespace].round !== undefined && obj.common.custom[adapter.namespace] !== '') {
125
+ obj.common.custom[adapter.namespace].round = parseInt(obj.common.custom[adapter.namespace], 10);
126
+ if (!isFinite(obj.common.custom[adapter.namespace].round) || obj.common.custom[adapter.namespace].round < 0) {
127
+ obj.common.custom[adapter.namespace].round = adapter.config.round;
128
+ } else {
129
+ obj.common.custom[adapter.namespace].round = Math.pow(10, parseInt(obj.common.custom[adapter.namespace].round, 10));
130
+ }
131
+ } else {
132
+ obj.common.custom[adapter.namespace].round = adapter.config.round;
133
+ }
134
+
135
+ // ignoreAboveNumber
136
+ if (obj.common.custom[adapter.namespace].ignoreAboveNumber !== undefined && obj.common.custom[adapter.namespace].ignoreAboveNumber !== null && obj.common.custom[adapter.namespace].ignoreAboveNumber !== '') {
137
+ obj.common.custom[adapter.namespace].ignoreAboveNumber = parseFloat(obj.common.custom[adapter.namespace].ignoreAboveNumber) || null;
138
+ }
139
+
140
+ // ignoreBelowNumber incl. ignoreBelowZero compatibility handling
141
+ if (obj.common.custom[adapter.namespace].ignoreBelowNumber !== undefined && obj.common.custom[adapter.namespace].ignoreBelowNumber !== null && obj.common.custom[adapter.namespace].ignoreBelowNumber !== '') {
142
+ obj.common.custom[adapter.namespace].ignoreBelowNumber = parseFloat(obj.common.custom[adapter.namespace].ignoreBelowNumber) || null;
143
+ } else if (obj.common.custom[adapter.namespace].ignoreBelowZero === 'true' || obj.common.custom[adapter.namespace].ignoreBelowZero === true) {
144
+ obj.common.custom[adapter.namespace].ignoreBelowNumber = 0;
145
+ }
146
+
147
+ // disableSkippedValueLogging
148
+ if (obj.common.custom[adapter.namespace].disableSkippedValueLogging !== undefined && obj.common.custom[adapter.namespace].disableSkippedValueLogging !== null && obj.common.custom[adapter.namespace].disableSkippedValueLogging !== '') {
149
+ obj.common.custom[adapter.namespace].disableSkippedValueLogging = obj.common.custom[adapter.namespace].disableSkippedValueLogging === 'true' || obj.common.custom[adapter.namespace].disableSkippedValueLogging === true;
150
+ } else {
151
+ obj.common.custom[adapter.namespace].disableSkippedValueLogging = adapter.config.disableSkippedValueLogging;
152
+ }
153
+
154
+ // enableDebugLogs
155
+ if (obj.common.custom[adapter.namespace].enableDebugLogs !== undefined && obj.common.custom[adapter.namespace].enableDebugLogs !== null && obj.common.custom[adapter.namespace].enableDebugLogs !== '') {
156
+ obj.common.custom[adapter.namespace].enableDebugLogs = obj.common.custom[adapter.namespace].enableDebugLogs === 'true' || obj.common.custom[adapter.namespace].enableDebugLogs === true;
157
+ } else {
158
+ obj.common.custom[adapter.namespace].enableDebugLogs = adapter.config.enableDebugLogs;
159
+ }
160
+
161
+ // changesRelogInterval
162
+ if (obj.common.custom[adapter.namespace].changesRelogInterval || obj.common.custom[adapter.namespace].changesRelogInterval === 0) {
112
163
  obj.common.custom[adapter.namespace].changesRelogInterval = parseInt(obj.common.custom[adapter.namespace].changesRelogInterval, 10) || 0;
113
164
  } else {
114
165
  obj.common.custom[adapter.namespace].changesRelogInterval = adapter.config.changesRelogInterval;
115
166
  }
116
167
 
117
- if (obj.common.custom[adapter.namespace].changesMinDelta !== undefined && obj.common.custom[adapter.namespace].changesMinDelta !== null && obj.common.custom[adapter.namespace].changesMinDelta !== '') {
168
+ // changesMinDelta
169
+ if (obj.common.custom[adapter.namespace].changesMinDelta || obj.common.custom[adapter.namespace].changesMinDelta === 0) {
118
170
  obj.common.custom[adapter.namespace].changesMinDelta = parseFloat(obj.common.custom[adapter.namespace].changesMinDelta.toString().replace(/,/g, '.')) || 0;
119
171
  } else {
120
172
  obj.common.custom[adapter.namespace].changesMinDelta = adapter.config.changesMinDelta;
121
173
  }
122
174
 
123
- if (!obj.common.custom[adapter.namespace].storageType) obj.common.custom[adapter.namespace].storageType = false;
175
+ // storageType
176
+ if (!obj.common.custom[adapter.namespace].storageType) {
177
+ obj.common.custom[adapter.namespace].storageType = false;
178
+ }
179
+
124
180
 
125
181
  if (adapter._influxDPs[formerAliasId] && !adapter._influxDPs[formerAliasId].storageTypeAdjustedInternally && adapter._influxDPs[formerAliasId][adapter.namespace] && isEqual(obj.common.custom[adapter.namespace], adapter._influxDPs[formerAliasId][adapter.namespace])) {
126
- adapter.log.debug(`Object ${id} unchanged. Ignore`);
182
+ obj.common.custom[adapter.namespace].enableDebugLogs && adapter.log.debug(`Object ${id} unchanged. Ignore`);
127
183
  return;
128
184
  }
129
185
 
186
+ // relogTimeout
187
+ if (adapter._influxDPs[formerAliasId] && adapter._influxDPs[formerAliasId].relogTimeout) {
188
+ clearTimeout(adapter._influxDPs[formerAliasId].relogTimeout);
189
+ adapter._influxDPs[formerAliasId].relogTimeout = null;
190
+ }
191
+
130
192
  const state = adapter._influxDPs[formerAliasId] ? adapter._influxDPs[formerAliasId].state : null;
131
193
  const skipped = adapter._influxDPs[formerAliasId] ? adapter._influxDPs[formerAliasId].skipped : null;
194
+ const timeout = adapter._influxDPs[formerAliasId] ? adapter._influxDPs[formerAliasId].timeout : null;
132
195
 
133
196
  adapter._influxDPs[id] = obj.common.custom;
134
197
  adapter._influxDPs[id].realId = realId;
135
198
  adapter._influxDPs[id].state = state;
136
199
  adapter._influxDPs[id].skipped = skipped;
137
-
138
- adapter._influxDPs[formerAliasId] && adapter._influxDPs[formerAliasId].relogTimeout && clearTimeout(adapter._influxDPs[formerAliasId].relogTimeout);
200
+ adapter._influxDPs[id].timeout = timeout;
139
201
 
140
202
  writeInitialValue(adapter, realId, id);
141
203
 
@@ -148,12 +210,12 @@ function startAdapter(options) {
148
210
 
149
211
  id = formerAliasId;
150
212
 
151
- if (adapter._influxDPs[id]) {
213
+ if (adapter._influxDPs[id] && adapter._influxDPs[id][adapter.namespace]) {
152
214
  adapter._influxDPs[id].relogTimeout && clearTimeout(adapter._influxDPs[id].relogTimeout);
153
215
  adapter._influxDPs[id].timeout && clearTimeout(adapter._influxDPs[id].timeout);
154
216
 
155
217
  delete adapter._influxDPs[id];
156
- adapter.log.info('disabled logging of ' + id);
218
+ adapter.log.info(`disabled logging of ${id}`);
157
219
  }
158
220
  }
159
221
  });
@@ -187,23 +249,13 @@ function startAdapter(options) {
187
249
  return adapter;
188
250
  }
189
251
 
190
- process.on('SIGINT', () => adapter && adapter.setState && finish(adapter));
191
- process.on('SIGTERM', () => adapter && adapter.setState && finish(adapter));
192
-
193
- process.on('uncaughtException', err => {
194
- adapter.log.warn('Exception: ' + err);
195
- if (adapter && adapter.setState) {
196
- finish(adapter);
197
- }
198
- });
199
-
200
252
  function setConnected(adapter, isConnected) {
201
253
  if (adapter._connected !== isConnected) {
202
254
  adapter._connected = isConnected;
203
255
  adapter.setState('info.connection', adapter._connected, true, err =>
204
256
  // analyse if the state could be set (because of permissions)
205
- err ? adapter.log.error('Can not update adapter._connected state: ' + err) :
206
- adapter.log.debug('connected set to ' + adapter._connected));
257
+ err ? adapter.log.error(`Can not update adapter._connected state: ${err}`) :
258
+ adapter.log.debug(`connected set to ${adapter._connected}`));
207
259
  }
208
260
  }
209
261
 
@@ -243,14 +295,20 @@ function ping(adapter) {
243
295
  }
244
296
 
245
297
  function connect(adapter) {
246
- adapter.log.info(`Connecting ${adapter.config.protocol}://${adapter.config.host}:${adapter.config.port} ...`);
298
+ if (!adapter.config.path) {
299
+ adapter.config.path = '';
300
+ } else if (adapter.config.path.startsWith('/')) {
301
+ adapter.config.path = adapter.config.path.substring(1);
302
+ }
303
+
304
+ adapter.log.info(`Connecting ${adapter.config.protocol}://${adapter.config.host}:${adapter.config.port}/${adapter.config.dbversion === '2.x' ? adapter.config.path || '' : ''} ...`);
247
305
 
248
306
  adapter.config.dbname = adapter.config.dbname || appName;
249
307
  adapter.config.validateSSL = adapter.config.validateSSL !== undefined ? !!adapter.config.validateSSL : true;
250
308
 
251
309
  adapter.config.seriesBufferMax = parseInt(adapter.config.seriesBufferMax, 10) || 0;
252
310
 
253
- adapter.log.info('Influx DB Version used: ' + adapter.config.dbversion);
311
+ adapter.log.info(`Influx DB Version used: ${adapter.config.dbversion}`);
254
312
 
255
313
  switch (adapter.config.dbversion) {
256
314
  case '2.x':
@@ -263,6 +321,7 @@ function connect(adapter) {
263
321
  adapter.config.host,
264
322
  adapter.config.port, // optional, default 8086
265
323
  adapter.config.protocol, // optional, default 'http'
324
+ adapter.config.path, // optional, default '/'
266
325
  adapter.config.token,
267
326
  adapter.config.organization,
268
327
  adapter.config.dbname,
@@ -384,7 +443,7 @@ function getRetention(adapter, msg) {
384
443
  }
385
444
 
386
445
  function testConnection(adapter, msg) {
387
- adapter.log.debug('testConnection msg-object: ' + JSON.stringify(msg));
446
+ adapter.log.debug(`testConnection msg-object: ${JSON.stringify(msg)}`);
388
447
  msg.message.config.port = parseInt(msg.message.config.port, 10) || 0;
389
448
  msg.message.config.requestTimeout = parseInt(msg.message.config.requestTimeout) || 30000;
390
449
 
@@ -396,7 +455,7 @@ function testConnection(adapter, msg) {
396
455
  }, 5000);
397
456
 
398
457
  let lClient;
399
- adapter.log.debug('TEST DB Version: ' + msg.message.config.dbversion);
458
+ adapter.log.debug(`TEST DB Version: ${msg.message.config.dbversion}`);
400
459
  switch (msg.message.config.dbversion) {
401
460
  case '2.x':
402
461
  adapter.log.info('Connecting to InfluxDB 2');
@@ -405,6 +464,7 @@ function testConnection(adapter, msg) {
405
464
  msg.message.config.host,
406
465
  msg.message.config.port,
407
466
  msg.message.config.protocol, // optional, default 'http'
467
+ msg.message.config.path, // optional, default '/'
408
468
  msg.message.config.token,
409
469
  msg.message.config.organization,
410
470
  msg.message.config.dbname || appName,
@@ -459,7 +519,7 @@ function destroyDB(adapter, msg) {
459
519
  adapter.sendTo(msg.from, msg.command, {error: null}, msg.callback);
460
520
  // restart adapter
461
521
  setTimeout(() => {
462
- adapter.getForeignObject('system.adapter.' + adapter.namespace, (err, obj) => {
522
+ adapter.getForeignObject(`system.adapter.${adapter.namespace}`, (err, obj) => {
463
523
  if (!err) {
464
524
  adapter.setForeignObject(obj._id, obj);
465
525
  } else {
@@ -523,6 +583,15 @@ function processMessage(adapter, msg) {
523
583
  else if (msg.command === 'resetConflictingPoints') {
524
584
  resetConflictingPoints(adapter, msg);
525
585
  }
586
+ else if (msg.command === 'flushBuffer') {
587
+ const id = msg.message ? msg.message.id : undefined;
588
+ adapter.log.debug(`Flushing buffer for ${id || 'all'}`);
589
+ storeBufferedSeries(adapter, id, error => {
590
+ if (msg.callback) {
591
+ adapter.sendTo(msg.from, msg.command, {error}, msg.callback);
592
+ }
593
+ });
594
+ }
526
595
  else if (msg.command === 'enableHistory') {
527
596
  enableHistory(adapter, msg);
528
597
  }
@@ -557,7 +626,11 @@ function resetConflictingPoints(adapter, msg) {
557
626
 
558
627
  function main(adapter) {
559
628
  adapter.config.port = parseInt(adapter.config.port, 10) || 0;
560
-
629
+ if (adapter.config.relogLastValueOnStart === undefined) {
630
+ adapter.config.relogLastValueOnStart = true;
631
+ } else if (adapter.config.relogLastValueOnStart === 'false') {
632
+ adapter.config.relogLastValueOnStart = false;
633
+ }
561
634
  // set default history if not yet set
562
635
  adapter.getForeignObject('system.config', (err, obj) => {
563
636
  if (obj && obj.common && !obj.common.defaultHistory) {
@@ -577,8 +650,14 @@ function main(adapter) {
577
650
  adapter.config.reconnectInterval = parseInt(adapter.config.reconnectInterval, 10) || 10000;
578
651
  adapter.config.pingInterval = parseInt(adapter.config.pingInterval, 10) || 15000;
579
652
 
580
- if (adapter.config.round !== null && adapter.config.round !== undefined) {
581
- adapter.config.round = Math.pow(10, parseInt(adapter.config.round, 10));
653
+ if (adapter.config.round !== null && adapter.config.round !== undefined && adapter.config.round !== '') {
654
+ adapter.config.round = parseInt(adapter.config.round, 10);
655
+ if (!isFinite(adapter.config.round) || adapter.config.round < 0) {
656
+ adapter.config.round = null;
657
+ adapter.log.info(`Invalid round value: ${adapter.config.round} - ignore, do not round values`);
658
+ } else {
659
+ adapter.config.round = Math.pow(10, parseInt(adapter.config.round, 10));
660
+ }
582
661
  } else {
583
662
  adapter.config.round = null;
584
663
  }
@@ -598,6 +677,27 @@ function main(adapter) {
598
677
  adapter.config.changesMinDelta = 0;
599
678
  }
600
679
 
680
+ if (adapter.config.blockTime !== null && adapter.config.blockTime !== undefined) {
681
+ adapter.config.blockTime = parseInt(adapter.config.blockTime, 10) || 0;
682
+ } else {
683
+ if (adapter.config.debounce !== null && adapter.config.debounce !== undefined) {
684
+ adapter.config.debounce = parseInt(adapter.config.debounce, 10) || 0;
685
+ } else {
686
+ adapter.config.blockTime = 0;
687
+ }
688
+ }
689
+
690
+ if (adapter.config.debounceTime !== null && adapter.config.debounceTime !== undefined) {
691
+ adapter.config.debounceTime = parseInt(adapter.config.debounceTime, 10) || 0;
692
+ } else {
693
+ adapter.config.debounceTime = 0;
694
+ }
695
+
696
+ adapter.config.retention = parseInt(adapter.config.retention, 10) || 0;
697
+ if (adapter.config.retention === -1 ) { // Custom timeframe
698
+ adapter.config.retention = (parseInt(adapter.config.customRetentionDuration, 10) || 0) * 24 * 60 * 60;
699
+ }
700
+
601
701
  // analyse if by the last stop the values were cached into file
602
702
  try {
603
703
  if (fs.statSync(cacheFile).isFile()) {
@@ -617,7 +717,7 @@ function main(adapter) {
617
717
 
618
718
  // read all custom settings
619
719
  adapter.getObjectView('system', 'custom', {}, (err, doc) => {
620
- err && adapter.log.error('main/getObjectView: ' + err);
720
+ err && adapter.log.error(`main/getObjectView: ${err}`);
621
721
  let count = 0;
622
722
  if (doc && doc.rows) {
623
723
  const l = doc.rows.length;
@@ -638,15 +738,62 @@ function main(adapter) {
638
738
  count++;
639
739
  adapter.log.info(`enabled logging of ${id}, Alias=${id !== realId}, ${count} points now activated`);
640
740
 
641
- if (adapter._influxDPs[id][adapter.namespace].debounce !== undefined && adapter._influxDPs[id][adapter.namespace].debounce !== null && adapter._influxDPs[id][adapter.namespace].debounce !== '') {
642
- adapter._influxDPs[id][adapter.namespace].debounce = parseInt(adapter._influxDPs[id][adapter.namespace].debounce, 10) || 0;
741
+ // debounceTime and debounce compatibility handling
742
+ if (!adapter._influxDPs[id][adapter.namespace].blockTime && adapter._influxDPs[id][adapter.namespace].blockTime !== '0' && adapter._influxDPs[id][adapter.namespace].blockTime !== 0) {
743
+ if (!adapter._influxDPs[id][adapter.namespace].debounce && adapter._influxDPs[id][adapter.namespace].debounce !== '0' && adapter._influxDPs[id][adapter.namespace].debounce !== 0) {
744
+ adapter._influxDPs[id][adapter.namespace].blockTime = parseInt(adapter.config.blockTime, 10) || 0;
745
+ } else {
746
+ adapter._influxDPs[id][adapter.namespace].blockTime = parseInt(adapter._influxDPs[id][adapter.namespace].debounce, 10) || 0;
747
+ }
643
748
  } else {
644
- adapter._influxDPs[id][adapter.namespace].debounce = adapter.config.debounce;
749
+ adapter._influxDPs[id][adapter.namespace].blockTime = parseInt(adapter._influxDPs[id][adapter.namespace].blockTime, 10) || 0;
750
+ }
751
+ if (!adapter._influxDPs[id][adapter.namespace].debounceTime && adapter._influxDPs[id][adapter.namespace].debounceTime !== '0' && adapter._influxDPs[id][adapter.namespace].debounceTime !== 0) {
752
+ adapter._influxDPs[id][adapter.namespace].debounceTime = parseInt(adapter.config.debounceTime, 10) || 0;
753
+ } else {
754
+ adapter._influxDPs[id][adapter.namespace].debounceTime = parseInt(adapter._influxDPs[id][adapter.namespace].debounceTime, 10) || 0;
645
755
  }
646
756
 
647
757
  adapter._influxDPs[id][adapter.namespace].changesOnly = adapter._influxDPs[id][adapter.namespace].changesOnly === 'true' || adapter._influxDPs[id][adapter.namespace].changesOnly === true;
648
758
  adapter._influxDPs[id][adapter.namespace].ignoreZero = adapter._influxDPs[id][adapter.namespace].ignoreZero === 'true' || adapter._influxDPs[id][adapter.namespace].ignoreZero === true;
649
- adapter._influxDPs[id][adapter.namespace].ignoreBelowZero = adapter._influxDPs[id][adapter.namespace].ignoreBelowZero === 'true' || adapter._influxDPs[id][adapter.namespace].ignoreBelowZero === true;
759
+
760
+ // round
761
+ if (adapter._influxDPs[id][adapter.namespace].round !== null && adapter._influxDPs[id][adapter.namespace].round !== undefined && adapter._influxDPs[id][adapter.namespace] !== '') {
762
+ adapter._influxDPs[id][adapter.namespace].round = parseInt(adapter._influxDPs[id][adapter.namespace], 10);
763
+ if (!isFinite(adapter._influxDPs[id][adapter.namespace].round) || adapter._influxDPs[id][adapter.namespace].round < 0) {
764
+ adapter._influxDPs[id][adapter.namespace].round = adapter.config.round;
765
+ } else {
766
+ adapter._influxDPs[id][adapter.namespace].round = Math.pow(10, parseInt(adapter._influxDPs[id][adapter.namespace].round, 10));
767
+ }
768
+ } else {
769
+ adapter._influxDPs[id][adapter.namespace].round = adapter.config.round;
770
+ }
771
+
772
+ // ignoreAboveNumber
773
+ if (adapter._influxDPs[id][adapter.namespace].ignoreAboveNumber !== undefined && adapter._influxDPs[id][adapter.namespace].ignoreAboveNumber !== null && adapter._influxDPs[id][adapter.namespace].ignoreAboveNumber !== '') {
774
+ adapter._influxDPs[id][adapter.namespace].ignoreAboveNumber = parseFloat(adapter._influxDPs[id][adapter.namespace].ignoreAboveNumber) || null;
775
+ }
776
+
777
+ // ignoreBelowNumber and ignoreBelowZero compatibility handling
778
+ if (adapter._influxDPs[id][adapter.namespace].ignoreBelowNumber !== undefined && adapter._influxDPs[id][adapter.namespace].ignoreBelowNumber !== null && adapter._influxDPs[id][adapter.namespace].ignoreBelowNumber !== '') {
779
+ adapter._influxDPs[id][adapter.namespace].ignoreBelowNumber = parseFloat(adapter._influxDPs[id][adapter.namespace].ignoreBelowNumber) || null;
780
+ } else if (adapter._influxDPs[id][adapter.namespace].ignoreBelowZero === 'true' || adapter._influxDPs[id][adapter.namespace].ignoreBelowZero === true) {
781
+ adapter._influxDPs[id][adapter.namespace].ignoreBelowNumber = 0;
782
+ }
783
+
784
+ // disableSkippedValueLogging
785
+ if (adapter._influxDPs[id][adapter.namespace].disableSkippedValueLogging !== undefined && adapter._influxDPs[id][adapter.namespace].disableSkippedValueLogging !== null && adapter._influxDPs[id][adapter.namespace].disableSkippedValueLogging !== '') {
786
+ adapter._influxDPs[id][adapter.namespace].disableSkippedValueLogging = adapter._influxDPs[id][adapter.namespace].disableSkippedValueLogging === 'true' || adapter._influxDPs[id][adapter.namespace].disableSkippedValueLogging === true;
787
+ } else {
788
+ adapter._influxDPs[id][adapter.namespace].disableSkippedValueLogging = adapter.config.disableSkippedValueLogging;
789
+ }
790
+
791
+ // enableDebugLogs
792
+ if (adapter._influxDPs[id][adapter.namespace].enableDebugLogs !== undefined && adapter._influxDPs[id][adapter.namespace].enableDebugLogs !== null && adapter._influxDPs[id][adapter.namespace].enableDebugLogs !== '') {
793
+ adapter._influxDPs[id][adapter.namespace].enableDebugLogs = adapter._influxDPs[id][adapter.namespace].enableDebugLogs === 'true' || adapter._influxDPs[id][adapter.namespace].enableDebugLogs === true;
794
+ } else {
795
+ adapter._influxDPs[id][adapter.namespace].enableDebugLogs = adapter.config.enableDebugLogs;
796
+ }
650
797
 
651
798
  if (adapter._influxDPs[id][adapter.namespace].changesRelogInterval !== undefined && adapter._influxDPs[id][adapter.namespace].changesRelogInterval !== null && adapter._influxDPs[id][adapter.namespace].changesRelogInterval !== '') {
652
799
  adapter._influxDPs[id][adapter.namespace].changesRelogInterval = parseInt(adapter._influxDPs[id][adapter.namespace].changesRelogInterval, 10) || 0;
@@ -696,11 +843,13 @@ function main(adapter) {
696
843
  function writeInitialValue(adapter, realId, id) {
697
844
  adapter.getForeignState(realId, (err, state) => {
698
845
  if (state && adapter._influxDPs[id]) {
699
- state.from = 'system.adapter.' + adapter.namespace;
846
+ state.from = `system.adapter.${adapter.namespace}`;
700
847
  adapter._influxDPs[id].state = state;
701
- adapter._tasksStart.push(id);
702
- if (adapter._tasksStart.length === 1 && adapter._connected) {
703
- processStartValues(adapter);
848
+ if (adapter.config.relogLastValueOnStart) {
849
+ adapter._tasksStart.push(id);
850
+ if (adapter._tasksStart.length === 1 && adapter._connected) {
851
+ processStartValues(adapter);
852
+ }
704
853
  }
705
854
  }
706
855
  });
@@ -720,36 +869,86 @@ function pushHistory(adapter, id, state, timerRelog) {
720
869
  }
721
870
 
722
871
  if (typeof state.val === 'string' && settings.storageType !== 'String') {
723
- const f = parseFloat(state.val);
724
- if (f == state.val) {
725
- state.val = f;
872
+ if (isFinite(state.val)) {
873
+ state.val = parseFloat(state.val);
726
874
  }
727
875
  }
728
- if (adapter._influxDPs[id].state && settings.changesOnly && !timerRelog) {
729
- if (settings.changesRelogInterval === 0) {
730
- if (state.ts !== state.lc) {
731
- adapter._influxDPs[id].skipped = state; // remember new timestamp
732
- adapter.log.debug(`value not changed ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
733
- return;
734
- }
735
- } else if (adapter._influxDPs[id].lastLogTime) {
736
- if ((state.ts !== state.lc) && (Math.abs(adapter._influxDPs[id].lastLogTime - state.ts) < settings.changesRelogInterval * 1000)) {
737
- adapter.log.debug(`value not changed ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
738
- adapter._influxDPs[id].skipped = state; // remember new timestamp
739
- return;
740
- }
741
- if (state.ts !== state.lc) {
742
- adapter.log.debug(`value-changed-relog ${id}, value=${state.val}, lastLogTime=${adapter._influxDPs[id].lastLogTime}, ts=${state.ts}`);
743
- }
876
+
877
+ settings.enableDebugLogs && adapter.log.debug(`new value received for ${id} (storageType ${settings.storageType}), new-value=${state.val}, ts=${state.ts}, relog=${timerRelog}`);
878
+
879
+ let ignoreDebonce = false;
880
+
881
+ if (!timerRelog) {
882
+ const valueUnstable = !!adapter._influxDPs[id].timeout;
883
+ // When a debounce timer runs and the value is the same as the last one, ignore it
884
+ if (adapter._influxDPs[id].timeout && state.ts !== state.lc) {
885
+ settings.enableDebugLogs && adapter.log.debug(`value not changed debounce ${id}, value=${state.val}, ts=${state.ts}, debounce timer keeps running`);
886
+ return;
887
+ } else if (adapter._influxDPs[id].timeout) { // if value changed, clear timer
888
+ settings.enableDebugLogs && adapter.log.debug(`value changed during debounce time ${id}, value=${state.val}, ts=${state.ts}, debounce timer restarted`);
889
+ clearTimeout(adapter._influxDPs[id].timeout);
890
+ adapter._influxDPs[id].timeout = null;
891
+ }
892
+
893
+ if (!valueUnstable && settings.blockTime && adapter._influxDPs[id].state && (adapter._influxDPs[id].state.ts + settings.blockTime) > state.ts) {
894
+ settings.enableDebugLogs && adapter.log.debug(`value ignored blockTime ${id}, value=${state.val}, ts=${state.ts}, lastState.ts=${adapter._influxDPs[id].state.ts}, blockTime=${settings.blockTime}`);
895
+ return;
744
896
  }
745
- if (settings.changesMinDelta !== 0 && typeof state.val === 'number' && Math.abs(adapter._influxDPs[id].state.val - state.val) < settings.changesMinDelta) {
746
- adapter.log.debug(`Min-Delta not reached ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
747
- adapter._influxDPs[id].skipped = state; // remember new timestamp
897
+
898
+ if (settings.ignoreZero && (state.val === undefined || state.val === null || state.val === 0)) {
899
+ settings.enableDebugLogs && adapter.log.debug(`value ignore because zero or null ${id}, new-value=${state.val}, ts=${state.ts}`);
900
+ return;
901
+ } else
902
+ if (typeof settings.ignoreBelowNumber === 'number' && typeof state.val === 'number' && state.val < settings.ignoreBelowNumber) {
903
+ settings.enableDebugLogs && adapter.log.debug(`value ignored because below ${settings.ignoreBelowNumber} for ${id}, new-value=${state.val}, ts=${state.ts}`);
748
904
  return;
749
- } else if (typeof state.val === 'number') {
750
- adapter.log.debug(`Min-Delta reached ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
751
- } else {
752
- adapter.log.debug(`Min-Delta ignored because no number ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
905
+ }
906
+ if (typeof settings.ignoreAboveNumber === 'number' && typeof state.val === 'number' && state.val > settings.ignoreAboveNumber) {
907
+ settings.enableDebugLogs && adapter.log.debug(`value ignored because above ${settings.ignoreAboveNumber} for ${id}, new-value=${state.val}, ts=${state.ts}`);
908
+ return;
909
+ }
910
+
911
+ if (adapter._influxDPs[id].state && settings.changesOnly) {
912
+ if (settings.changesRelogInterval === 0) {
913
+ if ((adapter._influxDPs[id].state.val !== null || state.val === null) && state.ts !== state.lc) {
914
+ // remember new timestamp
915
+ if (!valueUnstable && !settings.disableSkippedValueLogging) {
916
+ adapter._influxDPs[id].skipped = state;
917
+ }
918
+ settings.enableDebugLogs && adapter.log.debug(`value not changed ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
919
+ return;
920
+ }
921
+ } else if (adapter._influxDPs[id].lastLogTime) {
922
+ if ((adapter._influxDPs[id].state.val !== null || state.val === null) && (state.ts !== state.lc) && (Math.abs(adapter._influxDPs[id].lastLogTime - state.ts) < settings.changesRelogInterval * 1000)) {
923
+ // remember new timestamp
924
+ if (!valueUnstable && !settings.disableSkippedValueLogging) {
925
+ adapter._influxDPs[id].skipped = state;
926
+ }
927
+ settings.enableDebugLogs && adapter.log.debug(`value not changed ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
928
+ return;
929
+ }
930
+ if (state.ts !== state.lc) {
931
+ settings.enableDebugLogs && adapter.log.debug(`value-not-changed-relog ${id}, value=${state.val}, lastLogTime=${adapter._influxDPs[id].lastLogTime}, ts=${state.ts}`);
932
+ ignoreDebonce = true;
933
+ }
934
+ }
935
+ if (typeof state.val === 'number') {
936
+ if (
937
+ adapter._influxDPs[id].state.val !== null &&
938
+ settings.changesMinDelta !== 0 &&
939
+ Math.abs(adapter._influxDPs[id].state.val - state.val) < settings.changesMinDelta
940
+ ) {
941
+ if (!valueUnstable && !settings.disableSkippedValueLogging) {
942
+ adapter._influxDPs[id].skipped = state;
943
+ }
944
+ settings.enableDebugLogs && adapter.log.debug(`Min-Delta not reached ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
945
+ return;
946
+ } else if (settings.changesMinDelta !== 0) {
947
+ settings.enableDebugLogs && adapter.log.debug(`Min-Delta reached ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
948
+ }
949
+ } else {
950
+ settings.enableDebugLogs && adapter.log.debug(`Min-Delta ignored because no number ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
951
+ }
753
952
  }
754
953
  }
755
954
 
@@ -757,58 +956,65 @@ function pushHistory(adapter, id, state, timerRelog) {
757
956
  clearTimeout(adapter._influxDPs[id].relogTimeout);
758
957
  adapter._influxDPs[id].relogTimeout = null;
759
958
  }
760
- if (settings.changesRelogInterval > 0) {
761
- adapter._influxDPs[id].relogTimeout = setTimeout(() => reLogHelper(adapter, id), settings.changesRelogInterval * 1000);
762
- }
763
-
764
- let ignoreDebounce = false;
765
959
  if (timerRelog) {
960
+ state = Object.assign({}, state);
766
961
  state.ts = Date.now();
767
- state.from = 'system.adapter.' + adapter.namespace;
768
- adapter.log.debug(`timed-relog ${id}, value=${state.val}, lastLogTime=${adapter._influxDPs[id].lastLogTime}, ts=${state.ts}`);
769
- ignoreDebounce = true;
962
+ state.from = `system.adapter.${adapter.namespace}`;
963
+ settings.enableDebugLogs && adapter.log.debug(`timed-relog ${id}, value=${state.val}, lastLogTime=${adapter._influxDPs[id].lastLogTime}, ts=${state.ts}`);
964
+ ignoreDebonce = true;
770
965
  } else {
771
966
  if (settings.changesOnly && adapter._influxDPs[id].skipped) {
772
- adapter._influxDPs[id].state = adapter._influxDPs[id].skipped;
773
- pushHelper(adapter, id);
967
+ settings.enableDebugLogs && adapter.log.debug(`Skipped value logged ${id}, value=${adapter._influxDPs[id].skipped.val}, ts=${adapter._influxDPs[id].skipped.ts}`);
968
+ pushHelper(adapter, id, adapter._influxDPs[id].skipped);
969
+ adapter._influxDPs[id].skipped = null;
774
970
  }
775
971
  if (adapter._influxDPs[id].state && ((adapter._influxDPs[id].state.val === null && state.val !== null) || (adapter._influxDPs[id].state.val !== null && state.val === null))) {
776
- ignoreDebounce = true;
972
+ ignoreDebonce = true;
777
973
  } else if (!adapter._influxDPs[id].state && state.val === null) {
778
- ignoreDebounce = true;
974
+ ignoreDebonce = true;
779
975
  }
780
-
781
- // only store state if really changed
782
- adapter._influxDPs[id].state = state;
783
976
  }
784
977
 
785
- adapter._influxDPs[id].lastLogTime = state.ts;
786
- adapter._influxDPs[id].skipped = null;
787
-
788
- if (settings.debounce && !ignoreDebounce) {
978
+ if (settings.debounceTime && !ignoreDebonce && !timerRelog) {
789
979
  // Discard changes in de-bounce time to store last stable value
790
980
  adapter._influxDPs[id].timeout && clearTimeout(adapter._influxDPs[id].timeout);
791
- adapter._influxDPs[id].timeout = setTimeout(() => pushHelper(adapter, id), settings.debounce);
981
+ adapter._influxDPs[id].timeout = setTimeout((id, state) => {
982
+ adapter._influxDPs[id].timeout = null;
983
+ adapter._influxDPs[id].state = state;
984
+ adapter._influxDPs[id].lastLogTime = state.ts;
985
+ settings.enableDebugLogs && adapter.log.debug(`Value logged ${id}, value=${adapter._influxDPs[id].state.val}, ts=${adapter._influxDPs[id].state.ts}`);
986
+ pushHelper(adapter, id);
987
+ if (settings.changesRelogInterval > 0) {
988
+ adapter._influxDPs[id].relogTimeout = setTimeout(reLogHelper, settings.changesRelogInterval * 1000, adapter, id);
989
+ }
990
+ }, settings.debounceTime, id, state);
792
991
  } else {
793
- pushHelper(adapter, id);
992
+ if (!timerRelog) {
993
+ adapter._influxDPs[id].state = state;
994
+ }
995
+ adapter._influxDPs[id].lastLogTime = state.ts;
996
+
997
+ settings.enableDebugLogs && adapter.log.debug(`Value logged ${id}, value=${adapter._influxDPs[id].state.val}, ts=${adapter._influxDPs[id].state.ts}`);
998
+ pushHelper(adapter, id, state);
999
+ if (settings.changesRelogInterval > 0) {
1000
+ adapter._influxDPs[id].relogTimeout = setTimeout(reLogHelper, settings.changesRelogInterval * 1000, adapter, id);
1001
+ }
794
1002
  }
795
1003
  }
796
1004
  }
797
1005
 
798
1006
  function reLogHelper(adapter, _id) {
799
1007
  if (!adapter._influxDPs[_id]) {
800
- adapter.log.info('non-existing id ' + _id);
1008
+ adapter.log.info(`non-existing id ${_id}`);
801
1009
  return;
802
1010
  }
803
1011
  adapter._influxDPs[_id].relogTimeout = null;
1012
+ adapter._influxDPs[_id].relogTimeout = null;
804
1013
  if (adapter._influxDPs[_id].skipped) {
805
- adapter._influxDPs[_id].state = adapter._influxDPs[_id].skipped;
806
- adapter._influxDPs[_id].state.from = 'system.adapter.' + adapter.namespace;
807
- adapter._influxDPs[_id].skipped = null;
1014
+ pushHistory(adapter, _id, adapter._influxDPs[_id].skipped, true);
1015
+ } else if (adapter._influxDPs[_id].state) {
808
1016
  pushHistory(adapter, _id, adapter._influxDPs[_id].state, true);
809
- }
810
- else {
811
- adapter.getForeignState(adapter._influxDPs[_id].realId, (err, state) => {
1017
+ } else { adapter.getForeignState(adapter._influxDPs[_id].realId, (err, state) => {
812
1018
  if (err) {
813
1019
  adapter.log.info(`init timed Relog: can not get State for ${_id}: ${err}`);
814
1020
  } else if (!state) {
@@ -822,60 +1028,57 @@ function reLogHelper(adapter, _id) {
822
1028
  }
823
1029
  }
824
1030
 
825
- function pushHelper(adapter, _id, cb) {
826
- if (!adapter._influxDPs[_id] || !adapter._influxDPs[_id].state || !adapter._influxDPs[_id][adapter.namespace]) {
1031
+ function pushHelper(adapter, _id, state, cb) {
1032
+ if (!adapter._influxDPs[_id] || !adapter._influxDPs[_id][adapter.namespace] || (!adapter._influxDPs[_id].state && !state)) {
827
1033
  return cb && setImmediate(cb, `ID ${_id} not activated for logging`);
828
1034
  }
1035
+ if (!state) {
1036
+ state = adapter._influxDPs[_id].state;
1037
+ }
1038
+
829
1039
  const _settings = adapter._influxDPs[_id][adapter.namespace];
830
- // if it was not deleted in this time
831
- adapter._influxDPs[_id].timeout = null;
832
1040
 
833
- if (adapter._influxDPs[_id].state.val === null) { // InfluxDB can not handle null values
834
- return cb && setImmediate(cb, `null value for ${_id} can not be handled`);
835
- }
836
- if (adapter._influxDPs[_id].state.val === null) { // InfluxDB can not handle null values
1041
+ if (state.val === null) { // InfluxDB can not handle null values
837
1042
  return cb && setImmediate(cb, `null value for ${_id} can not be handled`);
838
1043
  }
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`);
1044
+ if (typeof state.val === 'number' && !isFinite(state.val)) { // InfluxDB can not handle Infinite values
1045
+ return cb && setImmediate(cb, `Non Finite value ${state.val} for ${_id} can not be handled`);
841
1046
  }
842
1047
 
843
- if (typeof adapter._influxDPs[_id].state.val === 'object') {
844
- adapter._influxDPs[_id].state.val = JSON.stringify(adapter._influxDPs[_id].state.val);
1048
+ if (state.val !== null && (typeof state.val === 'object' || typeof state.val === 'undefined')) {
1049
+ state.val = JSON.stringify(state.val);
845
1050
  }
846
1051
 
847
- adapter.log.debug(`Datatype ${_id}: Currently: ${typeof adapter._influxDPs[_id].state.val}, StorageType: ${_settings.storageType}`);
848
- if (typeof adapter._influxDPs[_id].state.val === 'string' && _settings.storageType !== 'String') {
849
- adapter.log.debug('Do Automatic Datatype conversion for ' + _id);
850
- const f = parseFloat(adapter._influxDPs[_id].state.val);
851
- if (f == adapter._influxDPs[_id].state.val) {
852
- adapter._influxDPs[_id].state.val = f;
853
- } else if (adapter._influxDPs[_id].state.val === 'true') {
854
- adapter._influxDPs[_id].state.val = true;
855
- } else if (adapter._influxDPs[_id].state.val === 'false') {
856
- adapter._influxDPs[_id].state.val = false;
1052
+ _settings.enableDebugLogs && adapter.log.debug(`Datatype ${_id}: Currently: ${typeof state.val}, StorageType: ${_settings.storageType}`);
1053
+ if (typeof state.val === 'string' && _settings.storageType !== 'String') {
1054
+ _settings.enableDebugLogs && adapter.log.debug(`Do Automatic Datatype conversion for ${_id}`);
1055
+ if (isFinite(state.val)) {
1056
+ state.val = parseFloat(state.val);
1057
+ } else if (state.val === 'true') {
1058
+ state.val = true;
1059
+ } else if (state.val === 'false') {
1060
+ state.val = false;
857
1061
  }
858
1062
  }
859
- if (_settings.storageType === 'String' && typeof adapter._influxDPs[_id].state.val !== 'string') {
860
- adapter._influxDPs[_id].state.val = adapter._influxDPs[_id].state.val.toString();
1063
+ if (_settings.storageType === 'String' && typeof state.val !== 'string') {
1064
+ state.val = state.val.toString();
861
1065
  }
862
- else if (_settings.storageType === 'Number' && typeof adapter._influxDPs[_id].state.val !== 'number') {
863
- if (typeof adapter._influxDPs[_id].state.val === 'boolean') {
864
- adapter._influxDPs[_id].state.val = adapter._influxDPs[_id].state.val?1:0;
1066
+ else if (_settings.storageType === 'Number' && typeof state.val !== 'number') {
1067
+ if (typeof state.val === 'boolean') {
1068
+ state.val = state.val ? 1 : 0;
865
1069
  }
866
1070
  else {
867
- adapter.log.info(`Do not store value "${adapter._influxDPs[_id].state.val}" for ${_id} because no number`);
1071
+ adapter.log.info(`Do not store value "${state.val}" for ${_id} because no number`);
868
1072
  return cb && setImmediate(cb, `do not store value for ${_id} because no number`);
869
1073
  }
870
1074
  }
871
- else if (_settings.storageType === 'Boolean' && typeof adapter._influxDPs[_id].state.val !== 'boolean') {
872
- adapter._influxDPs[_id].state.val = !!adapter._influxDPs[_id].state.val;
1075
+ else if (_settings.storageType === 'Boolean' && typeof state.val !== 'boolean') {
1076
+ state.val = !!state.val;
873
1077
  }
874
- pushValueIntoDB(adapter, _id, adapter._influxDPs[_id].state, () =>
875
- cb && setImmediate(cb));
1078
+ pushValueIntoDB(adapter, _id, state, false,() => cb && setImmediate(cb));
876
1079
  }
877
1080
 
878
- function pushValueIntoDB(adapter, id, state, cb) {
1081
+ function pushValueIntoDB(adapter, id, state, directWrite, cb) {
879
1082
  if (!adapter._client) {
880
1083
  adapter.log.warn('No connection to DB');
881
1084
  return cb && cb('No connection to DB');
@@ -888,20 +1091,8 @@ function pushValueIntoDB(adapter, id, state, cb) {
888
1091
  return cb && cb(`InfluxDB can not handle non finite values like ${state.val}`);
889
1092
  }
890
1093
 
891
- if (adapter._influxDPs[id] && adapter._influxDPs[id][adapter.namespace] && adapter._influxDPs[id][adapter.namespace].ignoreZero && state.val === 0) {
892
- adapter.log.debug(`pushValueIntoDB called for ${id} was ignored because the value zero or null`);
893
- return cb && cb();
894
- } else
895
- if (state && adapter._influxDPs[id] && adapter._influxDPs[id][adapter.namespace] && adapter._influxDPs[id][adapter.namespace].ignoreBelowZero && typeof state.val === 'number' && state.val < 0) {
896
- adapter.log.debug(`pushValueIntoDB called for ${id} and state: ${JSON.stringify(state)} was ignored because the value is below 0`);
897
- return cb && cb();
898
- }
899
-
900
1094
  state.ts = parseInt(state.ts, 10);
901
1095
 
902
- // if less 2000.01.01 00:00:00
903
- if (state.ts < 946681200000) state.ts *= 1000;
904
-
905
1096
  if (typeof state.val === 'object') {
906
1097
  state.val = JSON.stringify(state.val);
907
1098
  }
@@ -926,7 +1117,7 @@ function pushValueIntoDB(adapter, id, state, cb) {
926
1117
  ack: !!state.ack
927
1118
  };
928
1119
 
929
- if ((adapter._conflictingPoints[id] || adapter.config.seriesBufferMax === 0) && (adapter._connected && adapter._client.request && adapter._client.request.getHostsAvailable().length > 0)) {
1120
+ if ((adapter._conflictingPoints[id] || adapter.config.seriesBufferMax === 0 || directWrite) && (adapter._connected && adapter._client.request && adapter._client.request.getHostsAvailable().length > 0)) {
930
1121
  if (adapter.config.seriesBufferMax !== 0) {
931
1122
  adapter.log.debug(`Direct writePoint("${id} - ${influxFields.value} / ${influxFields.time}")`);
932
1123
  }
@@ -958,23 +1149,43 @@ function addPointToSeriesBuffer(adapter, id, stateObj, cb) {
958
1149
  }
959
1150
  }
960
1151
 
961
- function storeBufferedSeries(adapter, cb) {
1152
+ function storeBufferedSeries(adapter, id, cb) {
1153
+ if (typeof id === 'function') {
1154
+ cb = id;
1155
+ id = null;
1156
+ }
1157
+ if (id && (!adapter._seriesBuffer[id] || !adapter._seriesBuffer[id].length)) {
1158
+ return cb && cb(null, 0);
1159
+ }
962
1160
  if (Object.keys(adapter._seriesBuffer).length === 0) {
963
- return cb && cb();
1161
+ return cb && cb(null, 0);
964
1162
  }
965
1163
 
966
1164
  if (!adapter._client || adapter._client.request.getHostsAvailable().length === 0) {
967
1165
  setConnected(adapter, false);
968
- adapter.log.info('Currently no hosts available, try later');
1166
+ adapter.log.info('Currently no hosts available, try later', 0);
969
1167
  adapter._seriesBufferFlushPlanned = false;
970
- return cb && cb('Currently no hosts available, try later');
1168
+ return cb && cb('Currently no hosts available, try later', 0);
971
1169
  }
972
1170
  if (!adapter._connected) {
973
- adapter.log.info('Not connected to InfluxDB, try later');
1171
+ adapter.log.info('Not connected to InfluxDB, try later', 0);
974
1172
  adapter._seriesBufferFlushPlanned = false;
975
- return cb && cb('Not connected to InfluxDB, try later');
1173
+ return cb && cb('Not connected to InfluxDB, try later', 0);
1174
+ }
1175
+
1176
+ if (id) {
1177
+ const idSeries = adapter._seriesBuffer[id];
1178
+ adapter._seriesBuffer[id] = [];
1179
+ adapter.log.debug(`Store ${idSeries.length} buffered influxDB history points for ${id}`);
1180
+ adapter._seriesBufferCounter -= idSeries.length;
1181
+ writeSeriesPerID(adapter, id, idSeries, err => cb && cb(err, idSeries.length));
1182
+ return;
1183
+ }
1184
+
1185
+ if (adapter._seriesBufferChecker) {
1186
+ clearInterval(adapter._seriesBufferChecker);
1187
+ adapter._seriesBufferChecker = null;
976
1188
  }
977
- adapter._seriesBufferChecker && clearInterval(adapter._seriesBufferChecker);
978
1189
 
979
1190
  adapter.log.info(`Store ${adapter._seriesBufferCounter} buffered influxDB history points`);
980
1191
 
@@ -982,9 +1193,9 @@ function storeBufferedSeries(adapter, cb) {
982
1193
  if (adapter._seriesBufferCounter > 15000) {
983
1194
  // if we have too many data points in buffer; we better writer them per id
984
1195
  adapter.log.info(`Too many data points (${adapter._seriesBufferCounter}) to write at once; write per ID`);
985
- writeAllSeriesPerID(adapter, currentBuffer, cb);
1196
+ writeAllSeriesPerID(adapter, currentBuffer, err => cb && cb(err, adapter._seriesBufferCounter));
986
1197
  } else {
987
- writeAllSeriesAtOnce(adapter, currentBuffer, cb);
1198
+ writeAllSeriesAtOnce(adapter, currentBuffer, err => cb && cb(err, adapter._seriesBufferCounter));
988
1199
  }
989
1200
  adapter._seriesBuffer = {};
990
1201
  adapter._seriesBufferCounter = 0;
@@ -996,7 +1207,7 @@ function storeBufferedSeries(adapter, cb) {
996
1207
  function writeAllSeriesAtOnce(adapter, series, cb) {
997
1208
  adapter._client.writeSeries(series, (err /* , result */) => {
998
1209
  if (err) {
999
- adapter.log.warn('Error on writeSeries: ' + err);
1210
+ adapter.log.warn(`Error on writeSeries: ${err}`);
1000
1211
  if (adapter._client.request.getHostsAvailable().length === 0) {
1001
1212
  setConnected(adapter, false);
1002
1213
  adapter.log.info('Host not available, move all points back in the Buffer');
@@ -1037,7 +1248,7 @@ function writeAllSeriesPerID(adapter, series, cb, idList) {
1037
1248
 
1038
1249
  function writeSeriesPerID(adapter, seriesId, points, cb) {
1039
1250
  if (!points.length) {
1040
- return cb && cb();
1251
+ return cb && setImmediate(cb);
1041
1252
  }
1042
1253
  adapter.log.debug(`writePoints ${points.length} for ${seriesId} at once`);
1043
1254
 
@@ -1104,6 +1315,7 @@ function writeOnePointForID(adapter, pointId, point, directWrite, cb) {
1104
1315
  } else if (err.message && typeof err.message === 'string' && err.message.includes('field type conflict')) {
1105
1316
  // retry write after type correction for some easy cases
1106
1317
  let retry = false;
1318
+ let adjustType = false;
1107
1319
  if (adapter._influxDPs[pointId] && adapter._influxDPs[pointId][adapter.namespace] && !adapter._influxDPs[pointId][adapter.namespace].storageType) {
1108
1320
  let convertDirection = '';
1109
1321
  if (err.message.includes('is type bool, already exists as type float') ||
@@ -1117,6 +1329,7 @@ function writeOnePointForID(adapter, pointId, point, directWrite, cb) {
1117
1329
  point.value = 0;
1118
1330
  retry = true;
1119
1331
  }
1332
+ adjustType = true;
1120
1333
  adapter._influxDPs[pointId][adapter.namespace].storageType = 'Number';
1121
1334
  adapter._influxDPs[pointId].storageTypeAdjustedInternally = true;
1122
1335
  }
@@ -1131,18 +1344,30 @@ function writeOnePointForID(adapter, pointId, point, directWrite, cb) {
1131
1344
  point.value = false;
1132
1345
  retry = true;
1133
1346
  }
1347
+ adjustType = true;
1134
1348
  adapter._influxDPs[pointId][adapter.namespace].storageType = 'Boolean';
1135
1349
  adapter._influxDPs[pointId].storageTypeAdjustedInternally = true;
1136
1350
  }
1137
1351
  else if (err.message.includes(', already exists as type string')) {
1138
1352
  point.value = point.value.toString();
1139
1353
  retry = true;
1354
+ adjustType = true;
1140
1355
  adapter._influxDPs[pointId][adapter.namespace].storageType = 'String';
1141
1356
  adapter._influxDPs[pointId].storageTypeAdjustedInternally = true;
1357
+ } else if (err.message.includes('is type string, already exists as type float')) {
1358
+ if (isFinite(point.value)) {
1359
+ point.value = parseFloat(point.value);
1360
+ retry = true;
1361
+ }
1362
+ adjustType = true;
1363
+ adapter._influxDPs[pointId][adapter.namespace].storageType = 'Number';
1364
+ adapter._influxDPs[pointId].storageTypeAdjustedInternally = true;
1142
1365
  }
1143
1366
  if (retry) {
1144
1367
  adapter.log.info(`Try to convert ${convertDirection} and re-write for ${pointId} and set storageType to ${adapter._influxDPs[pointId][adapter.namespace].storageType}`);
1145
1368
  writeOnePointForID(adapter, pointId, point, true, cb);
1369
+ }
1370
+ if (adjustType) {
1146
1371
  const obj = {};
1147
1372
  obj.common = {};
1148
1373
  obj.common.custom = {};
@@ -1152,7 +1377,7 @@ function writeOnePointForID(adapter, pointId, point, directWrite, cb) {
1152
1377
  if (err) {
1153
1378
  adapter.log.error(`error updating history config for ${pointId} to pin datatype: ${err}`);
1154
1379
  } else {
1155
- adapter.log.info('changed history configuration to pin detected datatype for ' + pointId);
1380
+ adapter.log.info(`changed history configuration to pin detected datatype for ${pointId}`);
1156
1381
  }
1157
1382
  });
1158
1383
  }
@@ -1196,7 +1421,7 @@ function writeFileBufferToDisk() {
1196
1421
  adapter.log.warn(`Store data for ${fileData.seriesBufferCounter} points and ${Object.keys(fileData.conflictingPoints).length} conflicts`);
1197
1422
  }
1198
1423
  catch (err) {
1199
- adapter.log.warn('Could not save non-stored data to file: ' + err);
1424
+ adapter.log.warn(`Could not save non-stored data to file: ${err}`);
1200
1425
  }
1201
1426
  }
1202
1427
  adapter._seriesBufferCounter = null;
@@ -1222,7 +1447,7 @@ function _delete(adapter, id, state, cb) {
1222
1447
  adapter._client.query(query, err => {
1223
1448
  if (err) {
1224
1449
  adapter.log.warn(`Error on delete("${query}): ${err} / ${JSON.stringify(err.message)}"`);
1225
- cb(err);
1450
+ cb && cb(err);
1226
1451
  } else {
1227
1452
  setConnected(adapter, true);
1228
1453
  }
@@ -1237,7 +1462,7 @@ function deleteState(adapter, msg) {
1237
1462
  if (!msg.message) {
1238
1463
  adapter.log.error('deleteState called with invalid data');
1239
1464
  return adapter.sendTo(msg.from, msg.command, {
1240
- error: 'Invalid call: ' + JSON.stringify(msg)
1465
+ error: `Invalid call: ${JSON.stringify(msg)}`
1241
1466
  }, msg.callback);
1242
1467
  }
1243
1468
  let id;
@@ -1272,7 +1497,7 @@ function deleteState(adapter, msg) {
1272
1497
  }
1273
1498
  _delete(adapter, id, {start: msg.message[i].state.start, end: msg.message[i].state.end || Date.now()});
1274
1499
  } else {
1275
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message[i]));
1500
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
1276
1501
  }
1277
1502
  }
1278
1503
  } else if (msg.message.state && Array.isArray(msg.message.state)) {
@@ -1295,7 +1520,7 @@ function deleteState(adapter, msg) {
1295
1520
  } else if (msg.message.state[j] && typeof msg.message.state[j] === 'number') {
1296
1521
  _delete(adapter, id, {ts: msg.message.state[j]});
1297
1522
  } else {
1298
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message.state[j]));
1523
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
1299
1524
  }
1300
1525
  }
1301
1526
  } else if (msg.message.ts && Array.isArray(msg.message.ts)) {
@@ -1305,7 +1530,7 @@ function deleteState(adapter, msg) {
1305
1530
  if (msg.message.ts[j] && typeof msg.message.ts[j] === 'number') {
1306
1531
  _delete(adapter, id, {ts: msg.message.ts[j]});
1307
1532
  } else {
1308
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message.ts[j]));
1533
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message.ts[j])}`);
1309
1534
  }
1310
1535
  }
1311
1536
  } else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
@@ -1326,7 +1551,7 @@ function deleteState(adapter, msg) {
1326
1551
  }, msg.callback));
1327
1552
  } else {
1328
1553
  adapter.log.error('deleteState called with invalid data');
1329
- return adapter.sendTo(msg.from, msg.command, {error: 'Invalid call: ' + JSON.stringify(msg)}, msg.callback);
1554
+ return adapter.sendTo(msg.from, msg.command, {error: `Invalid call: ${JSON.stringify(msg)}`}, msg.callback);
1330
1555
  }
1331
1556
 
1332
1557
  setTimeout(() => {
@@ -1341,7 +1566,7 @@ function deleteStateAll(adapter, msg) {
1341
1566
  if (!msg.message) {
1342
1567
  adapter.log.error('deleteState called with invalid data');
1343
1568
  return adapter.sendTo(msg.from, msg.command, {
1344
- error: 'Invalid call: ' + JSON.stringify(msg)
1569
+ error: `Invalid call: ${JSON.stringify(msg)}`
1345
1570
  }, msg.callback);
1346
1571
  }
1347
1572
  let id;
@@ -1369,7 +1594,7 @@ function deleteStateAll(adapter, msg) {
1369
1594
  });
1370
1595
  } else {
1371
1596
  adapter.log.error('deleteStateAll called with invalid data');
1372
- return adapter.sendTo(msg.from, msg.command, {error: 'Invalid call: ' + JSON.stringify(msg)}, msg.callback);
1597
+ return adapter.sendTo(msg.from, msg.command, {error: `Invalid call: ${JSON.stringify(msg)}`}, msg.callback);
1373
1598
  }
1374
1599
  }
1375
1600
 
@@ -1384,7 +1609,7 @@ function update(adapter, id, state, cb) {
1384
1609
  adapter._client.query(query, (err, result) => {
1385
1610
  if (err) {
1386
1611
  adapter.log.warn(`Error on update("${query}): ${err} / ${JSON.stringify(err.message)}"`);
1387
- cb(err);
1612
+ cb && cb(err);
1388
1613
  } else {
1389
1614
  setConnected(adapter, true);
1390
1615
 
@@ -1409,10 +1634,9 @@ function update(adapter, id, state, cb) {
1409
1634
  _delete(adapter, id, {ts: stored.ts}, error => {
1410
1635
  if (error) {
1411
1636
  adapter.log.error(`Cannot delete value for ${id}: ${JSON.stringify(state)}`);
1412
- cb(err);
1637
+ cb && cb(err);
1413
1638
  } else {
1414
- pushValueIntoDB(adapter, id, stored);
1415
- cb && cb();
1639
+ pushValueIntoDB(adapter, id, stored, true, cb);
1416
1640
  }
1417
1641
  });
1418
1642
  } else {
@@ -1430,7 +1654,7 @@ function updateState(adapter, msg) {
1430
1654
  if (!msg.message) {
1431
1655
  adapter.log.error('updateState called with invalid data');
1432
1656
  return adapter.sendTo(msg.from, msg.command, {
1433
- error: 'Invalid call: ' + JSON.stringify(msg)
1657
+ error: `Invalid call: ${JSON.stringify(msg)}`
1434
1658
  }, msg.callback);
1435
1659
  }
1436
1660
  let id;
@@ -1442,7 +1666,7 @@ function updateState(adapter, msg) {
1442
1666
  if (msg.message[i].state && typeof msg.message[i].state === 'object') {
1443
1667
  update(adapter, id, msg.message[i].state);
1444
1668
  } else {
1445
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message[i]));
1669
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
1446
1670
  }
1447
1671
  }
1448
1672
  adapter.sendTo(msg.from, msg.command, {
@@ -1450,13 +1674,13 @@ function updateState(adapter, msg) {
1450
1674
  connected: !!adapter._connected
1451
1675
  }, msg.callback);
1452
1676
  } else if (msg.message.state && Array.isArray(msg.message.state)) {
1453
- adapter.log.debug('updateState ' + msg.message.state.length + ' items');
1677
+ adapter.log.debug(`updateState ${msg.message.state.length} items`);
1454
1678
  id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1455
1679
  for (let j = 0; j < msg.message.state.length; j++) {
1456
1680
  if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
1457
1681
  update(adapter, id, msg.message.state[j]);
1458
1682
  } else {
1459
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message.state[j]));
1683
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
1460
1684
  }
1461
1685
  }
1462
1686
  adapter.sendTo(msg.from, msg.command, {
@@ -1474,7 +1698,7 @@ function updateState(adapter, msg) {
1474
1698
  } else {
1475
1699
  adapter.log.error('updateState called with invalid data');
1476
1700
  adapter.sendTo(msg.from, msg.command, {
1477
- error: 'Invalid call: ' + JSON.stringify(msg)
1701
+ error: `Invalid call: ${JSON.stringify(msg)}`
1478
1702
  }, msg.callback);
1479
1703
  }
1480
1704
  }
@@ -1483,19 +1707,24 @@ function storeState(adapter, msg) {
1483
1707
  if (!msg.message) {
1484
1708
  adapter.log.error('storeState called with invalid data');
1485
1709
  return adapter.sendTo(msg.from, msg.command, {
1486
- error: 'Invalid call: ' + JSON.stringify(msg)
1710
+ error: `Invalid call: ${JSON.stringify(msg)}`
1487
1711
  }, msg.callback);
1488
1712
  }
1489
1713
 
1714
+ let pushFunc = pushHelper;
1715
+ if (msg.message.rules) {
1716
+ pushFunc = pushHistory;
1717
+ }
1718
+
1490
1719
  let id;
1491
1720
  if (Array.isArray(msg.message)) {
1492
1721
  adapter.log.debug(`storeState ${msg.message.length} items`);
1493
1722
  for (let i = 0; i < msg.message.length; i++) {
1494
1723
  id = adapter._aliasMap[msg.message[i].id] ? adapter._aliasMap[msg.message[i].id] : msg.message[i].id;
1495
1724
  if (msg.message[i].state && typeof msg.message[i].state === 'object') {
1496
- pushValueIntoDB(adapter, id, msg.message[i].state);
1725
+ pushFunc(adapter, id, msg.message[i].state);
1497
1726
  } else {
1498
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message[i]));
1727
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
1499
1728
  }
1500
1729
  }
1501
1730
  } else if (msg.message.state && Array.isArray(msg.message.state)) {
@@ -1503,7 +1732,7 @@ function storeState(adapter, msg) {
1503
1732
  id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1504
1733
  for (let j = 0; j < msg.message.state.length; j++) {
1505
1734
  if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
1506
- pushValueIntoDB(adapter, id, msg.message.state[j]);
1735
+ pushFunc(adapter, id, msg.message.state[j]);
1507
1736
  } else {
1508
1737
  adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
1509
1738
  }
@@ -1511,7 +1740,7 @@ function storeState(adapter, msg) {
1511
1740
  } else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
1512
1741
  adapter.log.debug('storeState 1 item');
1513
1742
  id = adapter._aliasMap[msg.message.id] ? adapter._aliasMap[msg.message.id] : msg.message.id;
1514
- pushValueIntoDB(adapter, id, msg.message.state);
1743
+ pushFunc(adapter, id, msg.message.state);
1515
1744
  } else {
1516
1745
  adapter.log.error('storeState called with invalid data');
1517
1746
  return adapter.sendTo(msg.from, msg.command, {
@@ -1581,10 +1810,9 @@ function finish(adapter, callback) {
1581
1810
  }
1582
1811
  const state = adapter._influxDPs[id].state ? tmpState : null;
1583
1812
  */
1584
- if (adapter._influxDPs[id].skipped) {
1813
+ if (adapter._influxDPs[id].skipped && !(adapter._influxDPs[id][adapter.namespace] && adapter._influxDPs[id][adapter.namespace].disableSkippedValueLogging)) {
1585
1814
  count++;
1586
- adapter._influxDPs[id].state = adapter._influxDPs[id].skipped;
1587
- pushHelper(adapter, id, () => {
1815
+ pushHelper(adapter, id, adapter._influxDPs[id].skipped, () => {
1588
1816
  if (!--count) {
1589
1817
  writeFileBufferToDisk();
1590
1818
  if (callback) {
@@ -1609,9 +1837,21 @@ function finish(adapter, callback) {
1609
1837
  }
1610
1838
  }
1611
1839
 
1840
+ function sortByTs(a, b) {
1841
+ const aTs = a.ts;
1842
+ const bTs = b.ts;
1843
+ return (aTs < bTs) ? -1 : ((aTs > bTs) ? 1 : 0);
1844
+ }
1845
+
1612
1846
  function getHistory(adapter, msg) {
1613
1847
  const startTime = Date.now();
1614
1848
 
1849
+ if (!msg.message || !msg.message.options) {
1850
+ return adapter.sendTo(msg.from, msg.command, {
1851
+ error: 'Invalid call. No options for getHistory provided'
1852
+ }, msg.callback);
1853
+ }
1854
+
1615
1855
  const options = {
1616
1856
  id: msg.message.id === '*' ? null : msg.message.id,
1617
1857
  start: msg.message.options.start,
@@ -1619,16 +1859,97 @@ function getHistory(adapter, msg) {
1619
1859
  step: parseInt(msg.message.options.step, 10) || null,
1620
1860
  count: parseInt(msg.message.options.count, 10) || 500,
1621
1861
  aggregate: msg.message.options.aggregate || 'average', // One of: max, min, average, total
1622
- limit: parseInt(msg.message.options.limit || adapter.config.limit || 2000),
1862
+ limit: parseInt(msg.message.options.limit, 10) || parseInt(msg.message.options.count, 10) || adapter.config.limit || 2000,
1623
1863
  addId: msg.message.options.addId || false,
1624
1864
  ignoreNull: true,
1625
- sessionId: msg.message.options.sessionId
1865
+ sessionId: msg.message.options.sessionId,
1866
+ returnNewestEntries: msg.message.options.returnNewestEntries || false,
1867
+ percentile: msg.message.options.aggregate === 'percentile' ? parseInt(msg.message.options.percentile, 10) || 50 : null,
1868
+ quantile: msg.message.options.aggregate === 'quantile' ? parseFloat(msg.message.options.quantile) || 0.5 : null,
1869
+ integralUnit: msg.message.options.aggregate === 'integral' ? parseInt(msg.message.options.integralUnit, 10) || 60 : null,
1870
+ integralInterpolation: msg.message.options.aggregate === 'integral' ? msg.message.options.integralInterpolation || 'none' : null,
1871
+ removeBorderValues: msg.message.options.removeBorderValues || false,
1872
+ logId: (msg.message.id ? msg.message.id : 'all') + Date.now() + Math.random()
1626
1873
  };
1627
1874
 
1875
+ if (!options.start && options.count) {
1876
+ options.returnNewestEntries = true;
1877
+ }
1878
+
1879
+ if (msg.message.options.round !== null && msg.message.options.round !== undefined && msg.message.options.round !== '') {
1880
+ msg.message.options.round = parseInt(msg.message.options.round, 10);
1881
+ if (!isFinite(msg.message.options.round) || msg.message.options.round < 0) {
1882
+ options.round = adapter.config.round;
1883
+ } else {
1884
+ options.round = Math.pow(10, parseInt(msg.message.options.round, 10));
1885
+ }
1886
+ } else {
1887
+ options.round = adapter.config.round;
1888
+ }
1889
+
1890
+ const debugLog = options.debugLog = !!(adapter._influxDPs[options.id] && adapter._influxDPs[options.id][adapter.namespace] && adapter._influxDPs[options.id][adapter.namespace].enableDebugLogs);
1891
+
1892
+ debugLog && adapter.log.debug(`${options.logId} getHistory (InfluxDB1) call: ${JSON.stringify(options)}`);
1893
+
1628
1894
  if (options.id && adapter._aliasMap[options.id]) {
1629
1895
  options.id = adapter._aliasMap[options.id];
1630
1896
  }
1631
1897
 
1898
+ if (options.aggregate === 'percentile' && options.percentile < 0 || options.percentile > 100) {
1899
+ adapter.log.error(`Invalid percentile value: ${options.percentile}, use 50 as default`);
1900
+ options.percentile = 50;
1901
+ }
1902
+
1903
+ if (options.aggregate === 'quantile' && options.quantile < 0 || options.quantile > 1) {
1904
+ adapter.log.error(`Invalid quantile value: ${options.quantile}, use 0.5 as default`);
1905
+ options.quantile = 0.5;
1906
+ }
1907
+
1908
+ if (options.aggregate === 'integral' && (typeof options.integralUnit !== 'number' || options.integralUnit <= 0)) {
1909
+ adapter.log.error(`Invalid integralUnit value: ${options.integralUnit}, use 60s as default`);
1910
+ options.integralUnit = 60;
1911
+ }
1912
+
1913
+ if (!adapter._influxDPs[options.id]) {
1914
+ adapter.sendTo(msg.from, msg.command, {
1915
+ result: [],
1916
+ step: 0,
1917
+ error: `Logging not activated for ${options.id}`
1918
+ }, msg.callback);
1919
+ return;
1920
+ }
1921
+
1922
+ if (options.start > options.end) {
1923
+ const _end = options.end;
1924
+ options.end = options.start;
1925
+ options.start = _end;
1926
+ }
1927
+
1928
+ if (!options.start && !options.count) {
1929
+ options.start = options.end - 86400000; // - 1 day
1930
+ }
1931
+
1932
+ let resultsFromInfluxDB = options.aggregate !== 'onchange' && options.aggregate !== 'none' && options.aggregate !== 'minmax';
1933
+ if (options.aggregate === 'integral' && options.integralInterpolation === 'linear') {
1934
+ resultsFromInfluxDB = false;
1935
+ }
1936
+
1937
+ // query one timegroup-value more than requested originally at start and end
1938
+ // to make sure to have no 0 values because of the way InfluxDB does group by time
1939
+
1940
+ if (resultsFromInfluxDB) {
1941
+ if (!options.step) {
1942
+ // calculate "step" based on difference between start and end using count
1943
+ options.step = Math.round((options.end - options.start) / options.count);
1944
+ }
1945
+ if (options.start) {
1946
+ options.start -= options.step;
1947
+ }
1948
+ options.end += options.step;
1949
+ options.limit += 2;
1950
+ }
1951
+
1952
+ options.preAggregated = true;
1632
1953
  let query = 'SELECT';
1633
1954
  if (options.step) {
1634
1955
  switch (options.aggregate) {
@@ -1644,6 +1965,23 @@ function getHistory(adapter, msg) {
1644
1965
  query += ' min(value) as val';
1645
1966
  break;
1646
1967
 
1968
+ case 'percentile':
1969
+ query += ` percentile(value, ${options.percentile}) as val`;
1970
+ break;
1971
+
1972
+ case 'quantile':
1973
+ query += ` percentile(value, ${options.quantile * 100}) as val`;
1974
+ break;
1975
+
1976
+ case 'integral':
1977
+ if (options.integralInterpolation === 'linear') {
1978
+ query += ' value';
1979
+ options.preAggregated = false;
1980
+ } else {
1981
+ query += ` integral(value, ${options.integralUnit}s) as val`;
1982
+ }
1983
+ break;
1984
+
1647
1985
  case 'total':
1648
1986
  query += ' sum(value) as val';
1649
1987
  break;
@@ -1656,6 +1994,7 @@ function getHistory(adapter, msg) {
1656
1994
  case 'onchange':
1657
1995
  case 'minmax':
1658
1996
  query += ' value';
1997
+ options.preAggregated = false;
1659
1998
  break;
1660
1999
 
1661
2000
  default:
@@ -1665,69 +2004,35 @@ function getHistory(adapter, msg) {
1665
2004
 
1666
2005
  } else {
1667
2006
  query += ' *';
2007
+ options.preAggregated = false;
1668
2008
  }
1669
2009
 
1670
2010
  query += ` from "${options.id}"`;
1671
2011
 
1672
- if (!adapter._influxDPs[options.id]) {
1673
- adapter.sendTo(msg.from, msg.command, {
1674
- result: [],
1675
- step: 0,
1676
- error: 'No connection'
1677
- }, msg.callback);
1678
- return;
1679
- }
1680
-
1681
- if (options.start > options.end) {
1682
- const _end = options.end;
1683
- options.end = options.start;
1684
- options.start = _end;
1685
- }
1686
-
1687
- // if less 2000.01.01 00:00:00
1688
- if (options.end && options.end < 946681200000) {
1689
- options.end *= 1000;
1690
- }
1691
- if (options.start && options.start < 946681200000) {
1692
- options.start *= 1000;
1693
- }
1694
-
1695
- if (!options.start && !options.count) {
1696
- options.start = options.end - 86400000; // - 1 day
1697
- }
1698
-
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
1701
- if (options.aggregate !== 'onchange' && options.aggregate !== 'none' && options.aggregate !== 'minmax') {
1702
- if (!options.step) {
1703
- // calculate "step" based on difference between start and end using count
1704
- options.step = parseInt((options.end - options.start) / options.count, 10);
1705
- }
1706
- if (options.start) {
1707
- options.start -= options.step;
1708
- }
1709
- options.end += options.step;
1710
- options.limit += 2;
1711
- }
1712
-
1713
2012
  query += ` WHERE `;
1714
2013
  if (options.start) {
1715
2014
  query += ` time > '${new Date(options.start).toISOString()}' AND `;
1716
2015
  }
1717
2016
  query += ` time < '${new Date(options.end).toISOString()}'`;
1718
2017
 
1719
- if (!options.start && (options.count || options.limit)) {
2018
+ if (resultsFromInfluxDB) {
2019
+ query += ` GROUP BY time(${options.step}ms) fill(previous)`;
2020
+ }
2021
+
2022
+ if ((!options.start && options.count) || (options.aggregate === 'none' && options.count && options.returnNewestEntries) ) {
1720
2023
  query += ` ORDER BY time DESC`;
2024
+ } else {
2025
+ query += ' ORDER BY time ASC';
1721
2026
  }
1722
2027
 
1723
- if (options.aggregate !== 'onchange' && options.aggregate !== 'none' && options.aggregate !== 'minmax') {
1724
- query += ` GROUP BY time(${options.step}ms) fill(previous) LIMIT ${options.limit}`;
1725
- } else if (options.aggregate !== 'minmax') {
2028
+ if (resultsFromInfluxDB) {
2029
+ query += ` LIMIT ${options.limit}`;
2030
+ } else if (options.aggregate !== 'minmax' && (options.aggregate !== 'integral')) {
1726
2031
  query += ` LIMIT ${options.count}`;
1727
2032
  }
1728
2033
 
1729
2034
  // select one datapoint more than wanted
1730
- if (options.aggregate === 'minmax' || options.aggregate === 'onchange' || options.aggregate === 'none') {
2035
+ if (!options.removeBorderValues) {
1731
2036
  let addQuery = '';
1732
2037
  if (options.start) {
1733
2038
  addQuery = `SELECT value from "${options.id}" WHERE time <= '${new Date(options.start).toISOString()}' ORDER BY time DESC LIMIT 1;`;
@@ -1737,56 +2042,70 @@ function getHistory(adapter, msg) {
1737
2042
  query = query + addQuery;
1738
2043
  }
1739
2044
 
1740
- adapter.log.debug(query);
2045
+ debugLog && adapter.log.debug(`${options.logId} History-Queries to execute: ${query}`);
1741
2046
 
1742
- // if specific id requested
1743
- adapter._client.query(query, (error, rows) => {
1744
- if (error) {
1745
- if (adapter._client.request.getHostsAvailable().length === 0) {
1746
- setConnected(adapter, false);
1747
- }
1748
- adapter.log.error('getHistory: ' + error);
1749
- } else {
1750
- setConnected(adapter, true);
2047
+ storeBufferedSeries(adapter, options.id, (err, storedCount) => {
2048
+ if (err) {
2049
+ adapter.log.info(`Error storing buffered series for ${options.id} before GetHistory: ${err}`);
1751
2050
  }
2051
+ setTimeout(() => {
2052
+ adapter._client.query(query, (error, rows) => {
2053
+ if (error) {
2054
+ if (adapter._client.request.getHostsAvailable().length === 0) {
2055
+ setConnected(adapter, false);
2056
+ }
2057
+ adapter.log.error(`getHistory: ${error}`);
2058
+ } else {
2059
+ setConnected(adapter, true);
2060
+ }
1752
2061
 
1753
- adapter.log.debug('ROWS:' + JSON.stringify(rows));
2062
+ debugLog && adapter.log.debug(`${options.logId} Response rows: ${JSON.stringify(rows)}`);
1754
2063
 
1755
- let result = [];
2064
+ let result = [];
1756
2065
 
1757
- if (rows && rows.length) {
1758
- for (let qr = 0; qr < rows.length; qr++) {
1759
- for (let rr = 0; rr < rows[qr].length; rr++) {
1760
- if ((rows[qr][rr].val === undefined) && (rows[qr][rr].value !== undefined)) {
1761
- rows[qr][rr].val = rows[qr][rr].value;
1762
- delete rows[qr][rr].value;
1763
- }
1764
- rows[qr][rr].ts = new Date(rows[qr][rr].time).getTime();
1765
- delete rows[qr][rr].time;
1766
- if (rows[qr][rr].val !== null) {
1767
- const f = parseFloat(rows[qr][rr].val);
1768
- if (f == rows[qr][rr].val) {
1769
- rows[qr][rr].val = f;
1770
- if (adapter.config.round) {
1771
- rows[qr][rr].val = Math.round(rows[qr][rr].val * adapter.config.round) / adapter.config.round;
2066
+ if (rows && rows.length) {
2067
+ for (let qr = 0; qr < rows.length; qr++) {
2068
+ for (let rr = 0; rr < rows[qr].length; rr++) {
2069
+ if ((rows[qr][rr].val === undefined) && (rows[qr][rr].value !== undefined)) {
2070
+ rows[qr][rr].val = rows[qr][rr].value;
2071
+ delete rows[qr][rr].value;
1772
2072
  }
2073
+ rows[qr][rr].ts = new Date(rows[qr][rr].time).getTime();
2074
+ delete rows[qr][rr].time;
2075
+
2076
+ if (rows[qr][rr].val !== null) {
2077
+ if (isFinite(rows[qr][rr].val)) {
2078
+ rows[qr][rr].val = parseFloat(rows[qr][rr].val);
2079
+ if (options.round) {
2080
+ rows[qr][rr].val = Math.round(rows[qr][rr].val * options.round) / options.round;
2081
+ }
2082
+ }
2083
+ }
2084
+
2085
+ if (options.addId) {
2086
+ rows[qr][rr].id = options.id;
2087
+ }
2088
+ result.push(rows[qr][rr]);
1773
2089
  }
1774
2090
  }
1775
- if (options.addId) {
1776
- rows[qr][rr].id = msg.message.id;
1777
- }
1778
- result.push(rows[qr][rr]);
2091
+ result = result.sort(sortByTs);
1779
2092
  }
1780
- }
1781
- }
1782
2093
 
1783
- Aggregate.sendResponse(adapter, msg, options, (error ? error.toString() : null) || result, startTime);
2094
+ Aggregate.sendResponse(adapter, msg, options, (error ? error.toString() : null) || result, startTime);
2095
+ });
2096
+ }, storedCount ? 50 : 0);
1784
2097
  });
1785
2098
  }
1786
2099
 
1787
2100
  function getHistoryIflx2(adapter, msg) {
1788
2101
  const startTime = Date.now();
1789
2102
 
2103
+ if (!msg.message || !msg.message.options) {
2104
+ return adapter.sendTo(msg.from, msg.command, {
2105
+ error: 'Invalid call. No options for getHistory provided'
2106
+ }, msg.callback);
2107
+ }
2108
+
1790
2109
  const options = {
1791
2110
  id: msg.message.id === '*' ? null : msg.message.id,
1792
2111
  start: msg.message.options.start,
@@ -1794,25 +2113,62 @@ function getHistoryIflx2(adapter, msg) {
1794
2113
  step: parseInt(msg.message.options.step, 10) || null,
1795
2114
  count: parseInt(msg.message.options.count, 10) || 500,
1796
2115
  aggregate: msg.message.options.aggregate || 'average', // One of: max, min, average, total
1797
- limit: parseInt(msg.message.options.limit || adapter.config.limit || 2000),
2116
+ limit: parseInt(msg.message.options.limit, 10) || parseInt(msg.message.options.count, 10) || adapter.config.limit || 2000,
1798
2117
  addId: msg.message.options.addId || false,
1799
2118
  ignoreNull: true,
1800
- sessionId: msg.message.options.sessionId
2119
+ sessionId: msg.message.options.sessionId,
2120
+ returnNewestEntries: msg.message.options.returnNewestEntries || false,
2121
+ percentile: msg.message.options.aggregate === 'percentile' ? parseInt(msg.message.options.percentile, 10) || 50 : null,
2122
+ quantile: msg.message.options.aggregate === 'quantile' ? parseFloat(msg.message.options.quantile) || 0.5 : null,
2123
+ integralUnit: msg.message.options.aggregate === 'integral' ? parseInt(msg.message.options.integralUnit, 10) || 60 : null,
2124
+ integralInterpolation: msg.message.options.aggregate === 'integral' ? msg.message.options.integralInterpolation || 'none' : null,
2125
+ removeBorderValues: msg.message.options.removeBorderValues || false,
2126
+ logId: (msg.message.id ? msg.message.id : 'all') + Date.now() + Math.random()
1801
2127
  };
1802
2128
 
2129
+ if (!options.start && options.count) {
2130
+ options.returnNewestEntries = true;
2131
+ }
2132
+
2133
+ if (msg.message.options.round !== null && msg.message.options.round !== undefined && msg.message.options.round !== '') {
2134
+ msg.message.options.round = parseInt(msg.message.options.round, 10);
2135
+ if (!isFinite(msg.message.options.round) || msg.message.options.round < 0) {
2136
+ options.round = adapter.config.round;
2137
+ } else {
2138
+ options.round = Math.pow(10, parseInt(msg.message.options.round, 10));
2139
+ }
2140
+ } else {
2141
+ options.round = adapter.config.round;
2142
+ }
2143
+
2144
+ const debugLog = options.debugLog = !!(adapter._influxDPs[options.id] && adapter._influxDPs[options.id][adapter.namespace] && adapter._influxDPs[options.id][adapter.namespace].enableDebugLogs);
2145
+
2146
+ debugLog && adapter.log.debug(`${options.logId} getHistory (InfluxDB2) call: ${JSON.stringify(options)}`);
2147
+
1803
2148
  if (options.id && adapter._aliasMap[options.id]) {
1804
2149
  options.id = adapter._aliasMap[options.id];
1805
2150
  }
1806
- const fluxQueries = [];
1807
- let fluxQuery = `from(bucket: "${adapter.config.dbname}") `;
1808
2151
 
1809
- const valueColumn = adapter.config.usetags ? '_value' : 'value';
2152
+ if (options.aggregate === 'percentile' && options.percentile < 0 || options.percentile > 100) {
2153
+ adapter.log.error(`Invalid percentile value: ${options.percentile}, use 50 as default`);
2154
+ options.percentile = 50;
2155
+ }
1810
2156
 
1811
- if (!adapter._influxDPs[options.id]) {
2157
+ if (options.aggregate === 'quantile' && options.quantile < 0 || options.quantile > 1) {
2158
+ adapter.log.error(`Invalid quantile value: ${options.quantile}, use 0.5 as default`);
2159
+ options.quantile = 0.5;
2160
+ }
2161
+
2162
+ if (options.aggregate === 'integral' && (typeof options.integralUnit !== 'number' || options.integralUnit <= 0)) {
2163
+ adapter.log.error(`Invalid integralUnit value: ${options.integralUnit}, use 60s as default`);
2164
+ options.integralUnit = 60;
2165
+ }
2166
+
2167
+ if (!adapter._influxDPs[options.id] || !adapter._influxDPs[options.id][adapter.namespace]) {
1812
2168
  return adapter.sendTo(msg.from, msg.command, {
1813
2169
  result: [],
1814
2170
  step: 0,
1815
- error: 'No connection'
2171
+ error: `Logging not activated for ${options.id}`
1816
2172
  }, msg.callback);
1817
2173
  }
1818
2174
 
@@ -1821,182 +2177,245 @@ function getHistoryIflx2(adapter, msg) {
1821
2177
  options.end = options.start;
1822
2178
  options.start = _end;
1823
2179
  }
1824
- // if less 2000.01.01 00:00:00
1825
- if (options.end && options.end < 946681200000) options.end *= 1000;
1826
- if (options.start && options.start < 946681200000) options.start *= 1000;
1827
2180
 
1828
2181
  if (!options.start && !options.count) {
1829
2182
  options.start = options.end - 86400000; // - 1 day
1830
2183
  }
1831
2184
 
2185
+ const resultsFromInfluxDB = options.aggregate !== 'onchange' && options.aggregate !== 'none' && options.aggregate !== 'minmax';
2186
+
1832
2187
  // query one timegroup-value more than requested originally at start and end
1833
2188
  // to make sure to have no 0 values because of the way InfluxDB does group by time
1834
- if (options.aggregate !== 'onchange' && options.aggregate !== 'none' && options.aggregate !== 'minmax') {
2189
+ if (resultsFromInfluxDB) {
1835
2190
  if (!options.step) {
1836
2191
  // calculate "step" based on difference between start and end using count
1837
- options.step = parseInt((options.end - options.start) / options.count, 10);
2192
+ options.step = Math.round((options.end - options.start) / options.count);
2193
+ }
2194
+ if (options.start) {
2195
+ options.start -= options.step;
1838
2196
  }
1839
- if (options.start) options.start -= options.step;
1840
2197
  options.end += options.step;
1841
2198
  options.limit += 2;
1842
2199
  }
1843
2200
 
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}")`;
1846
-
1847
- if (adapter.config.usetags)
1848
- fluxQuery += ' |> duplicate(column: "_value", as: "value")';
1849
- else
1850
- fluxQuery += ' |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")';
1851
-
1852
- if (!options.start && (options.count || options.limit)) {
1853
- fluxQuery += ` |> sort(columns:["_time"], desc: true)`;
1854
- }
1855
-
1856
- if (options.aggregate !== 'onchange' && options.aggregate !== 'none' && options.aggregate !== 'minmax') {
1857
- if ((options.step !== null) && (options.step > 0))
1858
- fluxQuery += ` |> window(every: ${options.step}ms)`;
1859
- fluxQuery += `|> fill(column: "${valueColumn}", usePrevious: true)`;
1860
- } else if (options.aggregate !== 'minmax') {
1861
- fluxQuery += ` |> group() |> limit(n: ${options.count})`;
1862
- }
2201
+ const valueColumn = adapter.config.usetags ? '_value' : 'value';
1863
2202
 
1864
2203
  // 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
2204
+ // There seems to be no officially supported way to detect this, so we check it by forcing a type-conflict;
1866
2205
  const booleanTypeCheckQuery = `
1867
2206
  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()})
2207
+ |> range(${(options.start) ? `start: ${new Date(options.start).toISOString()}, ` : `start: ${new Date(options.end - (adapter.config.retention || 31536000) * 1000).toISOString()}, `}stop: ${new Date(options.end).toISOString()})
1869
2208
  |> filter(fn: (r) => r["_measurement"] == "${options.id}" and contains(value: r._value, set: [true, false]))
2209
+ ${adapter.config.usetags ? ' |> duplicate(column: "_value", as: "value")' : ' |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")'}
2210
+ |> group()
1870
2211
  `;
1871
2212
 
1872
- adapter._client.query(booleanTypeCheckQuery, (error, _rslt) => {
1873
- let isBoolean;
1874
- if (error) {
1875
- if (error.message.includes('type conflict: bool')) {
1876
- isBoolean = false;
1877
- error = null;
1878
- } else {
1879
- return adapter.sendTo(msg.from, msg.command, {
1880
- result: [],
1881
- error: error,
1882
- sessionId: options.sessionId
1883
- }, msg.callback);
1884
- }
1885
- } else {
1886
- isBoolean = true;
1887
- adapter.log.debug(`Measurement ${options.id} is of type Boolean - skipping aggregation options`);
1888
- }
1889
-
1890
- if (options.step && !isBoolean) {
2213
+ storeBufferedSeries(adapter, options.id, (err, storedCount) => {
2214
+ if (err) {
2215
+ adapter.log.info(`Error storing buffered series for ${options.id} before GetHistory: ${err}`);
2216
+ }
2217
+ setTimeout(() => {
2218
+ adapter._client.query(booleanTypeCheckQuery, (error, rslt) => {
2219
+ let supportsAggregates;
2220
+ if (adapter._influxDPs[options.id][adapter.namespace].storageType && adapter._influxDPs[options.id][adapter.namespace].storageType !== 'Number') {
2221
+ supportsAggregates = false;
2222
+ } else if (error) {
2223
+ if (error.message.includes('type conflict: bool')) {
2224
+ debugLog && adapter.log.debug(`${options.logId} Bool check error: ${error.message}`);
2225
+ supportsAggregates = true;
2226
+ error = null;
2227
+ } else {
2228
+ return adapter.sendTo(msg.from, msg.command, {
2229
+ result: [],
2230
+ error: error,
2231
+ sessionId: options.sessionId
2232
+ }, msg.callback);
2233
+ }
2234
+ } else {
2235
+ debugLog && adapter.log.debug(`${options.logId} Bool check result: ${JSON.stringify(rslt)}`);
2236
+ if (rslt.find(r => r.error && r.error.includes('type conflict: bool'))) {
2237
+ supportsAggregates = true;
2238
+ } else {
2239
+ supportsAggregates = false;
2240
+ }
2241
+ }
2242
+ if (supportsAggregates) {
2243
+ if (adapter._influxDPs[options.id][adapter.namespace].state && typeof adapter._influxDPs[options.id][adapter.namespace].state.val !== 'number') {
2244
+ supportsAggregates = false;
2245
+ } else if (adapter._influxDPs[options.id][adapter.namespace].skipped && typeof adapter._influxDPs[options.id][adapter.namespace].skipped.val !== 'number') {
2246
+ supportsAggregates = false;
2247
+ }
2248
+ }
2249
+ if (!supportsAggregates) {
2250
+ debugLog && adapter.log.debug(`${options.logId} Measurement ${options.id} seems to be no number - skipping aggregation options`);
2251
+ }
1891
2252
 
1892
- switch (options.aggregate) {
1893
- case 'average':
1894
- fluxQuery += ` |> mean(column: "${valueColumn}")`;
1895
- break;
2253
+ const fluxQueries = [];
2254
+ let fluxQuery = `from(bucket: "${adapter.config.dbname}") `;
1896
2255
 
1897
- case 'max':
1898
- fluxQuery += ` |> max(column: "${valueColumn}")`;
1899
- break;
2256
+ fluxQuery += ` |> range(${(options.start) ? `start: ${new Date(options.start).toISOString()}, ` : `start: ${new Date(options.end - (adapter.config.retention || 31536000) * 1000).toISOString()}, `}stop: ${new Date(options.end).toISOString()})`;
2257
+ fluxQuery += ` |> filter(fn: (r) => r["_measurement"] == "${options.id}")`;
1900
2258
 
1901
- case 'min':
1902
- fluxQuery += ` |> min(column: "${valueColumn}")`;
1903
- break;
2259
+ if (adapter.config.usetags)
2260
+ fluxQuery += ' |> duplicate(column: "_value", as: "value")';
2261
+ else
2262
+ fluxQuery += ' |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")';
1904
2263
 
1905
- case 'total':
1906
- fluxQuery += ` |> sum(column: "${valueColumn}")`;
1907
- break;
2264
+ if (resultsFromInfluxDB && supportsAggregates) {
2265
+ if ((options.step !== null) && (options.step > 0))
2266
+ fluxQuery += ` |> window(every: ${options.step}ms)`;
2267
+ fluxQuery += `|> fill(column: "${valueColumn}", usePrevious: true)`;
2268
+ } else if (options.aggregate !== 'minmax') {
2269
+ fluxQuery += ` |> group()`;
2270
+ }
1908
2271
 
1909
- case 'count':
1910
- fluxQuery += ` |> count(column: "${valueColumn}")`;
1911
- break;
2272
+ if ((!options.start && options.count) || (options.aggregate === 'none' && options.count && options.returnNewestEntries) ) {
2273
+ fluxQuery += ` |> sort(columns:["_time"], desc: true)`;
2274
+ } else {
2275
+ fluxQuery += ` |> sort(columns:["_time"], desc: false)`;
2276
+ }
1912
2277
 
1913
- default:
1914
- fluxQuery += ` |> mean(column: "${valueColumn}")`;
1915
- break;
1916
- }
1917
- }
2278
+ if (!(resultsFromInfluxDB && supportsAggregates) && options.aggregate !== 'minmax') {
2279
+ fluxQuery += ` |> limit(n: ${options.count})`;
2280
+ }
1918
2281
 
1919
- fluxQueries.push(fluxQuery);
1920
-
1921
- // select one datapoint more than wanted
1922
- if (options.aggregate === 'minmax' || options.aggregate === 'onchange' || options.aggregate === 'none') {
1923
- let addFluxQuery = '';
1924
- if (options.start) {
1925
- // get one entry "before" the defined timeframe for displaying purposes
1926
- addFluxQuery = `from(bucket: "${adapter.config.dbname}")
1927
- |> range(start: ${new Date(options.start - (adapter.config.retention || 31536000) * 1000).toISOString()}, stop: ${new Date(options.start).toISOString()})
1928
- |> filter(fn: (r) => r["_measurement"] == "${options.id}")
1929
- ${(!adapter.config.usetags) ? '|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")' : ''}
1930
- |> sort(columns: ["_time"], desc: true)
1931
- |> group()
1932
- |> limit(n: 1)`;
1933
-
1934
- const mainQuery = fluxQueries.pop();
1935
- fluxQueries.push(addFluxQuery);
1936
- fluxQueries.push(mainQuery);
1937
- }
1938
- // get one entry "after" the defined timeframe for displaying purposes
1939
- addFluxQuery = `from(bucket: "${adapter.config.dbname}")
1940
- |> range(start: ${new Date(options.end).toISOString()})
1941
- |> filter(fn: (r) => r["_measurement"] == "${options.id}")
1942
- ${(!adapter.config.usetags) ? '|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")' : ''}
1943
- |> sort(columns: ["_time"], desc: false)
1944
- |> group()
1945
- |> limit(n: 1)`;
1946
- //fluxQuery = fluxQuery + addFluxQuery;
1947
- fluxQueries.push(addFluxQuery);
1948
- }
1949
-
1950
- adapter.log.debug('History-queries to execute: ' + fluxQueries);
1951
-
1952
- // if specific id requested
1953
- adapter._client.queries(fluxQueries, (err, rows) => {
1954
- if (err && !rows) {
1955
- if (adapter._client.request.getHostsAvailable().length === 0) {
1956
- setConnected(adapter, false);
2282
+ if (resultsFromInfluxDB && options.step && supportsAggregates) {
2283
+ options.preAggregated = true;
2284
+ switch (options.aggregate) {
2285
+ case 'average':
2286
+ fluxQuery += ` |> mean(column: "${valueColumn}")`;
2287
+ break;
2288
+
2289
+ case 'max':
2290
+ fluxQuery += ` |> max(column: "${valueColumn}")`;
2291
+ break;
2292
+
2293
+ case 'min':
2294
+ fluxQuery += ` |> min(column: "${valueColumn}")`;
2295
+ break;
2296
+
2297
+ case 'percentile':
2298
+ fluxQuery += ` |> quantile(column: "${valueColumn}", q: ${options.percentile / 100})`;
2299
+ break;
2300
+
2301
+ case 'quantile':
2302
+ fluxQuery += ` |> quantile(column: "${valueColumn}", q: ${options.quantile})`;
2303
+ break;
2304
+
2305
+ case 'integral':
2306
+ fluxQuery += ` |> integral(column: "${valueColumn}", unit: ${options.integralUnit}s, interpolate: ${options.integralInterpolation === 'linear' ? '"linear"' : '""'})`;
2307
+ break;
2308
+
2309
+ case 'total':
2310
+ fluxQuery += ` |> sum(column: "${valueColumn}")`;
2311
+ break;
2312
+
2313
+ case 'count':
2314
+ fluxQuery += ` |> count(column: "${valueColumn}")`;
2315
+ break;
2316
+
2317
+ default:
2318
+ fluxQuery += ` |> mean(column: "${valueColumn}")`;
2319
+ options.preAggregated = false;
2320
+ break;
2321
+ }
1957
2322
  }
1958
- adapter.log.error('getHistory: ' + err);
1959
- } else {
1960
- setConnected(adapter, true);
1961
- }
1962
2323
 
1963
- adapter.log.debug('Parsing retrieved rows:' + JSON.stringify(rows));
2324
+ fluxQueries.push(fluxQuery);
2325
+
2326
+ // select one datapoint more than wanted
2327
+ if (!options.removeBorderValues) {
2328
+ let addFluxQuery = '';
2329
+ if (options.start) {
2330
+ // get one entry "before" the defined timeframe for displaying purposes
2331
+ addFluxQuery = `from(bucket: "${adapter.config.dbname}")
2332
+ |> range(start: ${new Date(options.start - (adapter.config.retention || 31536000) * 1000).toISOString()}, stop: ${new Date(options.start - 1).toISOString()})
2333
+ |> filter(fn: (r) => r["_measurement"] == "${options.id}")
2334
+ ${(!adapter.config.usetags) ? '|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")' : ''}
2335
+ |> group()
2336
+ |> sort(columns: ["_time"], desc: true)
2337
+ |> limit(n: 1)`;
2338
+
2339
+ fluxQueries.unshift(addFluxQuery);
2340
+ }
2341
+ // get one entry "after" the defined timeframe for displaying purposes
2342
+ addFluxQuery = `from(bucket: "${adapter.config.dbname}")
2343
+ |> range(start: ${new Date(options.end + 1).toISOString()})
2344
+ |> filter(fn: (r) => r["_measurement"] == "${options.id}")
2345
+ ${(!adapter.config.usetags) ? '|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")' : ''}
2346
+ |> group()
2347
+ |> sort(columns: ["_time"], desc: false)
2348
+ |> limit(n: 1)`;
2349
+ fluxQueries.push(addFluxQuery);
2350
+ }
1964
2351
 
1965
- let result = [];
2352
+ debugLog && adapter.log.debug(`${options.logId} History-queries to execute: ${fluxQueries}`);
1966
2353
 
1967
- if (rows && rows.length) {
1968
- for (let qr = 0; qr < rows.length; qr++) {
1969
- for (let rr = 0; rr < rows[qr].length; rr++) {
1970
- if ((rows[qr][rr].val === undefined) && (rows[qr][rr].value !== undefined)) {
1971
- rows[qr][rr].val = rows[qr][rr].value;
1972
- delete rows[qr][rr].value;
2354
+ // if specific id requested
2355
+ adapter._client.queries(fluxQueries, (err, rows) => {
2356
+ if (err && !rows) {
2357
+ if (adapter._client.request.getHostsAvailable().length === 0) {
2358
+ setConnected(adapter, false);
1973
2359
  }
2360
+ adapter.log.error(`getHistory: ${err}`);
2361
+ } else {
2362
+ setConnected(adapter, true);
2363
+ }
1974
2364
 
1975
- rows[qr][rr].ts = new Date(rows[qr][rr].time).getTime();
2365
+ debugLog && adapter.log.debug(`${options.logId} Parsing retrieved rows:${JSON.stringify(rows)}`);
1976
2366
 
1977
- delete rows[qr][rr].time;
2367
+ let result = [];
1978
2368
 
1979
- if (rows[qr][rr].val !== null) {
1980
- const f = parseFloat(rows[qr][rr].val);
1981
- if (f == rows[qr][rr].val) {
1982
- rows[qr][rr].val = f;
1983
- if (adapter.config.round) {
1984
- rows[qr][rr].val = Math.round(rows[qr][rr].val * adapter.config.round) / adapter.config.round;
2369
+ if (rows && rows.length) {
2370
+ for (let qr = 0; qr < rows.length; qr++) {
2371
+ for (let rr = 0; rr < rows[qr].length; rr++) {
2372
+ if ((rows[qr][rr].val === undefined) && (rows[qr][rr].value !== undefined)) {
2373
+ rows[qr][rr].val = rows[qr][rr].value;
2374
+ delete rows[qr][rr].value;
1985
2375
  }
1986
- }
1987
- }
1988
2376
 
1989
- if (options.addId) {
1990
- rows[qr][rr].id = msg.message.id;
2377
+ if (rows[qr][rr].val !== null) {
2378
+ if (isFinite(rows[qr][rr].val)) {
2379
+ rows[qr][rr].val = parseFloat(rows[qr][rr].val);
2380
+ if (options.round) {
2381
+ rows[qr][rr].val = Math.round(rows[qr][rr].val * options.round) / options.round;
2382
+ }
2383
+ }
2384
+ }
2385
+
2386
+ if (rows[qr][rr].time) {
2387
+ rows[qr][rr].ts = new Date(rows[qr][rr].time).getTime();
2388
+ delete rows[qr][rr].time;
2389
+ } else if (rows[qr][rr]._start && rows[qr][rr]._stop) {
2390
+ const startTime = new Date(rows[qr][rr]._start).getTime();
2391
+ const stopTime = new Date(rows[qr][rr]._stop).getTime();
2392
+ rows[qr][rr].ts = startTime + (stopTime - startTime) / 2;
2393
+ delete rows[qr][rr]._start;
2394
+ delete rows[qr][rr]._stop;
2395
+ }
2396
+
2397
+ delete rows[qr][rr].result;
2398
+ delete rows[qr][rr].table;
2399
+
2400
+ if (options.addId) {
2401
+ rows[qr][rr].id = rows[qr][rr]._measurement || options.id;
2402
+ }
2403
+ delete rows[qr][rr]._measurement;
2404
+
2405
+ result.push(rows[qr][rr]);
2406
+ }
1991
2407
  }
2408
+ result = result.sort(sortByTs);
2409
+ }
1992
2410
 
1993
- result.push(rows[qr][rr]);
2411
+ if (options.debugLog) {
2412
+ options.log = adapter.log.debug;
1994
2413
  }
1995
- }
1996
- }
1997
2414
 
1998
- Aggregate.sendResponse(adapter, msg, options, (error ? error.toString() : null) || result, startTime);
1999
- });
2415
+ Aggregate.sendResponse(adapter, msg, options, (error ? error.toString() : null) || result, startTime);
2416
+ });
2417
+ });
2418
+ }, storedCount ? 50 : 0);
2000
2419
  });
2001
2420
  }
2002
2421
 
@@ -2005,7 +2424,7 @@ function query(adapter, msg) {
2005
2424
  const query = msg.message.query || msg.message;
2006
2425
 
2007
2426
  if (!query || typeof query !== 'string') {
2008
- adapter.log.error('query missing: ' + query);
2427
+ adapter.log.error(`query missing: ${query}`);
2009
2428
  adapter.sendTo(msg.from, msg.command, {
2010
2429
  result: [],
2011
2430
  error: 'Query missing'
@@ -2013,14 +2432,14 @@ function query(adapter, msg) {
2013
2432
  return;
2014
2433
  }
2015
2434
 
2016
- adapter.log.debug('query: ' + query);
2435
+ adapter.log.debug(`query: ${query}`);
2017
2436
 
2018
2437
  adapter._client.query(query, (err, rows) => {
2019
2438
  if (err) {
2020
2439
  if (adapter._client.request.getHostsAvailable().length === 0) {
2021
2440
  setConnected(adapter, false);
2022
2441
  }
2023
- adapter.log.error('query: ' + err);
2442
+ adapter.log.error(`query: ${err}`);
2024
2443
  return adapter.sendTo(msg.from, msg.command, {
2025
2444
  result: [],
2026
2445
  error: 'Invalid call'
@@ -2029,13 +2448,17 @@ function query(adapter, msg) {
2029
2448
  setConnected(adapter, true);
2030
2449
  }
2031
2450
 
2032
- adapter.log.debug('result: ' + JSON.stringify(rows));
2451
+ adapter.log.debug(`result: ${JSON.stringify(rows)}`);
2033
2452
 
2034
2453
  for (let r = 0, l = rows.length; r < l; r++) {
2035
2454
  for (let rr = 0, ll = rows[r].length; rr < ll; rr++) {
2036
2455
  if (rows[r][rr].time) {
2037
2456
  rows[r][rr].ts = new Date(rows[r][rr].time).getTime();
2038
2457
  delete rows[r][rr].time;
2458
+ } else if (rows[r][rr]._start && rows[r][rr]._stop) {
2459
+ const startTime = new Date(rows[r][rr]._start).getTime();
2460
+ const stopTime = new Date(rows[r][rr]._stop).getTime();
2461
+ rows[r][rr].ts = startTime + (stopTime - startTime) / 2;
2039
2462
  }
2040
2463
  }
2041
2464
  }
@@ -2075,21 +2498,21 @@ function multiQuery(adapter, msg) {
2075
2498
  c++;
2076
2499
  }
2077
2500
  } catch (error) {
2078
- adapter.log.warn('Error in received multiQuery: ' + error);
2501
+ adapter.log.warn(`Error in received multiQuery: ${error}`);
2079
2502
  adapter.sendTo(msg.from, msg.command, {
2080
2503
  result: [],
2081
2504
  error: error
2082
2505
  }, msg.callback);
2083
2506
  return;
2084
2507
  }
2085
- adapter.log.debug('queries: ' + queries);
2508
+ adapter.log.debug(`queries: ${queries}`);
2086
2509
 
2087
2510
  adapter._client.queries(queries, (err, rows) => {
2088
2511
  if (err) {
2089
2512
  if (adapter._client.request.getHostsAvailable().length === 0) {
2090
2513
  setConnected(adapter, false);
2091
2514
  }
2092
- adapter.log.error('queries: ' + err);
2515
+ adapter.log.error(`queries: ${err}`);
2093
2516
  return adapter.sendTo(msg.from, msg.command, {
2094
2517
  result: [],
2095
2518
  error: 'Invalid call'
@@ -2098,7 +2521,7 @@ function multiQuery(adapter, msg) {
2098
2521
  setConnected(adapter, true);
2099
2522
  }
2100
2523
 
2101
- adapter.log.debug('result: ' + JSON.stringify(rows));
2524
+ adapter.log.debug(`result: ${JSON.stringify(rows)}`);
2102
2525
 
2103
2526
  for (let r = 0, l = rows.length; r < l; r++) {
2104
2527
  for (let rr = 0, ll = rows[r].length; rr < ll; rr++) {
@@ -2140,7 +2563,7 @@ function enableHistory(adapter, msg) {
2140
2563
  obj.common.custom[adapter.namespace].enabled = true;
2141
2564
  adapter.extendForeignObject(msg.message.id, obj, error => {
2142
2565
  if (error) {
2143
- adapter.log.error('enableHistory: ' + error);
2566
+ adapter.log.error(`enableHistory: ${error}`);
2144
2567
  adapter.sendTo(msg.from, msg.command, {error}, msg.callback);
2145
2568
  } else {
2146
2569
  adapter.log.info(JSON.stringify(obj));
@@ -2162,7 +2585,7 @@ function disableHistory(adapter, msg) {
2162
2585
  obj.common.custom[adapter.namespace].enabled = false;
2163
2586
  adapter.extendForeignObject(msg.message.id, obj, error => {
2164
2587
  if (error) {
2165
- adapter.log.error('disableHistory: ' + error);
2588
+ adapter.log.error(`disableHistory: ${error}`);
2166
2589
  adapter.sendTo(msg.from, msg.command, {error}, msg.callback);
2167
2590
  } else {
2168
2591
  adapter.log.info(JSON.stringify(obj));
@@ -2174,10 +2597,9 @@ function disableHistory(adapter, msg) {
2174
2597
  function getEnabledDPs(adapter, msg) {
2175
2598
  const data = {};
2176
2599
  for (const id in adapter._influxDPs) {
2177
- if (!adapter._influxDPs.hasOwnProperty(id)) {
2178
- continue;
2600
+ if (adapter._influxDPs.hasOwnProperty(id) && adapter._influxDPs[id] && adapter._influxDPs[id][adapter.namespace] && adapter._influxDPs[id][adapter.namespace].enabled) {
2601
+ data[adapter._influxDPs[id].realId] = adapter._influxDPs[id][adapter.namespace];
2179
2602
  }
2180
- data[adapter._influxDPs[id].realId] = adapter._influxDPs[id][adapter.namespace];
2181
2603
  }
2182
2604
 
2183
2605
  adapter.sendTo(msg.from, msg.command, data, msg.callback);