iobroker.sql 2.2.0 → 4.0.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.
Files changed (53) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +177 -454
  3. package/admin/i18n/de/translations.json +3 -3
  4. package/admin/i18n/en/translations.json +2 -2
  5. package/admin/i18n/es/translations.json +12 -12
  6. package/admin/i18n/fr/translations.json +1 -1
  7. package/admin/i18n/it/translations.json +1 -1
  8. package/admin/i18n/nl/translations.json +1 -1
  9. package/admin/i18n/pl/translations.json +1 -1
  10. package/admin/i18n/pt/translations.json +1 -1
  11. package/admin/i18n/ru/translations.json +1 -1
  12. package/admin/jsonConfig.json +423 -321
  13. package/admin/words.js +14 -14
  14. package/build/lib/aggregate.js +1484 -0
  15. package/build/lib/aggregate.js.map +1 -0
  16. package/build/lib/connection-factory.js +7 -0
  17. package/build/lib/connection-factory.js.map +1 -0
  18. package/build/lib/mssql-client.js +67 -0
  19. package/build/lib/mssql-client.js.map +1 -0
  20. package/build/lib/mssql.js +267 -0
  21. package/build/lib/mssql.js.map +1 -0
  22. package/build/lib/mysql-client.js +55 -0
  23. package/build/lib/mysql-client.js.map +1 -0
  24. package/build/lib/mysql.js +245 -0
  25. package/build/lib/mysql.js.map +1 -0
  26. package/build/lib/postgresql-client.js +56 -0
  27. package/build/lib/postgresql-client.js.map +1 -0
  28. package/build/lib/postgresql.js +241 -0
  29. package/build/lib/postgresql.js.map +1 -0
  30. package/build/lib/sql-client-pool.js +369 -0
  31. package/build/lib/sql-client-pool.js.map +1 -0
  32. package/build/lib/sql-client.js +110 -0
  33. package/build/lib/sql-client.js.map +1 -0
  34. package/build/lib/sqlite.js +244 -0
  35. package/build/lib/sqlite.js.map +1 -0
  36. package/build/lib/sqlite3-client.js +68 -0
  37. package/build/lib/sqlite3-client.js.map +1 -0
  38. package/build/main.js +3591 -0
  39. package/build/main.js.map +1 -0
  40. package/docker-compose.yaml +57 -0
  41. package/io-package.json +67 -43
  42. package/package.json +31 -22
  43. package/admin/.gitignore +0 -0
  44. package/lib/aggregate.js +0 -968
  45. package/lib/mssql-client.js +0 -61
  46. package/lib/mssql.js +0 -270
  47. package/lib/mysql-client.js +0 -62
  48. package/lib/mysql.js +0 -257
  49. package/lib/postgresql-client.js +0 -202
  50. package/lib/postgresql.js +0 -252
  51. package/lib/sqlite.js +0 -252
  52. package/lib/tools.js +0 -99
  53. package/main.js +0 -3482
package/lib/aggregate.js DELETED
@@ -1,968 +0,0 @@
1
- /* jshint -W097 */
2
- /* jshint strict: false */
3
- /* jslint node: true */
4
- 'use strict';
5
- // THIS file should be identical with sql and history adapter's one
6
-
7
- function initAggregate(options) {
8
- let log = () => {};
9
- if (options.debugLog) {
10
- log = options.log || console.log;
11
- }
12
-
13
- //step; // 1 Step is 1 second
14
- if (options.step === null) {
15
- options.step = (options.end - options.start) / options.count;
16
- }
17
-
18
- // Limit 2000
19
- if ((options.end - options.start) / options.step > options.limit) {
20
- options.step = (options.end - options.start) / options.limit;
21
- }
22
-
23
- options.maxIndex = Math.ceil(((options.end - options.start) / options.step) - 1);
24
- options.result = [];
25
- options.averageCount = [];
26
- options.quantileDatapoints = [];
27
- options.integralDatapoints = [];
28
- options.aggregate = options.aggregate || 'minmax';
29
- options.overallLength = 0;
30
-
31
- if (options.aggregate === 'percentile') {
32
- if (typeof options.percentile !== 'number' || options.percentile < 0 || options.percentile > 100) {
33
- options.percentile = 50;
34
- }
35
- options.quantile = options.percentile / 100; // Internally we use quantile for percentile too
36
- }
37
- if (options.aggregate === 'quantile') {
38
- if (typeof options.quantile !== 'number' || options.quantile < 0 || options.quantile > 1) {
39
- options.quantile = 0.5;
40
- }
41
- }
42
- if (options.aggregate === 'integral') {
43
- if (typeof options.integralUnit !== 'number' || options.integralUnit <= 0) {
44
- options.integralUnit = 60;
45
- }
46
- options.integralUnit *= 1000; // Convert to milliseconds
47
- }
48
-
49
- log(`${options.logId} Initialize: maxIndex = ${options.maxIndex}, step = ${options.step}, start = ${options.start}, end = ${options.end}`);
50
- // pre-fill the result with timestamps (add one before start and one after end)
51
- try {
52
- options.result.length = options.maxIndex + 2;
53
- } catch (err) {
54
- err.message += `: ${options.maxIndex + 2}`;
55
- throw err;
56
- }
57
- // We define the array length but do not prefill values, we do that on runtime when needed
58
- options.result[0] = {
59
- val: {ts: null, val: null},
60
- max: {ts: null, val: null},
61
- min: {ts: null, val: null},
62
- start: {ts: null, val: null},
63
- end: {ts: null, val: null}
64
- };
65
- options.result[options.maxIndex + 2] = {
66
- val: {ts: null, val: null},
67
- max: {ts: null, val: null},
68
- min: {ts: null, val: null},
69
- start: {ts: null, val: null},
70
- end: {ts: null, val: null}
71
- };
72
-
73
- if (options.aggregate === 'average') {
74
- options.averageCount[0] = 0;
75
- options.averageCount[options.maxIndex + 2] = 0;
76
- }
77
-
78
- if (options.aggregate === 'percentile' || options.aggregate === 'quantile') {
79
- options.quantileDatapoints[0] = [];
80
- options.quantileDatapoints[options.maxIndex + 2] = [];
81
- }
82
- if (options.aggregate === 'integral') {
83
- options.integralDatapoints[0] = [];
84
- options.integralDatapoints[options.maxIndex + 2] = [];
85
- }
86
- return options;
87
- }
88
-
89
- function aggregation(options, data) {
90
- let index;
91
- let preIndex;
92
-
93
- let collectedTooEarlyData = [];
94
- let collectedTooLateData = [];
95
- let preIndexValueFound = false;
96
- let postIndexValueFound = false;
97
-
98
- for (let i = 0; i < data.length; i++) {
99
- if (!data[i]) {
100
- continue;
101
- }
102
- if (typeof data[i].ts !== 'number') {
103
- data[i].ts = parseInt(data[i].ts, 10);
104
- }
105
-
106
- preIndex = Math.floor((data[i].ts - options.start) / options.step);
107
-
108
- // store all border values
109
- if (preIndex < 0) {
110
- index = 0;
111
- // if the ts is even earlier than the "pre interval" ignore it, else we collect all data there
112
- if (preIndex < -1) {
113
- collectedTooEarlyData.push(data[i]);
114
- continue;
115
- }
116
- preIndexValueFound = true;
117
- } else if (preIndex > options.maxIndex) {
118
- index = options.maxIndex + 2;
119
- // if the ts is even later than the "post interval" ignore it, else we collect all data there
120
- if (preIndex > options.maxIndex + 1) {
121
- collectedTooLateData.push(data[i]);
122
- continue;
123
- }
124
- postIndexValueFound = true;
125
- } else {
126
- index = preIndex + 1;
127
- }
128
- options.overallLength++;
129
-
130
- if (options.result[index] === undefined) { // lazy initialization of datastructure
131
- options.result[index] = {
132
- val: {ts: null, val: null},
133
- max: {ts: null, val: null},
134
- min: {ts: null, val: null},
135
- start: {ts: null, val: null},
136
- end: {ts: null, val: null}
137
- };
138
-
139
- if (options.aggregate === 'average') {
140
- options.averageCount[index] = 0;
141
- }
142
-
143
- if (options.aggregate === 'percentile' || options.aggregate === 'quantile') {
144
- options.quantileDatapoints[index] = [];
145
- }
146
- if (options.aggregate === 'integral') {
147
- options.integralDatapoints[index] = [];
148
- }
149
- }
150
-
151
- aggregationLogic(data[i], index, options);
152
- }
153
-
154
- // If no data was found in the pre interval, but we have earlier data, we put the latest of them in the pre interval
155
- if (!preIndexValueFound && collectedTooEarlyData.length > 0) {
156
- collectedTooEarlyData = collectedTooEarlyData.sort(sortByTs);
157
- options.overallLength++;
158
- aggregationLogic(collectedTooEarlyData[collectedTooEarlyData.length - 1], 0, options);
159
- }
160
- // If no data was found in the post interval, but we have later data, we put the earliest of them in the pre interval
161
- if (!postIndexValueFound && collectedTooLateData.length > 0) {
162
- collectedTooLateData = collectedTooLateData.sort(sortByTs);
163
- options.overallLength++;
164
- aggregationLogic(collectedTooLateData[0], options.maxIndex + 2, options);
165
- }
166
-
167
- return {result: options.result, step: options.step, sourceLength: data.length} ;
168
- }
169
-
170
- function aggregationLogic(data, index, options) {
171
- let log = () => {};
172
- if (options.debugLog) {
173
- log = options.log || console.log;
174
- }
175
-
176
- if (!options.result[index]) {
177
- log(`${options.logId} Data index ${index} not initialized, ignore!`);
178
- return;
179
- }
180
-
181
- if (options.aggregate !== 'minmax' && !options.result[index].val.ts) {
182
- options.result[index].val.ts = Math.round(options.start + (((index - 1) + 0.5) * options.step));
183
- }
184
-
185
- if (options.aggregate === 'max') {
186
- if (options.result[index].val.val === null || options.result[index].val.val < data.val) {
187
- options.result[index].val.val = data.val;
188
- }
189
- } else if (options.aggregate === 'min') {
190
- if (options.result[index].val.val === null || options.result[index].val.val > data.val) {
191
- options.result[index].val.val = data.val;
192
- }
193
- } else if (options.aggregate === 'average') {
194
- options.result[index].val.val += parseFloat(data.val);
195
- options.averageCount[index]++;
196
- } else if (options.aggregate === 'total') {
197
- options.result[index].val.val += parseFloat(data.val);
198
- } else if (options.aggregate === 'minmax') {
199
- if (options.result[index].min.ts === null) {
200
- options.result[index].min.ts = data.ts;
201
- options.result[index].min.val = data.val;
202
-
203
- options.result[index].max.ts = data.ts;
204
- options.result[index].max.val = data.val;
205
-
206
- options.result[index].start.ts = data.ts;
207
- options.result[index].start.val = data.val;
208
-
209
- options.result[index].end.ts = data.ts;
210
- options.result[index].end.val = data.val;
211
- } else {
212
- if (data.val !== null) {
213
- if (data.val > options.result[index].max.val) {
214
- options.result[index].max.ts = data.ts;
215
- options.result[index].max.val = data.val;
216
- } else if (data.val < options.result[index].min.val) {
217
- options.result[index].min.ts = data.ts;
218
- options.result[index].min.val = data.val;
219
- }
220
- if (data.ts > options.result[index].end.ts) {
221
- options.result[index].end.ts = data.ts;
222
- options.result[index].end.val = data.val;
223
- }
224
- } else {
225
- if (data.ts > options.result[index].end.ts) {
226
- options.result[index].end.ts = data.ts;
227
- options.result[index].end.val = null;
228
- }
229
- }
230
- }
231
- } else if (options.aggregate === 'percentile' || options.aggregate === 'quantile') {
232
- options.quantileDatapoints[index].push(data.val);
233
- log(`${options.logId} Quantile ${index}: Add ts= ${data.ts} val=${data.val}`);
234
- } else if (options.aggregate === 'integral') {
235
- options.integralDatapoints[index].push(data);
236
- log(`${options.logId} Integral ${index}: Add ts= ${data.ts} val=${data.val}`);
237
- }
238
- }
239
-
240
- function finishAggregation(options) {
241
- let log = () => {};
242
- if (options.debugLog) {
243
- log = options.log || console.log;
244
- }
245
-
246
- if (options.aggregate === 'minmax') {
247
- let preBorderValueRemoved = false;
248
- let postBorderValueRemoved = false;
249
- const originalResultLength = options.result.length;
250
-
251
- let startIndex = 0;
252
- let endIndex = options.result.length;
253
- const finalResult = [];
254
-
255
- for (let ii = startIndex; ii < endIndex; ii++) {
256
- // no one value in this period
257
- if (options.result[ii] === undefined || options.result[ii].start.ts === null) {
258
- if (ii === 0) {
259
- preBorderValueRemoved = true;
260
- } else if (ii === originalResultLength - 1) {
261
- postBorderValueRemoved = true;
262
- }
263
- //options.result.splice(ii, 1);
264
- continue;
265
- }
266
- // just one value in this period: max == min == start == end
267
- if (options.result[ii].start.ts === options.result[ii].end.ts) {
268
- finalResult.push({
269
- ts: options.result[ii].start.ts,
270
- val: options.result[ii].start.val
271
- });
272
- } else
273
- if (options.result[ii].min.ts === options.result[ii].max.ts) {
274
- // if just 2 values: start == min == max, end
275
- if (options.result[ii].start.ts === options.result[ii].min.ts ||
276
- options.result[ii].end.ts === options.result[ii].min.ts) {
277
- finalResult.push({
278
- ts: options.result[ii].start.ts,
279
- val: options.result[ii].start.val
280
- });
281
- finalResult.push({
282
- ts: options.result[ii].end.ts,
283
- val: options.result[ii].end.val
284
- });
285
- } // if just 3 values: start, min == max, end
286
- else {
287
- finalResult.push({
288
- ts: options.result[ii].start.ts,
289
- val: options.result[ii].start.val
290
- });
291
- finalResult.push({
292
- ts: options.result[ii].max.ts,
293
- val: options.result[ii].max.val
294
- });
295
- finalResult.push({
296
- ts: options.result[ii].end.ts,
297
- val: options.result[ii].end.val
298
- });
299
- }
300
- } else
301
- if (options.result[ii].start.ts === options.result[ii].max.ts) {
302
- // just one value in this period: start == max, min == end
303
- if (options.result[ii].min.ts === options.result[ii].end.ts) {
304
- finalResult.push({
305
- ts: options.result[ii].start.ts,
306
- val: options.result[ii].start.val
307
- });
308
- finalResult.push({
309
- ts: options.result[ii].end.ts,
310
- val: options.result[ii].end.val
311
- });
312
- } // start == max, min, end
313
- else {
314
- finalResult.push({
315
- ts: options.result[ii].start.ts,
316
- val: options.result[ii].start.val
317
- });
318
- finalResult.push({
319
- ts: options.result[ii].min.ts,
320
- val: options.result[ii].min.val
321
- });
322
- finalResult.push({
323
- ts: options.result[ii].end.ts,
324
- val: options.result[ii].end.val
325
- });
326
- }
327
- } else
328
- if (options.result[ii].end.ts === options.result[ii].max.ts) {
329
- // just one value in this period: start == min, max == end
330
- if (options.result[ii].min.ts === options.result[ii].start.ts) {
331
- finalResult.push({
332
- ts: options.result[ii].start.ts,
333
- val: options.result[ii].start.val
334
- });
335
- finalResult.push({
336
- ts: options.result[ii].end.ts,
337
- val: options.result[ii].end.val
338
- });
339
- } // start, min, max == end
340
- else {
341
- finalResult.push({
342
- ts: options.result[ii].start.ts,
343
- val: options.result[ii].start.val
344
- });
345
- finalResult.push({
346
- ts: options.result[ii].min.ts,
347
- val: options.result[ii].min.val
348
- });
349
- finalResult.push({
350
- ts: options.result[ii].end.ts,
351
- val: options.result[ii].end.val
352
- });
353
- }
354
- } else
355
- if (options.result[ii].start.ts === options.result[ii].min.ts ||
356
- options.result[ii].end.ts === options.result[ii].min.ts) {
357
- // just one value in this period: start == min, max, end
358
- finalResult.push({
359
- ts: options.result[ii].start.ts,
360
- val: options.result[ii].start.val
361
- });
362
- finalResult.push({
363
- ts: options.result[ii].max.ts,
364
- val: options.result[ii].max.val
365
- });
366
- finalResult.push({
367
- ts: options.result[ii].end.ts,
368
- val: options.result[ii].end.val
369
- });
370
- } else {
371
- finalResult.push({
372
- ts: options.result[ii].start.ts,
373
- val: options.result[ii].start.val
374
- });
375
- // just one value in this period: start == min, max, end
376
- if (options.result[ii].max.ts > options.result[ii].min.ts) {
377
- finalResult.push({
378
- ts: options.result[ii].min.ts,
379
- val: options.result[ii].min.val
380
- });
381
- finalResult.push({
382
- ts: options.result[ii].max.ts,
383
- val: options.result[ii].max.val
384
- });
385
- } else {
386
- finalResult.push({
387
- ts: options.result[ii].max.ts,
388
- val: options.result[ii].max.val
389
- });
390
- finalResult.push({
391
- ts: options.result[ii].min.ts,
392
- val: options.result[ii].min.val
393
- });
394
- }
395
- finalResult.push({
396
- ts: options.result[ii].end.ts,
397
- val: options.result[ii].end.val
398
- });
399
- }
400
- }
401
- if (options.removeBorderValues) { // we cut out the additional results
402
- if (!preBorderValueRemoved) {
403
- finalResult.splice(0, 1);
404
- }
405
- if (!postBorderValueRemoved) {
406
- finalResult.length--;
407
- }
408
- }
409
- options.result = finalResult;
410
- } else if (options.aggregate === 'average') {
411
- let startIndex = 0;
412
- let endIndex = options.result.length;
413
- const finalResult = [];
414
- if (options.removeBorderValues) { // we cut out the additional results
415
- // options.result.splice(0, 1);
416
- // options.averageCount.splice(0, 1);
417
- // options.result.length--;
418
- // options.averageCount.length--;
419
- startIndex++;
420
- endIndex--;
421
- }
422
- for (let k = startIndex; k < endIndex; k++) {
423
- if (options.result[k] !== undefined && options.result[k].val.ts) {
424
- finalResult.push({
425
- ts: options.result[k].val.ts,
426
- val: options.result[k].val.val !== null ? Math.round(options.result[k].val.val / options.averageCount[k] * 100) / 100 : null
427
- });
428
- } else {
429
- // no one value in this interval
430
- //options.result.splice(k, 1);
431
- //options.averageCount.splice(k, 1); // not needed to clean up because not used anymore afterwards
432
- }
433
- }
434
- options.result = finalResult;
435
- } else if (options.aggregate === 'integral') {
436
- let preBorderValueRemoved = false;
437
- let postBorderValueRemoved = false;
438
- const originalResultLength = options.result.length;
439
- const finalResult = [];
440
-
441
- for (let k = 0; k < options.result.length; k++) {
442
- let indexStartTs = options.start + ((k - 1) * options.step);
443
- let indexEndTs = indexStartTs + options.step;
444
- if (options.integralDatapoints[k] && options.integralDatapoints[k].length) {
445
- // Sort datapoints by ts first
446
- options.integralDatapoints[k].sort(sortByTs);
447
- }
448
- // Make sure that we have entries that always start at the beginning of the interval
449
- if ((!options.integralDatapoints[k] || !options.integralDatapoints[k].length || options.integralDatapoints[k][0].ts > indexStartTs) && options.integralDatapoints[k - 1] && options.integralDatapoints[k -1][options.integralDatapoints[k - 1].length - 1]) {
450
- // if the first entry of this interval started somewhere in the start of the interval, add a start entry
451
- // same if there is no entry at all in the timeframe, use last entry from interval before
452
- options.integralDatapoints[k] = options.integralDatapoints[k] || [];
453
- options.integralDatapoints[k].unshift({
454
- ts: indexStartTs,
455
- val: options.integralDatapoints[k - 1][options.integralDatapoints[k - 1].length - 1].val
456
- });
457
- log(`${options.logId} Integral: ${k}: Added start entry for interval with ts=${indexStartTs}, val=${options.integralDatapoints[k][0].val}`);
458
- } else if (options.integralDatapoints[k] && options.integralDatapoints[k].length && options.integralDatapoints[k][0].ts > indexStartTs) {
459
- options.integralDatapoints[k].unshift({
460
- ts: indexStartTs,
461
- val: options.integralDatapoints[k][0].val
462
- });
463
- log(`${options.logId} Integral: ${k}: Added start entry for interval with ts=${indexStartTs}, val=${options.integralDatapoints[k][0].val} with same value as first point in interval because no former datapoint was found`);
464
- } else if (options.integralDatapoints[k] && options.integralDatapoints[k].length && options.integralDatapoints[k][0].ts < indexStartTs) {
465
- // if the first entry of this interval started before the start of the interval, search for the last value before the start of the interval, add as start entry
466
- let preFirstIndex = null;
467
- for (let kk = 0; kk < options.integralDatapoints[k].length; kk++) {
468
- if (options.integralDatapoints[k][kk].ts >= indexStartTs) {
469
- break;
470
- }
471
- preFirstIndex = kk;
472
- }
473
- if (preFirstIndex !== null) {
474
- options.integralDatapoints[k].splice(0, preFirstIndex, {
475
- ts: indexStartTs,
476
- val: options.integralDatapoints[k][preFirstIndex].val
477
- });
478
- log(`${options.logId} Integral: ${k}: Remove ${preFirstIndex + 1} entries and add start entry for interval with ts=${indexStartTs}, val=${options.integralDatapoints[k][0].val}`);
479
- }
480
- }
481
-
482
- const point = {
483
- ts: options.result[k] !== undefined && options.result[k].val.ts ? options.result[k].val.ts : Math.round(options.start + (((k - 1) + 0.5) * options.step)),
484
- val: null
485
- }
486
-
487
- const integralDatapoints = options.integralDatapoints[k] || [];
488
- const vals = integralDatapoints.map(dp => `[${dp.ts}, ${dp.val}]`);
489
- log(`${options.logId} Integral: ${k}: ${integralDatapoints.length} datapoints for interval for ${indexStartTs} - ${indexEndTs}: ${vals.join(',')}`);
490
-
491
- // Calculate Intervals and always calculate till the interval end (start made sure above already)
492
- for (let kk = 0; kk < integralDatapoints.length; kk++) {
493
- const valEndTs = integralDatapoints[kk + 1] ? Math.min(integralDatapoints[kk + 1].ts, indexEndTs) : indexEndTs;
494
- let valDuration = valEndTs - integralDatapoints[kk].ts;
495
- if (valDuration < 0) {
496
- log(`${options.logId} Integral: ${k}[${kk}] data do not belong to this interval, ignore ${JSON.stringify(integralDatapoints[kk])} (vs. ${valEndTs})`)
497
- break;
498
- }
499
- if (valDuration === 0) {
500
- log(`${options.logId} Integral: ${k}[${kk}] valDuration zero, ignore ${JSON.stringify(integralDatapoints[kk])}`)
501
- continue;
502
- }
503
- let valStart = parseFloat(integralDatapoints[kk].val) || 0;
504
- // End value is the next value, or if none, assume "linearity
505
- let valEnd = parseFloat((integralDatapoints[kk + 1] ? integralDatapoints[kk + 1].val : (options.integralDatapoints[k + 1] && options.integralDatapoints[k + 1][0] ? options.integralDatapoints[k + 1][0].val : valStart))) || 0;
506
- if (options.integralInterpolation !== 'linear' || valStart === valEnd) {
507
- const integralAdd = valStart * valDuration / options.integralUnit;
508
- // simple rectangle linear interpolation
509
- log(`${options.logId} Integral: ${k}[${kk}] : Add ${integralAdd} from val=${valStart} for ${valDuration}`);
510
- point.val += integralAdd;
511
- } else if ((valStart >= 0 && valEnd >= 0) || (valStart <= 0 && valEnd <= 0)) {
512
- // start and end are both positive or both negative, or one is 0
513
- let multiplier = 1;
514
- if (valStart <= 0 && valEnd <= 0) {
515
- multiplier = -1; // correct the sign at the end
516
- valStart = -valStart;
517
- valEnd = -valEnd;
518
- }
519
- const minVal = Math.min(valStart, valEnd);
520
- const maxVal = Math.max(valStart, valEnd);
521
- const rectPart = minVal * valDuration / options.integralUnit;
522
- const trianglePart = (maxVal - minVal) * valDuration * 0.5 / options.integralUnit;
523
- const integralAdd = (rectPart + trianglePart) * multiplier;
524
- log(`${options.logId} Integral: ${k}[${kk}] : Add R${rectPart} + T${trianglePart} => ${integralAdd} from val=${valStart} to ${valEnd} for ${valDuration}`);
525
- point.val += integralAdd;
526
- } else {
527
- // Values are on different sides of 0, so we need to find the 0 crossing
528
- const zeroCrossing = Math.abs((valStart * valDuration) / (valEnd - valStart));
529
- // Then calculate two linear segments, one from 0 to the crossing, and one from the crossing to the end
530
- const trianglePart1 = valStart * zeroCrossing * 0.5 / options.integralUnit;
531
- const trianglePart2 = valEnd * (valDuration - zeroCrossing) * 0.5 / options.integralUnit;
532
- const integralAdd = trianglePart1 + trianglePart2;
533
- log(`${options.logId} Integral: ${k}[${kk}] : Add T${trianglePart1} + T${trianglePart2} => ${integralAdd} from val=${valStart} to ${valEnd} for ${valDuration} (zero crossing ${zeroCrossing})`);
534
- point.val += integralAdd;
535
- }
536
- }
537
- /*options.result[k] = {
538
- ts: options.result[k].val.ts,
539
- val: options.result[k].val.val
540
- }*/
541
- if (point.val !== null) {
542
- finalResult.push(point);
543
- } else {
544
- if (k === 0) {
545
- preBorderValueRemoved = true;
546
- } else if (k === originalResultLength - 1) {
547
- postBorderValueRemoved = true;
548
- }
549
- }
550
- }
551
- if (options.removeBorderValues) { // we cut out the additional results
552
- if (!preBorderValueRemoved) {
553
- finalResult.splice(0, 1);
554
- }
555
- if (!postBorderValueRemoved) {
556
- finalResult.length--;
557
- }
558
- }
559
- options.result = finalResult;
560
- } else if (options.aggregate === 'percentile' || options.aggregate === 'quantile') {
561
- let startIndex = 0;
562
- let endIndex = options.result.length;
563
- const finalResult = [];
564
- if (options.removeBorderValues) { // we cut out the additional results
565
- /*options.result.splice(0, 1);
566
- options.quantileDatapoints.splice(0, 1);
567
- options.result.length--
568
- options.quantileDatapoints.length--;*/
569
- startIndex++;
570
- endIndex--;
571
- }
572
- for (let k = startIndex; k < endIndex; k++) {
573
- if (options.result[k] !== undefined && options.result[k].val.ts) {
574
- const point = {
575
- ts: options.result[k].val.ts,
576
- val: quantile(options.quantile, options.quantileDatapoints[k])
577
- };
578
- log(`${options.logId} Quantile ${k} ${point.ts}: ${options.quantileDatapoints[k].join(', ')} -> ${point.val}`);
579
- finalResult.push(point);
580
- } else {
581
- // no one value in this interval
582
- //options.result.splice(k, 1);
583
- //options.quantileDatapoints.splice(k, 1); // not needed to clean up because not used anymore afterwards
584
- }
585
- }
586
- options.result = finalResult;
587
- } else {
588
- let startIndex = 0;
589
- let endIndex = options.result.length;
590
- const finalResult = [];
591
- if (options.removeBorderValues) { // we cut out the additional results
592
- // options.result.splice(0, 1);
593
- // options.result.length--;
594
- startIndex++;
595
- endIndex--;
596
- }
597
- for (let j = startIndex; j < endIndex; j++) {
598
- if (options.result[j] !== undefined && options.result[j].val.ts) {
599
- finalResult.push({
600
- ts: options.result[j].val.ts,
601
- val: options.result[j].val.val
602
- });
603
- } else {
604
- // no one value in this interval
605
- //options.result.splice(j, 1);
606
- }
607
- }
608
- options.result = finalResult;
609
- }
610
-
611
- beautify(options);
612
- }
613
-
614
- function beautify(options) {
615
- let log = () => {};
616
- if (options.debugLog) {
617
- log = options.log || console.log;
618
- }
619
-
620
- log(`${options.logId} Beautify: ${options.result.length} results`);
621
- let preFirstValue = null;
622
- let postLastValue = null;
623
-
624
- if (options.ignoreNull === 'true') { // include nulls and replace them with last value
625
- options.ignoreNull = true;
626
- } else
627
- if (options.ignoreNull === 'false') { // include nulls
628
- options.ignoreNull = false;
629
- } else
630
- if (options.ignoreNull === '0') { // include nulls and replace them with 0
631
- options.ignoreNull = 0;
632
- } else
633
- if (options.ignoreNull !== true && options.ignoreNull !== false && options.ignoreNull !== 0) {
634
- options.ignoreNull = false;
635
- }
636
-
637
- // process null values, remove points outside the span and find first points after end and before start
638
- for (let i = 0; i < options.result.length; i++) {
639
- if (options.ignoreNull !== false) {
640
- // if value is null
641
- if (options.result[i].val === null) {
642
- // null value must be replaced with last not null value
643
- if (options.ignoreNull === true) {
644
- // remove value
645
- options.result.splice(i, 1);
646
- i--;
647
- continue;
648
- } else {
649
- // null value must be replaced with 0
650
- options.result[i].val = options.ignoreNull;
651
- }
652
- }
653
- }
654
-
655
- // remove all not requested points
656
- if (options.result[i].ts < options.start) {
657
- preFirstValue = options.result[i].val !== null ? options.result[i] : null;
658
- options.result.splice(i, 1);
659
- i--;
660
- continue;
661
- }
662
-
663
- postLastValue = options.result[i].val !== null ? options.result[i] : null;
664
-
665
- if (options.result[i].ts > options.end) {
666
- options.result.splice(i, options.result.length - i);
667
- break;
668
- }
669
- }
670
-
671
- // check start and stop
672
- if (options.result.length && options.aggregate !== 'none' && !options.removeBorderValues) {
673
- const firstTS = options.result[0].ts;
674
-
675
- if (firstTS > options.start && !options.removeBorderValues) {
676
- if (preFirstValue) {
677
- const firstY = options.result[0].val;
678
- // if steps
679
- if (options.aggregate === 'onchange' || !options.aggregate) {
680
- if (preFirstValue.ts !== firstTS) {
681
- options.result.unshift({ts: options.start, val: preFirstValue.val});
682
- } else {
683
- if (options.ignoreNull) {
684
- options.result.unshift({ts: options.start, val: firstY});
685
- }
686
- }
687
- } else {
688
- if (preFirstValue.ts !== firstTS) {
689
- if (firstY !== null) {
690
- // interpolate
691
- const y = preFirstValue.val + (firstY - preFirstValue.val) * (options.start - preFirstValue.ts) / (firstTS - preFirstValue.ts);
692
- options.result.unshift({ts: options.start, val: y, i: true});
693
- log(`${options.logId} interpolate ${y} from ${preFirstValue.val} to ${firstY} as first return value`);
694
- } else {
695
- options.result.unshift({ts: options.start, val: null});
696
- }
697
- } else {
698
- if (options.ignoreNull) {
699
- options.result.unshift({ts: options.start, val: firstY});
700
- }
701
- }
702
- }
703
- } else {
704
- if (options.ignoreNull) {
705
- options.result.unshift({ts: options.start, val: options.result[0].val});
706
- } else {
707
- options.result.unshift({ts: options.start, val: null});
708
- }
709
- }
710
- }
711
-
712
- const lastTS = options.result[options.result.length - 1].ts;
713
- if (lastTS < options.end && !options.removeBorderValues) {
714
- if (postLastValue) {
715
- // if steps
716
- if (options.aggregate === 'onchange' || !options.aggregate) {
717
- // if more data following, draw line to the end of chart
718
- if (postLastValue.ts !== lastTS) {
719
- options.result.push({ts: options.end, val: postLastValue.val});
720
- } else {
721
- if (options.ignoreNull) {
722
- options.result.push({ts: options.end, val: postLastValue.val});
723
- }
724
- }
725
- } else {
726
- if (postLastValue.ts !== lastTS) {
727
- const lastY = options.result[options.result.length - 1].val;
728
- if (lastY !== null) {
729
- // make interpolation
730
- const _y = lastY + (postLastValue.val - lastY) * (options.end - lastTS) / (postLastValue.ts - lastTS);
731
- options.result.push({ts: options.end, val: _y, i: true});
732
- log(`${options.logId} interpolate ${_y} from ${lastY} to ${postLastValue.val} as last return value`);
733
- } else {
734
- options.result.push({ts: options.end, val: null});
735
- }
736
- } else {
737
- if (options.ignoreNull) {
738
- options.result.push({ts: options.end, val: postLastValue.val});
739
- }
740
- }
741
- }
742
- } else {
743
- if (options.ignoreNull) {
744
- const lastY = options.result[options.result.length - 1].val;
745
- // if no more data, that means do not draw line
746
- options.result.push({ts: options.end, val: lastY});
747
- } else {
748
- // if no more data, that means do not draw line
749
- options.result.push({ts: options.end, val: null});
750
- }
751
- }
752
- }
753
- } else if (options.aggregate === 'none') {
754
- if (options.count && options.result.length > options.count) {
755
- options.result.splice(0, options.result.length - options.count);
756
- }
757
- }
758
-
759
- if (options.addId) {
760
- for (let i = 0; i < options.result.length; i++) {
761
- if (!options.result[i].id && options.id) {
762
- options.result[i].id = options.index || options.id;
763
- }
764
- }
765
- }
766
- }
767
-
768
- function sendResponse(adapter, msg, options, data, startTime) {
769
- let aggregateData;
770
- if (typeof data === 'string') {
771
- adapter.log.error(data);
772
- return adapter.sendTo(msg.from, msg.command, {
773
- result: [],
774
- step: 0,
775
- error: data,
776
- sessionId: options.sessionId
777
- }, msg.callback);
778
- }
779
-
780
- if (options.count && !options.start && data.length > options.count) {
781
- data.splice(0, data.length - options.count);
782
- }
783
- if (data[0]) {
784
- options.start = options.start || data[0].ts;
785
-
786
- if (!options.aggregate || options.aggregate === 'onchange' || options.aggregate === 'none' || options.preAggregated) {
787
- aggregateData = {result: data, step: 0, sourceLength: data.length};
788
-
789
- // convert ack from 0/1 to false/true
790
- if (options.ack && aggregateData.result) {
791
- for (let i = 0; i < aggregateData.result.length; i++) {
792
- aggregateData.result[i].ack = !!aggregateData.result[i].ack;
793
- }
794
- }
795
- options.result = aggregateData.result;
796
-
797
- beautify(options);
798
-
799
- if (options.aggregate === 'none' && options.count && options.result.length > options.count) {
800
- options.result.splice(0, options.result.length - options.count);
801
- }
802
- aggregateData.result = options.result;
803
- } else {
804
- initAggregate(options);
805
- aggregateData = aggregation(options, data);
806
- finishAggregation(options);
807
- aggregateData.result = options.result;
808
- }
809
-
810
- adapter.log.debug(`Send: ${aggregateData.result.length} of: ${aggregateData.sourceLength} in: ${Date.now() - startTime}ms`);
811
-
812
- adapter.sendTo(msg.from, msg.command, {
813
- result: aggregateData.result,
814
- step: aggregateData.step,
815
- error: null,
816
- sessionId: options.sessionId
817
- }, msg.callback);
818
- } else {
819
- adapter.log.info('No Data');
820
- adapter.sendTo(msg.from, msg.command, {result: [], step: null, error: null, sessionId: options.sessionId}, msg.callback);
821
- }
822
- }
823
-
824
- function sendResponseCounter(adapter, msg, options, data, startTime) {
825
- // data
826
- // 1586713810000 100
827
- // 1586713810010 200
828
- // 1586713810040 500
829
- // 1586713810050 0
830
- // 1586713810090 400
831
- // 1586713810100 0
832
- // 1586713810110 100
833
- if (typeof data === 'string') {
834
- adapter.log.error(data);
835
- return adapter.sendTo(msg.from, msg.command, {
836
- result: [],
837
- error: data,
838
- sessionId: options.sessionId
839
- }, msg.callback);
840
- }
841
-
842
- if (data[0] && data[1]) {
843
- // first | start | afterFirst | ...... | last | end | afterLast
844
- // 5 | | 8 | 9 | 1 | 3 | | 5
845
- // | 5+(8-5/tsDiff) | | 9 | 1 | | 3+(5-3/tsDiff) |
846
- // (9 - 6.5) + (4 - 1)
847
-
848
- if (data[1].ts === options.start) {
849
- data.splice(0, 1);
850
- }
851
-
852
- if (data[0].ts < options.start && data[0].val > data[1].val) {
853
- data.splice(0, 1);
854
- }
855
-
856
- // interpolate from first to start time
857
- if (data[0].ts < options.start) {
858
- const val = data[0].val + (data[1].val - data[0].val) * ((options.start - data[0].ts) / (data[1].ts - data[0].ts));
859
- data.splice(0, 1);
860
- data.unshift({ts: options.start, val, i: true});
861
- }
862
-
863
- if (data[data.length - 2] !== undefined && data[data.length - 2].ts === options.end) {
864
- data.length--;
865
- }
866
-
867
- const veryLast = data[data.length - 1];
868
- const beforeLast = data[data.length - 2];
869
-
870
- // interpolate from end time to last
871
- if (veryLast !== undefined && beforeLast !== undefined && options.end < veryLast.ts) {
872
- const val = beforeLast.val + (veryLast.val - beforeLast.val) * ((options.end - beforeLast.ts) / (veryLast.ts - beforeLast.ts));
873
- data.length--;
874
- data.push({ts: options.end, val, i: true});
875
- }
876
-
877
- // at this point we expect [6.5, 9, 1, 4]
878
- // at this point we expect [150, 200, 500, 0, 400, 0, 50]
879
- let sum = 0;
880
- if (data.length > 1) {
881
- let val = data[data.length - 1].val;
882
- for (let i = data.length - 2; i >= 0; i--) {
883
- if (data[i].val < val) {
884
- sum += val - data[i].val;
885
- }
886
- val = data[i].val;
887
- }
888
- }
889
-
890
- adapter.sendTo(msg.from, msg.command, {
891
- result: sum,
892
- error: null,
893
- sessionId: options.sessionId
894
- }, msg.callback);
895
- } else {
896
- adapter.log.info('No Data');
897
- adapter.sendTo(msg.from, msg.command, {result: 0, step: null, error: null, sessionId: options.sessionId}, msg.callback);
898
- }
899
- }
900
-
901
- /**
902
- * Get quantile value from an array.
903
- *
904
- * @param {Number} q - quantile
905
- * @param {Array|TypedArray} list - list of sorted values (ascending)
906
- *
907
- * @return {number} Quantile value
908
- */
909
- function getQuantileValue(q, list) {
910
- if (q === 0) return list[0];
911
-
912
- const index = list.length * q;
913
- if (Number.isInteger(index)) {
914
- // mean of two middle numbers
915
- return (list[index - 1] + list[index]) / 2;
916
- }
917
- return list[Math.ceil(index - 1)];
918
- }
919
-
920
- /**
921
- * Calculate quantile for given array of values.
922
- *
923
- * @template T
924
- * @param {Number|Array<Number>} qOrPs - quantile or a list of quantiles
925
- * @param {Array<T>|Array<Number>|TypedArray} list - array of values
926
- * @param {function(T): Number} [fn] - optional function to extract a value from an array item
927
- *
928
- * @return {Number|T|Array<Number>|Array<T>}
929
- */
930
- function quantile(qOrPs, list, fn) {
931
- const q = Array.isArray(qOrPs) ? qOrPs : [qOrPs];
932
-
933
- list = list.slice().sort(function (a, b) {
934
- if (fn) {
935
- a = fn(a);
936
- b = fn(b);
937
- }
938
-
939
- a = Number.isNaN(a) ? Number.NEGATIVE_INFINITY : a;
940
- b = Number.isNaN(b) ? Number.NEGATIVE_INFINITY : b;
941
-
942
- if (a > b) return 1;
943
- if (a < b) return -1;
944
-
945
- return 0;
946
- });
947
-
948
- if (q.length === 1) {
949
- return getQuantileValue(q[0], list);
950
- }
951
-
952
- return q.map(function (q) {
953
- return getQuantileValue(q, list);
954
- });
955
- }
956
-
957
- function sortByTs(a, b) {
958
- const aTs = a.ts;
959
- const bTs = b.ts;
960
- return (aTs < bTs) ? -1 : ((aTs > bTs) ? 1 : 0);
961
- }
962
-
963
- module.exports.sendResponseCounter = sendResponseCounter;
964
- module.exports.sendResponse = sendResponse;
965
- module.exports.initAggregate = initAggregate;
966
- module.exports.aggregation = aggregation;
967
- module.exports.beautify = beautify;
968
- module.exports.finishAggregation = finishAggregation;