iobroker.sql 1.16.2 → 2.0.2

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