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