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