iobroker.sql 1.16.0 → 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,570 +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
- 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.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;