iobroker.influxdb 2.3.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,7 +12,7 @@ class FakeConnectionPool {
12
12
  }
13
13
 
14
14
  activatePool () {
15
- this.connections.push("fakehost");
15
+ this.connections.push('fakehost');
16
16
  }
17
17
 
18
18
  getHostsAvailable () {
@@ -22,7 +22,7 @@ class FakeConnectionPool {
22
22
 
23
23
  //Influx 2.x auth requires token, not user/pw
24
24
  class DatabaseInfluxDB2x extends Database {
25
- constructor(log, host, port, protocol, token, organization, database, useTags, timePrecision, requestTimeout) {
25
+ constructor(log, host, port, protocol, token, organization, database, requestTimeout, validateSSL, useTags, timePrecision) {
26
26
  super();
27
27
 
28
28
  this.log = log;
@@ -36,18 +36,23 @@ class DatabaseInfluxDB2x extends Database {
36
36
  this.timePrecision = timePrecision; // ms
37
37
  this.requestTimeout = requestTimeout; // 30000
38
38
  this.useTags = useTags || false;
39
+ this.validateSSL = validateSSL;
39
40
 
40
41
  this.request = new FakeConnectionPool();
41
42
 
42
43
  this.connect();
43
44
  }
44
45
 
45
- connect () {
46
- const url = this.protocol + '://' + this.host + ':' + this.port + '/';
46
+ connect() {
47
+ const url = `${this.protocol}://${this.host}:${this.port}/`;
48
+
49
+ this.log.debug(`Connect InfluxDB1: ${url} [${this.database}]`);
47
50
 
48
51
  this.connection = new InfluxClient.InfluxDB({
49
- url: url,
52
+ url,
50
53
  token: this.token,
54
+ timeout: this.requestTimeout,
55
+ transportOptions: {rejectUnauthorized: this.validateSSL},
51
56
  });
52
57
 
53
58
  this.queryApi = this.connection.getQueryApi(this.organization);
@@ -63,19 +68,19 @@ class DatabaseInfluxDB2x extends Database {
63
68
  this.request.activatePool();
64
69
  }
65
70
 
66
- async getDatabaseNames (callback) {
67
- this.log.debug("Organization being checked: " + this.organization);
71
+ async getDatabaseNames(callback) {
72
+ this.log.debug(`Organization being checked: ${this.organization}`);
68
73
 
69
74
  try {
70
75
  const organizations = await this.orgsApi.getOrgs({ org: this.organization });
71
- this.log.debug("Organizations: " + JSON.stringify(organizations));
76
+ this.log.debug(`Organizations: ${JSON.stringify(organizations)}`);
72
77
  if (organizations && organizations.orgs && !organizations.orgs.length) {
73
78
  throw new Error('No organizations exists or the token do not have proper permissions. Please check the token!')
74
79
  }
75
80
  this.organizationId = organizations.orgs[0].id;
76
81
 
77
82
  const buckets = await this.bucketsApi.getBuckets({ orgID: this.organizationId });
78
- this.log.debug("Buckets: " + JSON.stringify(buckets));
83
+ this.log.debug(`Buckets: ${JSON.stringify(buckets)}`);
79
84
 
80
85
  const foundDatabases = [];
81
86
 
@@ -90,21 +95,21 @@ class DatabaseInfluxDB2x extends Database {
90
95
  }
91
96
  }
92
97
 
93
- async getRetentionPolicyForDB (dbname, callback) {
94
- this.log.debug("Getting retention policy for " + dbname);
98
+ async getRetentionPolicyForDB(dbname, callback) {
99
+ this.log.debug(`Getting retention policy for ${dbname}`);
95
100
  try {
96
101
  const bucketData = await this.bucketsApi.getBucketsID({ bucketID: this.bucketIds[dbname] });
97
- this.log.debug("Found retention policy: " + bucketData.retentionRules[0].everySeconds + " seconds ");
98
- callback({ "time": bucketData.retentionRules[0].everySeconds });
102
+ this.log.debug(`Found retention policy: ${bucketData.retentionRules[0].everySeconds} seconds`);
103
+ callback({time: bucketData.retentionRules[0].everySeconds });
99
104
  } catch (error) {
100
105
  this.log.error(error);
101
106
  callback(null);
102
107
  }
103
108
  }
104
109
 
105
- async applyRetentionPolicyToDB (dbname, retention, callback_error) {
110
+ async applyRetentionPolicyToDB(dbname, retention, callback_error) {
106
111
  const shardGroupDuration = this.calculateShardGroupDuration(retention);
107
- this.log.info("Applying retention policy for " + dbname + " to " + ((retention === 0) ? "infinity" : retention + " seconds") + ". Shard Group Duration (calculated): " + shardGroupDuration + " seconds");
112
+ this.log.info(`Applying retention policy for ${dbname} to ${!retention ? "infinity" : retention + " seconds"}. Shard Group Duration (calculated): ${shardGroupDuration} seconds`);
108
113
  try {
109
114
  await this.bucketsApi.patchBucketsID({
110
115
  bucketID: this.bucketIds[dbname],
@@ -123,9 +128,9 @@ class DatabaseInfluxDB2x extends Database {
123
128
  }
124
129
  }
125
130
 
126
- async createDatabase (dbname, callback_error) {
131
+ async createDatabase(dbname, callback_error) {
127
132
  try {
128
- this.log.info("Creating database " + dbname + " for orgId " + this.organizationId);
133
+ this.log.info(`Creating database ${dbname} for orgId ${this.organizationId}`);
129
134
  const newBucket = await this.bucketsApi.postBuckets({
130
135
  body: {
131
136
  orgID: this.organizationId,
@@ -141,9 +146,9 @@ class DatabaseInfluxDB2x extends Database {
141
146
  }
142
147
  }
143
148
 
144
- async dropDatabase (dbname, callback_error) {
149
+ async dropDatabase(dbname, callback_error) {
145
150
  try {
146
- this.log.info("Dropping database " + dbname + " for orgId " + this.organizationId);
151
+ this.log.info(`Dropping database ${dbname} for orgId ${this.organizationId}`);
147
152
  await this.bucketsApi.deleteBucketsID({ bucketID: this.bucketIds[dbname] });
148
153
 
149
154
  callback_error(false);
@@ -153,8 +158,8 @@ class DatabaseInfluxDB2x extends Database {
153
158
  }
154
159
  }
155
160
 
156
- async writeSeries (series, callback_error) {
157
- this.log.debug("Write series: " + JSON.stringify(series));
161
+ async writeSeries(series, callback_error) {
162
+ this.log.debug(`Write series: ${JSON.stringify(series)}`);
158
163
 
159
164
  const points = [];
160
165
  for (const [pointId, valueSets] of Object.entries(series)) {
@@ -168,15 +173,15 @@ class DatabaseInfluxDB2x extends Database {
168
173
  try {
169
174
  this.writeApi.writePoints(points);
170
175
  await this.writeApi.flush();
171
- this.log.debug("Points written to " + this.database);
176
+ this.log.debug(`Points written to ${this.database}`);
172
177
  callback_error();
173
178
  } catch (error) {
174
179
  callback_error(error);
175
180
  }
176
181
  }
177
182
 
178
- async writePoints (pointId, pointsToSend, callback_error) {
179
- this.log.debug("Write Points: " + pointId + " pointstoSend:" + JSON.stringify(pointsToSend));
183
+ async writePoints(pointId, pointsToSend, callback_error) {
184
+ this.log.debug(`Write Points: ${pointId} pointstoSend:${JSON.stringify(pointsToSend)}`);
180
185
 
181
186
  const points = [];
182
187
  pointsToSend.forEach((values) => {
@@ -188,62 +193,62 @@ class DatabaseInfluxDB2x extends Database {
188
193
  try {
189
194
  this.writeApi.writePoints(points);
190
195
  await this.writeApi.flush();
191
- this.log.debug("Points written to " + this.database);
196
+ this.log.debug(`Points written to ${this.database}`);
192
197
  callback_error();
193
198
  } catch (error) {
194
199
  callback_error(error);
195
200
  }
196
201
  }
197
202
 
198
- async writePoint (pointId, values, options, callback_error) {
199
- this.log.debug("Write Point: " + pointId + " values:" + JSON.stringify(values) + " options: " + JSON.stringify(options));
203
+ async writePoint(pointId, values, options, callback_error) {
204
+ this.log.debug(`Write Point: ${pointId} values:${JSON.stringify(values)} options: ${JSON.stringify(options)}`);
200
205
 
201
206
  try {
202
207
  this.writeApi.writePoint(this.stateValueToPoint(pointId, values));
203
208
  await this.writeApi.flush();
204
- this.log.debug("Point written to " + this.database);
209
+ this.log.debug(`Point written to ${this.database}`);
205
210
  callback_error();
206
211
  } catch (error) {
207
- this.log.warn("Point could not be written to database: " + this.database);
212
+ this.log.warn(`Point could not be written to database: ${this.database}`);
208
213
  callback_error(error);
209
214
  }
210
215
 
211
216
  }
212
217
 
213
- stateValueToPoint (pointName, stateValue) {
218
+ stateValueToPoint(pointName, stateValue) {
214
219
  let point = null;
215
220
 
216
221
  if (this.useTags) {
217
222
  point = new InfluxClient.Point(pointName)
218
223
  .timestamp(stateValue.time)
219
- .tag("q", String(stateValue.q))
220
- .tag("ack", String(stateValue.ack))
221
- .tag("from", stateValue.from);
224
+ .tag('q', String(stateValue.q))
225
+ .tag('ack', String(stateValue.ack))
226
+ .tag('from', stateValue.from);
222
227
  } else {
223
228
  point = new InfluxClient.Point(pointName)
224
229
  .timestamp(stateValue.time)
225
- .floatField("q", stateValue.q)
226
- .booleanField("ack", stateValue.ack)
227
- .stringField("from", stateValue.from);
230
+ .floatField('q', stateValue.q)
231
+ .booleanField('ack', stateValue.ack)
232
+ .stringField('from', stateValue.from);
228
233
  }
229
234
 
230
235
  switch (typeof stateValue.value) {
231
- case "boolean":
232
- point.booleanField("value", stateValue.value);
236
+ case 'boolean':
237
+ point.booleanField('value', stateValue.value);
233
238
  break;
234
- case "number":
235
- point.floatField("value", parseFloat(stateValue.value));
239
+ case 'number':
240
+ point.floatField('value', parseFloat(stateValue.value));
236
241
  break;
237
- case "string":
242
+ case 'string':
238
243
  default:
239
- point.stringField("value", stateValue.value);
244
+ point.stringField('value', stateValue.value);
240
245
  break;
241
246
  }
242
247
  return point;
243
248
  }
244
249
 
245
- query (query, callback) {
246
- this.log.debug("Query to execute: " + query);
250
+ query(query, callback) {
251
+ this.log.debug(`Query to execute: ${query}`);
247
252
  let rows = [];
248
253
 
249
254
  this.queryApi.queryRows(query, {
@@ -251,9 +256,9 @@ class DatabaseInfluxDB2x extends Database {
251
256
  const fields = tableMeta.toObject(row);
252
257
 
253
258
  //Columns "_time" and "_value" are mapped to "time" and "value" for backwards compatibility
254
- if (fields["_time"] !== null)
255
- fields["time"] = fields["_time"];
256
-
259
+ if (fields['_time'] !== null)
260
+ fields['time'] = fields['_time'];
261
+
257
262
  //if (fields["_value"] !== null)
258
263
  // fields["value"] = fields["_value"];
259
264
 
@@ -262,9 +267,9 @@ class DatabaseInfluxDB2x extends Database {
262
267
  // console.log(JSON.stringify(o, null, 2))
263
268
  },
264
269
  error (error) {
265
- //Ignore errors that are related to an empty range. The handling of this currently seems inconsitent for flux.
270
+ //Ignore errors that are related to an empty range. The handling of this currently seems inconsistent for flux.
266
271
  //See also https://github.com/influxdata/flux/issues/3543
267
- if (error.message.match(".*cannot query an empty range.*"))
272
+ if (error.message.match('.*cannot query an empty range.*'))
268
273
  callback(null, rows);
269
274
  else
270
275
  callback(error, null);
@@ -278,8 +283,8 @@ class DatabaseInfluxDB2x extends Database {
278
283
 
279
284
  getMetaDataStorageType (callback) {
280
285
  const queries = [
281
- 'import "influxdata/influxdb/schema" schema.tagKeys(bucket: "' + this.database + '")',
282
- 'import "influxdata/influxdb/schema" schema.fieldKeys(bucket: "' + this.database + '")',
286
+ `import "influxdata/influxdb/schema" schema.tagKeys(bucket: "${this.database}")`,
287
+ `import "influxdata/influxdb/schema" schema.fieldKeys(bucket: "${this.database}")`,
283
288
  ];
284
289
 
285
290
  this.queries(queries, (error, result) => {
@@ -287,21 +292,21 @@ class DatabaseInfluxDB2x extends Database {
287
292
  if (error) {
288
293
  callback(error, null);
289
294
  } else {
290
- this.log.debug("Result of metadata storage type check: " + JSON.stringify(result));
291
- for (let i=0; i <= 1; i++) {
292
- result[i].forEach((row) => {
295
+ this.log.debug(`Result of metadata storage type check: ${JSON.stringify(result)}`);
296
+ for (let i = 0; i <= 1; i++) {
297
+ result[i].forEach(row => {
293
298
  switch(row._value) {
294
- case "q":
295
- case "ack":
296
- case "from":
297
- storageType = (i == 0)? "tags" : "fields";
299
+ case 'q':
300
+ case 'ack':
301
+ case 'from':
302
+ storageType = i == 0 ? 'tags' : 'fields';
298
303
  return;
299
304
  }
300
305
  });
301
306
  }
302
307
  callback(null, storageType);
303
308
  }
304
-
309
+
305
310
  });
306
311
  }
307
312
 
@@ -324,6 +329,7 @@ class DatabaseInfluxDB2x extends Database {
324
329
  });
325
330
  });
326
331
  }
332
+
327
333
  let retError = null;
328
334
  if (errors.length) {
329
335
  retError = new Error(`${errors.length} Error happened while processing ${queries.length} queries`);
@@ -332,18 +338,10 @@ class DatabaseInfluxDB2x extends Database {
332
338
  callback(retError, success ? collectedRows : null);
333
339
  }
334
340
 
335
- ping (interval) {
336
- //can't do much with interval, so ignoring it for compatibility reasons
337
- const promises = [];
338
- promises.push(new Promise((resolve, reject) => {
339
- this.healthApi.getHealth().then(result => {
340
- resolve(result.status === 'pass' ? { online: true } : { online: false });
341
- })
342
- .catch(error => {
343
- reject(error);
344
- });
345
- }));
346
- return Promise.all(promises);
341
+ ping(interval) {
342
+ // can't do much with interval, so ignoring it for compatibility reasons
343
+ return this.healthApi.getHealth()
344
+ .then(result => result.status === 'pass' ? [{ online: true }] : [{ online: false }]);
347
345
  }
348
346
  }
349
347
 
package/lib/aggregate.js CHANGED
@@ -22,16 +22,18 @@ function initAggregate(options) {
22
22
  options.overallLength = 0;
23
23
 
24
24
  // pre-fill the result with timestamps (add one before start and one after end)
25
- for (let i = 0; i <= options.maxIndex + 2; i++){
25
+ for (let i = 0; i <= options.maxIndex + 2; i++) {
26
26
  options.result[i] = {
27
- val: {ts: null, val: null},
28
- max: {ts: null, val: null},
29
- min: {ts: null, val: null},
30
- start: {ts: null, val: null},
31
- end: {ts: null, val: null}
27
+ val: {ts: null, val: null},
28
+ max: {ts: null, val: null},
29
+ min: {ts: null, val: null},
30
+ start: {ts: null, val: null},
31
+ end: {ts: null, val: null}
32
32
  };
33
33
 
34
- if (options.aggregate === 'average') options.averageCount[i] = 0;
34
+ if (options.aggregate === 'average') {
35
+ options.averageCount[i] = 0;
36
+ }
35
37
  }
36
38
  return options;
37
39
  }
@@ -40,9 +42,12 @@ function aggregation(options, data) {
40
42
  let index;
41
43
  let preIndex;
42
44
  for (let i = 0; i < data.length; i++) {
43
- if (!data[i]) continue;
44
- if (typeof data[i].ts !== 'number') data[i].ts = parseInt(data[i].ts, 10);
45
- if (data[i].ts < 946681200000) data[i].ts *= 1000;
45
+ if (!data[i]) {
46
+ continue;
47
+ }
48
+ if (typeof data[i].ts !== 'number') {
49
+ data[i].ts = parseInt(data[i].ts, 10);
50
+ }
46
51
 
47
52
  preIndex = Math.floor((data[i].ts - options.start) / options.step);
48
53
 
@@ -62,17 +67,29 @@ function aggregation(options, data) {
62
67
  }
63
68
 
64
69
  if (options.aggregate === 'max') {
65
- if (!options.result[index].val.ts) options.result[index].val.ts = Math.round(options.start + (((index - 1) + 0.5) * options.step));
66
- if (options.result[index].val.val === null || options.result[index].val.val < data[i].val) options.result[index].val.val = data[i].val;
70
+ if (!options.result[index].val.ts) {
71
+ options.result[index].val.ts = Math.round(options.start + (((index - 1) + 0.5) * options.step));
72
+ }
73
+ if (options.result[index].val.val === null || options.result[index].val.val < data[i].val) {
74
+ options.result[index].val.val = data[i].val;
75
+ }
67
76
  } else if (options.aggregate === 'min') {
68
- if (!options.result[index].val.ts) options.result[index].val.ts = Math.round(options.start + (((index - 1) + 0.5) * options.step));
69
- if (options.result[index].val.val === null || options.result[index].val.val > data[i].val) options.result[index].val.val = data[i].val;
77
+ if (!options.result[index].val.ts) {
78
+ options.result[index].val.ts = Math.round(options.start + (((index - 1) + 0.5) * options.step));
79
+ }
80
+ if (options.result[index].val.val === null || options.result[index].val.val > data[i].val) {
81
+ options.result[index].val.val = data[i].val;
82
+ }
70
83
  } else if (options.aggregate === 'average') {
71
- if (!options.result[index].val.ts) options.result[index].val.ts = Math.round(options.start + (((index - 1) + 0.5) * options.step));
84
+ if (!options.result[index].val.ts) {
85
+ options.result[index].val.ts = Math.round(options.start + (((index - 1) + 0.5) * options.step));
86
+ }
72
87
  options.result[index].val.val += parseFloat(data[i].val);
73
88
  options.averageCount[index]++;
74
89
  } else if (options.aggregate === 'total') {
75
- if (!options.result[index].val.ts) options.result[index].val.ts = Math.round(options.start + (((index - 1) + 0.5) * options.step));
90
+ if (!options.result[index].val.ts) {
91
+ options.result[index].val.ts = Math.round(options.start + (((index - 1) + 0.5) * options.step));
92
+ }
76
93
  options.result[index].val.val += parseFloat(data[i].val);
77
94
  } else if (options.aggregate === 'minmax') {
78
95
  if (options.result[index].min.ts === null) {
@@ -195,7 +212,6 @@ function finishAggregation(options) {
195
212
  };
196
213
  } // start, min, max == end
197
214
  else {
198
-
199
215
  options.result.splice(ii + 1, 0, {
200
216
  ts: options.result[ii].min.ts,
201
217
  val: options.result[ii].min.val
@@ -261,8 +277,8 @@ function finishAggregation(options) {
261
277
  for (let k = options.result.length - 1; k >= 0; k--) {
262
278
  if (options.result[k].val.ts) {
263
279
  options.result[k] = {
264
- ts: options.result[k].val.ts,
265
- val: (options.result[k].val.val !== null) ? Math.round(options.result[k].val.val / options.averageCount[k] * 100) / 100 : null
280
+ ts: options.result[k].val.ts,
281
+ val: options.result[k].val.val !== null ? Math.round(options.result[k].val.val / options.averageCount[k] * 100) / 100 : null
266
282
  };
267
283
  } else {
268
284
  // no one value in this interval
@@ -282,16 +298,26 @@ function finishAggregation(options) {
282
298
  }
283
299
  }
284
300
  }
301
+
285
302
  beautify(options);
286
303
  }
287
304
 
288
305
  function beautify(options) {
289
306
  let preFirstValue = null;
290
307
  let postLastValue = null;
291
- if (options.ignoreNull === 'true') options.ignoreNull = true; // include nulls and replace them with last value
292
- if (options.ignoreNull === 'false') options.ignoreNull = false; // include nulls
293
- if (options.ignoreNull === '0') options.ignoreNull = 0; // include nulls and replace them with 0
294
- if (options.ignoreNull !== true && options.ignoreNull !== false && options.ignoreNull !== 0) options.ignoreNull = false;
308
+
309
+ if (options.ignoreNull === 'true') { // include nulls and replace them with last value
310
+ options.ignoreNull = true;
311
+ } else
312
+ if (options.ignoreNull === 'false') { // include nulls
313
+ options.ignoreNull = false;
314
+ } else
315
+ if (options.ignoreNull === '0') { // include nulls and replace them with 0
316
+ options.ignoreNull = 0;
317
+ } else
318
+ if (options.ignoreNull !== true && options.ignoreNull !== false && options.ignoreNull !== 0) {
319
+ options.ignoreNull = false;
320
+ }
295
321
 
296
322
  // process null values, remove points outside the span and find first points after end and before start
297
323
  for (let i = 0; i < options.result.length; i++) {
@@ -348,7 +374,7 @@ function beautify(options) {
348
374
  if (firstY !== null) {
349
375
  // interpolate
350
376
  const y = preFirstValue.val + (firstY - preFirstValue.val) * (options.start - preFirstValue.ts) / (firstTS - preFirstValue.ts);
351
- options.result.unshift({ts: options.start, val: y});
377
+ options.result.unshift({ts: options.start, val: y, i: true});
352
378
  } else {
353
379
  options.result.unshift({ts: options.start, val: null});
354
380
  }
@@ -386,7 +412,7 @@ function beautify(options) {
386
412
  if (lastY !== null) {
387
413
  // make interpolation
388
414
  const _y = lastY + (postLastValue.val - lastY) * (options.end - lastTS) / (postLastValue.ts - lastTS);
389
- options.result.push({ts: options.end, val: _y});
415
+ options.result.push({ts: options.end, val: _y, i: true});
390
416
  } else {
391
417
  options.result.push({ts: options.end, val: null});
392
418
  }
@@ -407,9 +433,8 @@ function beautify(options) {
407
433
  }
408
434
  }
409
435
  }
410
- }
411
- else if (options.aggregate === 'none') {
412
- if ((options.count) && (options.result.length > options.count)) {
436
+ } else if (options.aggregate === 'none') {
437
+ if (options.count && options.result.length > options.count) {
413
438
  options.result = options.result.slice(0, options.count);
414
439
  }
415
440
  }
@@ -443,8 +468,10 @@ function sendResponse(adapter, msg, options, data, startTime) {
443
468
  }
444
469
  }
445
470
  options.result = aggregateData.result;
471
+
446
472
  beautify(options);
447
- if ((options.aggregate === 'none') && (options.count) && (options.result.length > options.count)) {
473
+
474
+ if (options.aggregate === 'none' && options.count && options.result.length > options.count) {
448
475
  options.result = options.result.slice(0, options.count);
449
476
  }
450
477
  aggregateData.result = options.result;
@@ -455,10 +482,11 @@ function sendResponse(adapter, msg, options, data, startTime) {
455
482
  aggregateData.result = options.result;
456
483
  }
457
484
 
458
- adapter.log.debug('Send: ' + aggregateData.result.length + ' of: ' + aggregateData.sourceLength + ' in: ' + (new Date().getTime() - startTime) + 'ms');
485
+ adapter.log.debug(`Send: ${aggregateData.result.length} of: ${aggregateData.sourceLength} in: ${Date.now() - startTime}ms`);
486
+
459
487
  adapter.sendTo(msg.from, msg.command, {
460
- result: aggregateData.result,
461
- step: aggregateData.step,
488
+ result: aggregateData.result,
489
+ step: aggregateData.step,
462
490
  error: null,
463
491
  sessionId: options.sessionId
464
492
  }, msg.callback);
@@ -468,8 +496,84 @@ function sendResponse(adapter, msg, options, data, startTime) {
468
496
  }
469
497
  }
470
498
 
471
- module.exports.sendResponse = sendResponse;
472
- module.exports.initAggregate = initAggregate;
473
- module.exports.aggregation = aggregation;
474
- module.exports.beautify = beautify;
475
- module.exports.finishAggregation = finishAggregation;
499
+ function sendResponseCounter(adapter, msg, options, data, startTime) {
500
+ // data
501
+ // 1586713810000 100
502
+ // 1586713810010 200
503
+ // 1586713810040 500
504
+ // 1586713810050 0
505
+ // 1586713810090 400
506
+ // 1586713810100 0
507
+ // 1586713810110 100
508
+ if (typeof data === 'string') {
509
+ adapter.log.error(data);
510
+ return adapter.sendTo(msg.from, msg.command, {
511
+ result: [],
512
+ error: data,
513
+ sessionId: options.sessionId
514
+ }, msg.callback);
515
+ }
516
+
517
+ if (data[0] && data[1]) {
518
+ // first | start | afterFirst | ...... | last | end | afterLast
519
+ // 5 | | 8 | 9 | 1 | 3 | | 5
520
+ // | 5+(8-5/tsDiff) | | 9 | 1 | | 3+(5-3/tsDiff) |
521
+ // (9 - 6.5) + (4 - 1)
522
+
523
+ if (data[1].ts === options.start) {
524
+ data.splice(0, 1);
525
+ }
526
+
527
+ if (data[0].ts < options.start && data[0].val > data[1].val) {
528
+ data.splice(0, 1);
529
+ }
530
+
531
+ // interpolate from first to start time
532
+ if (data[0].ts < options.start) {
533
+ const val = data[0].val + (data[1].val - data[0].val) * ((options.start - data[0].ts) / (data[1].ts - data[0].ts));
534
+ data.splice(0, 1);
535
+ data.unshift({ts: options.start, val, i: true});
536
+ }
537
+
538
+ if (data[data.length - 2].ts === options.end) {
539
+ data.splice(-1, 1);
540
+ }
541
+
542
+ const veryLast = data[data.length - 1];
543
+ const beforeLast = data[data.length - 2];
544
+
545
+ // interpolate from end time to last
546
+ if (options.end < veryLast.ts) {
547
+ const val = beforeLast.val + (veryLast.val - beforeLast.val) * ((options.end - beforeLast.ts) / (veryLast.ts - beforeLast.ts));
548
+ data.splice(-1, 1);
549
+ data.push({ts: options.end, val, i: true});
550
+ }
551
+
552
+ // at this point we expect [6.5, 9, 1, 4]
553
+ // at this point we expect [150, 200, 500, 0, 400, 0, 50]
554
+ let val = data[data.length - 1].val;
555
+ let sum = 0;
556
+ for (let i = data.length - 2; i >= 0; i--) {
557
+ if (data[i].val < val) {
558
+ sum += val - data[i].val;
559
+ }
560
+ val = data[i].val;
561
+ }
562
+
563
+ adapter.sendTo(msg.from, msg.command, {
564
+ result: sum,
565
+ error: null,
566
+ sessionId: options.sessionId
567
+ }, msg.callback);
568
+ } else {
569
+ adapter.log.info('No Data');
570
+ adapter.sendTo(msg.from, msg.command, {result: 0, step: null, error: null, sessionId: options.sessionId}, msg.callback);
571
+ }
572
+ }
573
+
574
+ module.exports.sendResponseCounter = sendResponseCounter;
575
+ module.exports.sendResponse = sendResponse;
576
+ module.exports.initAggregate = initAggregate;
577
+ module.exports.aggregation = aggregation;
578
+ module.exports.beautify = beautify;
579
+ module.exports.finishAggregation = finishAggregation;