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