-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.js
1866 lines (1580 loc) · 77.3 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const utils = require('@iobroker/adapter-core');
const CronJob = require('cron').CronJob;
const stateObjects = require('./lib/objects');
const PRECISION = 5;
const MIN15 = '15Min';
const HOUR = 'hour';
const DAY = 'day';
const WEEK = 'week';
const MONTH = 'month';
const QUARTER = 'quarter';
const YEAR = 'year';
// Which objects should be created (see lib/objects.js)
const nameObjects = {
count: {
save: [MIN15, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR],
temp: [MIN15, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, 'last5Min', 'lastPulse']
},
sumCount: {
save: [MIN15, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR],
temp: [MIN15, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, 'lastPulse']
},
sumDelta: {
save: [MIN15, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, 'delta', 'last'],
temp: [MIN15, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR]
},
minmax: {
save: [
'dayMin', 'weekMin', 'monthMin', 'quarterMin', 'yearMin',
'dayMax', 'weekMax', 'monthMax', 'quarterMax', 'yearMax',
'absMin', 'absMax'
],
temp: [
'dayMin', 'weekMin', 'monthMin', 'quarterMin', 'yearMin',
'dayMax', 'weekMax', 'monthMax', 'quarterMax', 'yearMax',
'last'
]
},
avg: {
save: ['15MinAvg', 'hourAvg', 'dayAvg', 'weekAvg', 'monthAvg', 'quarterAvg', 'yearAvg'],
temp: [
'15MinAvg', '15MinCount', '15MinSum',
'hourAvg', 'hourCount', 'hourSum',
'dayAvg', 'dayCount', 'daySum',
'weekAvg', 'weekCount', 'weekSum',
'monthAvg', 'monthCount', 'monthSum',
'quarterAvg', 'quarterCount', 'quarterSum',
'yearAvg', 'yearCount', 'yearSum',
'last'
]
},
timeCount: {
save: [
'onDay', 'onWeek', 'onMonth', 'onQuarter', 'onYear',
'offDay', 'offWeek', 'offMonth', 'offQuarter', 'offYear'
],
temp: [
'onDay', 'onWeek', 'onMonth', 'onQuarter', 'onYear',
'offDay', 'offWeek', 'offMonth', 'offQuarter', 'offYear',
'last01', 'last10', 'last'
]
},
fiveMin: {
save: ['mean5Min', 'dayMax5Min', 'dayMin5Min'],
temp: ['mean5Min', 'dayMax5Min', 'dayMin5Min']
},
sumGroup: {
save: [MIN15, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR],
temp: [MIN15, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR]
}
};
const column = [MIN15, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR];
const copyToSave = ['count', 'sumCount', 'sumDelta', 'sumGroup'];
function isTrue(val) {
return val === 1 || val === '1' || val === true || val === 'true' || val === 'on' || val === 'ON';
}
function isFalse(val) {
return val === 0 || val === '0' || val === false || val === 'false' || val === 'off' || val === 'OFF' || val === 'standby';
}
function roundValue(value, precision = 0) {
const multiplier = Math.pow(10, precision);
return Math.round(value * multiplier) / multiplier;
}
function timeConverter(timestamp) {
const a = new Date(timestamp);
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const year = a.getFullYear();
const month = months[a.getMonth()];
const date = a.getDate();
const hour = a.getHours();
const min = a.getMinutes();
const sec = a.getSeconds();
return `${date < 10 ? ' ' + date : date} ${month} ${year} ${hour < 10 ? '0' + hour : hour}:${min < 10 ? '0' + min : min}:${sec < 10 ? '0' + sec : sec}`;
}
class Statistics extends utils.Adapter {
constructor(options) {
super({
...options,
name: 'statistics'
});
this.tasks = [];
this.taskCallback = null;
this.tasksFinishedCallbacks = [];
this.crons = {};
this.groups = {};
this.states = {}; // hold all states locally
// to remember the used objects within the types (calculations)
this.typeObjects = {
sumDelta: [],
sumGroup: [],
avg: [],
minmax: [],
count: [],
sumCount: [],
timeCount: [],
fiveMin: [],
};
this.statDP = {}; // contains all custom object definitions (with Object-ID as key)
this.on('ready', this.onReady.bind(this));
this.on('objectChange', this.onObjectChange.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('message', this.onMessage.bind(this));
this.on('unload', this.onUnload.bind(this));
}
async onReady() {
await this.setStateAsync('info.started', { val: false, ack: true });
// typeObjects is rebuilt after starting the adapter
// deleting data points during runtime must be cleaned up in both arrays
// reading the setting (here come with other setting!)
const doc = await this.getObjectViewAsync('system', 'custom', {});
let objCount = 0;
if (doc && doc.rows) {
for (let i = 0, l = doc.rows.length; i < l; i++) {
if (doc.rows[i].value) {
const id = doc.rows[i].id;
const custom = doc.rows[i].value;
if (!custom || !custom[this.namespace] || !custom[this.namespace].enabled) continue;
this.log.info(`[SETUP] enabled statistics for ${id}`);
this.statDP[id] = custom[this.namespace];
objCount++;
}
}
if (this.config.groups) {
for (let g = 0; g < this.config.groups.length; g++) {
const groupConfig = this.config.groups[g];
const groupId = groupConfig.id;
if (groupId) {
this.groups[groupId] = { config: groupConfig, items: [] };
if (!this.typeObjects.sumGroup.includes(groupId)) {
this.typeObjects.sumGroup.push(groupId);
}
await this.defineObject('sumGroup', groupId, `Sum for ${groupConfig.name}`, groupConfig.priceUnit);
} else {
this.log.error(`Found group without id in configuration - skipping! Check your instance configuration for groups`);
}
}
}
const keys = Object.keys(this.statDP);
await this.setupObjects(keys);
// subscribe to objects, so the settings in the object are arriving to the adapter
await this.subscribeForeignObjectsAsync('*');
this.log.info(`[SETUP] observing ${objCount} values after startup`);
}
// create cron-jobs
const timezone = this.config.timezone || 'Europe/Berlin';
// every 5min
try {
this.crons.fiveMin = new CronJob('*/5 * * * *',
() => this.fiveMin(),
() => this.log.debug('stopped fiveMin'),
true,
timezone
);
} catch (e) {
this.log.error(`creating cron fiveMin errored with: ${e}`);
}
// Every 15 minutes
try {
this.crons.fifteenMinSave = new CronJob('0,15,30,45 * * * *',
() => this.saveValues(MIN15),
() => this.log.debug('stopped fifteenMinSave'),
true,
timezone
);
} catch (e) {
this.log.error(`creating cron fifteenMinSave errored with: ${e}`);
}
// Hourly at 00 min
try {
this.crons.hourSave = new CronJob('0 * * * *',
() => this.saveValues(HOUR),
() => this.log.debug('stopped hourSave'),
true,
timezone
);
} catch (e) {
this.log.error(`creating cron hourSave errored with: ${e}`);
}
// daily at 23:59:58
try {
this.crons.dayTriggerTimeCount = new CronJob('58 59 23 * * *',
() => this.setTimeCountMidnight(),
() => this.log.debug('stopped dayTriggerTimeCount'),
true,
timezone
);
} catch (e) {
this.log.error(`creating cron dayTriggerTimeCount errored with: ${e}`);
}
// daily at 00:00
try {
this.crons.daySave = new CronJob('0 0 * * *',
() => this.saveValues(DAY),
() => this.log.debug('stopped daySave'),
true,
timezone
);
} catch (e) {
this.log.error(`creating cron daySave errored with: ${e}`);
}
// Monday 00:00
try {
this.crons.weekSave = new CronJob('0 0 * * 1',
() => this.saveValues(WEEK),
() => this.log.debug('stopped weekSave'),
true,
timezone
);
} catch (e) {
this.log.error(`creating cron weekSave errored with: ${e}`);
}
// Monthly at 1st of every month at 00:00
try {
this.crons.monthSave = new CronJob('0 0 1 * *',
() => this.saveValues(MONTH),
() => this.log.debug('stopped monthSave'),
true,
timezone
);
} catch (e) {
this.log.error(`creating cron monthSave errored with: ${e}`);
}
// Quarterly at 1st of every quarter at 00:00
try {
this.crons.quarterSave = new CronJob('0 0 1 1,4,7,10 *',
() => this.saveValues(QUARTER),
() => this.log.debug('stopped quarterSave'),
true,
timezone
);
} catch (e) {
this.log.error(`creating cron quarterSave errored with: ${e}`);
}
// New year at 1st of every year at 00:00
try {
this.crons.yearSave = new CronJob('0 0 1 1 *',
() => this.saveValues(YEAR),
() => this.log.debug('stopped yearSave'),
true,
timezone
);
} catch (e) {
this.log.error(`creating cron yearSave errored with: ${e}`);
}
for (const type in this.crons) {
if (Object.prototype.hasOwnProperty.call(this.crons, type) && this.crons[type]) {
this.log.debug(`[SETUP] ${type} status = "${this.crons[type].running ? 'running' : 'error'}", next event: ${timeConverter(this.crons[type].nextDate())}`);
}
}
await this.setStateAsync('info.started', { val: true, ack: true });
}
/**
* @param {string} id
* @param {ioBroker.Object | null | undefined} obj
*/
onObjectChange(id, obj) {
const isStart = !this.tasks.length;
this.tasks.push({
name: 'promise',
args: { id, obj },
callback: async (args) => {
// Warning, obj can be null if it was deleted
if (args?.obj?.common?.custom?.[this.namespace] && args.obj.common.custom[this.namespace]?.enabled) {
this.log.debug(`[OBJECT CHANGE] stat "${args.id}": ${JSON.stringify(args.obj.common.custom)}`);
// old but changed
if (this.statDP[args.id]) {
const newObj = args.obj.common.custom[this.namespace];
this.statDP[args.id] = newObj;
// Delete objects of unspecified types
Object.keys(this.typeObjects).forEach(type => {
if (!newObj[type]) {
this.delObject(`save.${type}.${args.id}`, { recursive: true });
this.delObject(`temp.${type}.${args.id}`, { recursive: true });
}
});
this.removeObject(args.id);
this.setupObjects([args.id]);
this.log.debug(`[OBJECT CHANGE] saved (updated) typeObject of stat "${args.id}": ${JSON.stringify(this.statDP[args.id])}`);
} else {
this.statDP[args.id] = args.obj.common.custom[this.namespace];
this.setupObjects([args.id]);
this.log.debug(`[OBJECT CHANGE] saved (new) typeObjects of stat "${args.id}": ${JSON.stringify(this.statDP[args.id])}`);
}
} else if (this.statDP[args.id]) {
this.log.debug(`[OBJECT CHANGE] removing typeObjects of stat "${args.id}": ${JSON.stringify(this.statDP[args.id])}`);
// Delete objects of all types
Object.keys(this.typeObjects).forEach(type => {
this.delObject(`save.${type}.${args.id}`, { recursive: true });
this.delObject(`temp.${type}.${args.id}`, { recursive: true });
});
delete this.statDP[args.id];
this.removeObject(args.id);
this.unsubscribeForeignObjects(args.id);
this.unsubscribeForeignStates(args.id);
}
}
});
isStart && this.processTasks();
}
/**
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
onStateChange(id, state) {
const isStart = !this.tasks.length;
if (id && state && state.ack) {
this.tasks.push({
name: 'promise',
args: { id, state },
callback: async (args) => {
this.log.debug(`[STATE CHANGE] ======================= ${args.id} =======================`);
this.log.debug(`[STATE CHANGE] stateChange => ${args.state.val}`);
if ((args.state.val === null) || (args.state.val === undefined) || isNaN(args.state.val)) {
this.log.warn(`[STATE CHANGE] wrong value => ${args.state.val} on ${args.id} => check the other adapter where value comes from `);
} else {
if (this.typeObjects.sumDelta.includes(args.id)) {
this.log.debug(`[STATE CHANGE] schedule onStateChangeSumDeltaValue for ${args.id}`);
this.onStateChangeSumDeltaValue(args.id, args.state.val);
} else if (this.typeObjects.avg.includes(args.id)) {
this.log.debug(`[STATE CHANGE] schedule onStateChangeAvgValue for ${args.id}`);
this.onStateChangeAvgValue(args.id, args.state.val);
}
if (this.typeObjects.minmax.includes(args.id)) {
this.log.debug(`[STATE CHANGE] schedule onStateChangeMinMaxValue for ${args.id}`);
this.onStateChangeMinMaxValue(args.id, args.state.val);
}
if (this.typeObjects.count.includes(args.id)) {
this.log.debug(`[STATE CHANGE] schedule onStateChangeCountValue for ${args.id}`);
this.onStateChangeCountValue(args.id, args.state.val);
}
if (this.typeObjects.sumCount.includes(args.id)) {
this.log.debug(`[STATE CHANGE] schedule onStateChangeSumCountValue for ${args.id}`);
this.onStateChangeSumCountValue(args.id, args.state.val);
}
if (this.typeObjects.timeCount.includes(args.id)) {
this.log.debug(`[STATE CHANGE] schedule onStateChangeTimeCntValue for ${args.id}`);
this.onStateChangeTimeCntValue(args.id, args.state);
}
// 5min is treated cyclically
}
}
});
}
isStart && this.processTasks();
}
/**
* @param {ioBroker.Message} msg
*/
onMessage(msg) {
this.log.debug(`[onMessage] Received ${JSON.stringify(msg)}`);
if (msg.command === 'groups' && msg.callback) {
this.sendTo(msg.from, msg.command, (this.config.groups || []).map(item => ({ label: item.name, value: item.id })), msg.callback);
} else if (msg.command === 'getCrons') {
this.sendTo(msg.from, msg.command, Object.keys(this.crons).map(item => ({ label: item, value: new Date(this.crons[item].nextDate()).getTime() })), msg.callback);
} else if (msg.command === 'enableStatistics') {
if (typeof msg.message === 'object' && msg.message?.id) {
const objId = msg.message.id;
this.getForeignObject(objId, (err, obj) => {
if (err || !obj) {
this.sendTo(msg.from, msg.command, {
success: false,
err: `Unable to get object with ID ${objId}`
}, msg.callback);
} else {
if (obj?.type === 'state') {
const objCustomOptions = {
common: {
custom: {}
}
};
const objCustomDefaults = {
enabled: true,
// for boolean states
count: false,
fiveMin: false, // requires .count = true
sumCount: false,
impUnitPerImpulse: 1, // requires .sumCount = true
impUnit: '', // requires .sumCount = true
timeCount: false,
// for number states
avg: false,
minmax: false,
sumDelta: false,
sumIgnoreMinus: false,
sumGroup: undefined, // requires .sumCount = true or .sumDelta = true
groupFactor: 1, // requres sumGroup
logName: String(obj._id).split('.').pop()
};
if (typeof msg.message === 'object' && typeof msg.message?.options === 'object') {
objCustomOptions.common.custom[this.namespace] = {
...objCustomDefaults,
...msg.message.options
};
} else {
objCustomOptions.common.custom[this.namespace] = {
...objCustomDefaults,
count: obj.common.type === 'boolean',
avg: obj.common.type === 'number'
};
}
this.log.debug(`Extending state ${JSON.stringify(obj)} with ${JSON.stringify(objCustomOptions)}`);
this.extendForeignObject(objId, objCustomOptions, (err) => {
if (err) {
this.log.error(`enableStatistics of ${objId} failed: ${err}`);
this.sendTo(msg.from, msg.command, {
success: false,
err: err
}, msg.callback);
} else {
this.sendTo(msg.from, msg.command, {
success: true,
err: null
}, msg.callback);
}
});
} else {
this.sendTo(msg.from, msg.command, {
success: false,
err: `Object with ID ${objId} is not a state: ${obj?.type}`
}, msg.callback);
}
}
});
} else {
this.sendTo(msg.from, msg.command, {
success: false,
err: `Configuration missing - please set at least { id: 'your.object.id' }`
}, msg.callback);
}
} else if (msg.command === 'saveValues') {
// Used for integration tests
if (msg.message?.period && column.includes(msg.message.period)) {
this.saveValues(msg.message.period);
this.sendTo(msg.from, msg.command, { success: true, period: msg.message.period }, msg.callback);
} else {
this.sendTo(msg.from, msg.command, { success: false, err: 'invalid time period' }, msg.callback);
}
}
}
/**
* @param {() => void} callback
*/
onUnload(callback) {
try {
this.setStateAsync('info.started', { val: false, ack: true });
this.setStateAsync('info.working', { val: false, ack: true });
// possibly also delete a few schedules
for (const type in this.crons) {
if (Object.prototype.hasOwnProperty.call(this.crons, type) && this.crons[type]) {
this.crons[type].stop();
this.crons[type] = null;
}
}
this.log.info('cleaned everything up...');
callback();
} catch {
callback();
}
}
async isTrueNew(id, val, type) {
// detection if a count value is real or only from polling with same state
let newPulse = false;
const value = await this.getValueAsync(`temp.${type}.${id}.lastPulse`);
await this.setValueAsync(`temp.${type}.${id}.lastPulse`, val);
if (value === val) {
newPulse = false;
this.log.debug(`new pulse false ? ${newPulse}`);
} else {
newPulse = isTrue(val);
this.log.debug(`new pulse true ? ${newPulse}`);
}
return newPulse;
}
async getValueAsync(id) {
return new Promise((resolve, reject) => {
if (Object.prototype.hasOwnProperty.call(this.states, id)) {
resolve(this.states[id]);
} else {
this.getState(id, (err, state) => {
if (err) {
reject(err);
}
this.states[id] = state ? state.val : null;
resolve(this.states[id]);
});
}
});
}
async setValueAsync(id, value) {
return new Promise((resolve, reject) => {
this.states[id] = value;
this.setState(id, { val: value, ack: true }, (err) => {
if (err) {
reject(err);
}
resolve(value);
});
});
}
async setValueStatAsync(id, value) {
return new Promise((resolve, reject) => {
const ts = new Date();
ts.setMinutes(ts.getMinutes() - 1);
ts.setSeconds(59);
ts.setMilliseconds(0);
this.states[id] = value;
this.setState(id, { val: value, ts: ts.getTime(), ack: true }, (err) => {
if (err) {
reject(err);
}
resolve(value);
});
});
}
checkValue(value, ts, id, type) {
const now = new Date();
now.setSeconds(0);
now.setMilliseconds(0);
if (type === MIN15) {
// value may not be older than 15 min
now.setMinutes(now.getMinutes() - now.getMinutes() % 15);
} else if (type === HOUR) {
// value may not be older than full hour
now.setMinutes(0);
} else if (type === DAY) {
// value may not be older than 00:00 of today
now.setMinutes(0);
now.setHours(0);
} else if (type === WEEK) {
// value may not be older than 00:00 of today
now.setMinutes(0);
now.setHours(0);
} else if (type === MONTH) {
// value may not be older than 00:00 of today
now.setMinutes(0);
now.setHours(0);
now.setDate(1);
} else if (type === QUARTER) {
// value may not be older than 00:00 of today
now.setMinutes(0);
now.setHours(0);
now.setDate(1);
// 0, 3, 6, 9
now.setMonth(now.getMonth() - now.getMonth() % 3);
} else if (type === YEAR) {
// value may not be older than 1 Januar of today
now.setMinutes(0);
now.setHours(0);
now.setDate(1);
now.setMonth(0);
} else {
this.log.error('Unknown calc type: ' + type);
return value;
}
if (ts < now.getTime()) {
this.log.warn(`[STATE CHANGE] Value of ${id} ignored because older than ${now.toISOString()}`);
value = 0;
}
return value;
}
async copyValue(sourceId, targetId) {
let value = await this.getValueAsync(sourceId);
if (value !== null && value !== undefined) {
this.log.debug(`[SAVE VALUES] Process ${sourceId} = ${value}`);
value = value || 0; // protect against NaN
await this.setValueStatAsync(targetId, value);
await this.setValueAsync(sourceId, 0);
} else {
this.log.debug(`[SAVE VALUES] Process ${targetId} => no value found`);
}
}
async copyValueActMinMax(args) {
let value = await this.getValueAsync(args.temp);
if (value !== null && value !== undefined) {
this.log.debug(`[SAVE VALUES] Process ${args.temp} = ${value} to ${args.save}`);
value = value || 0; // protect against NaN
await this.setValueStatAsync(args.save, value);
const actual = await this.getValueAsync(args.actual);
this.log.debug(`[SET DAILY START MINMAX] Process ${args.temp} = ${actual} from ${args.actual}`);
await this.setValueAsync(args.temp, actual);
return true;
} else {
this.log.debug(`[SAVE VALUES & SET DAILY START MINMAX] Process ${args.temp} => no value found`);
return false;
}
}
setTimeCountMidnight() {
if (this.typeObjects.timeCount) {
for (let s = 0; s < this.typeObjects.timeCount.length; s++) {
const id = this.typeObjects.timeCount[s];
// bevor umgespeichert wird, muß noch ein Aufruf mit actual erfolgen, damit die restliche Zeit vom letzten Signalwechsel bis Mitternacht erfolgt
// aufruf von newTimeCntValue(id, "last") damit wird gleicher Zustand getriggert und last01 oder last10 zu Mitternacht neu gesetzt
this.getState(`temp.timeCount.${id}.last`, (err, last) => { //hier muss nur id stehen, dann aber noch Beachtung des Timestamps
//evtl. status ermitteln und dann setForeignState nochmals den Zustand schreiben um anzutriggern und aktuelle Zeit zu verwenden (bzw. 00:00:00)
const ts = new Date();
//ts.setMinutes(ts.getMinutes() - 1);
//ts.setSeconds(59);
//ts.setMilliseconds(0);
if (last) {
last.ts = ts.getTime();
this.onStateChangeTimeCntValue(id, last);
}
});
}
}
}
async setupObjects(ids) {
for (const id of ids) {
const obj = this.statDP[id];
if (obj.groupFactor && obj.groupFactor !== '0' && obj.groupFactor !== 0) {
obj.groupFactor = parseFloat(obj.groupFactor) || this.config.impFactor;
} else {
obj.groupFactor = this.config.impFactor; // Default from config if 0
}
if (obj.impUnitPerImpulse && obj.impUnitPerImpulse !== '0' && obj.impUnitPerImpulse !== 0) {
obj.impUnitPerImpulse = parseFloat(obj.impUnitPerImpulse) || this.config.impUnitPerImpulse;
} else {
obj.impUnitPerImpulse = this.config.impUnitPerImpulse; // Default from config if 0
}
const sourceObj = await this.getForeignObjectAsync(id);
const sourceUnit = sourceObj?.type === 'state' && sourceObj?.common?.unit;
// function is called with the custom objects
this.log.debug(`[CREATION] ============================== ${id} =============================`);
this.log.debug(`[CREATION] setup of object "${id}": ${JSON.stringify(obj)}`);
const logName = obj.logName;
// count
if (obj.count) {
this.log.debug(`[CREATION] count: ${id}`);
if (!this.typeObjects.count.includes(id)) {
this.typeObjects.count.push(id);
}
await this.defineObject('count', id, logName);
}
// sumCount
if (obj.sumCount) {
this.log.debug(`[CREATION] sumCount: ${id}`);
if (!this.typeObjects.sumCount.includes(id)) {
this.typeObjects.sumCount.push(id);
}
await this.defineObject('sumCount', id, logName, obj.impUnit);
}
// sumDelta
if (obj.sumDelta) {
this.log.debug(`[CREATION] sumDelta: ${id}`);
if (!this.typeObjects.sumDelta.includes(id)) {
this.typeObjects.sumDelta.push(id);
}
await this.defineObject('sumDelta', id, logName, sourceUnit);
}
// minMax
if (obj.minmax) {
this.log.debug(`[CREATION] minmax: ${id}`);
if (!this.typeObjects.minmax.includes(id)) {
this.typeObjects.minmax.push(id);
}
await this.defineObject('minmax', id, logName, sourceUnit);
}
// avg
if (obj.avg) {
this.log.debug(`[CREATION] avg: ${id}`);
if (!this.typeObjects.avg.includes(id)) {
this.typeObjects.avg.push(id);
}
await this.defineObject('avg', id, logName, sourceUnit);
}
// timeCount
if (obj.timeCount) {
this.log.debug(`[CREATION] timeCount: ${id}`);
if (!this.typeObjects.timeCount.includes(id)) {
this.typeObjects.timeCount.push(id);
}
await this.defineObject('timeCount', id, logName);
}
// fiveMin
if (obj.fiveMin && obj.count) {
this.log.debug(`[CREATION] fiveMin: ${id}`);
if (!this.typeObjects.fiveMin.includes(id)) {
this.typeObjects.fiveMin.push(id);
}
await this.defineObject('fiveMin', id, logName);
}
// sumGroup
if (obj.sumGroup && (obj.sumCount || obj.sumDelta) && this.groups[obj.sumGroup]) {
if (!this.groups[obj.sumGroup].items.includes(id)) {
this.groups[obj.sumGroup].items.push(id);
}
}
await this.subscribeForeignStatesAsync(id);
}
}
removeObject(id) {
Object.keys(this.states).forEach(key => {
if (key.indexOf(id) > -1) {
this.log.debug(`[DELETE] Removing "${key}" from value cache`);
delete this.states[key];
}
});
Object.keys(this.typeObjects).forEach(type => {
if (Array.isArray(this.typeObjects[type])) {
this.typeObjects[type] = this.typeObjects[type].filter(typeId => typeId !== id);
}
});
Object.keys(this.groups).forEach(g => {
if (this.groups[g].items && Array.isArray(this.groups[g].items)) {
this.groups[g].items = this.groups[g].items.filter(groupId => groupId !== id);
} else {
this.log.error(`Invalid structure of group "${g}": ${JSON.stringify(this.groups[g])}`);
}
});
}
saveValues(timePeriod) {
const isStart = !this.tasks.length;
const dayTypes = [];
for (const key in this.typeObjects) {
if (this.typeObjects[key].length && copyToSave.includes(key)) {
dayTypes.push(key);
}
}
this.log.debug(`[SAVE VALUES] saving ${timePeriod} values: ${dayTypes.join(', ')}`);
const tp = column.indexOf(timePeriod); // nameObjects[day] contains the time-related object value
// count, sumCount, sumDelta, sumGroup
for (let t = 0; t < dayTypes.length; t++) {
for (let s = 0; s < this.typeObjects[dayTypes[t]].length; s++) {
const nameObjId = nameObjects[dayTypes[t]].temp[tp];
// ignore last5min
if (nameObjId === 'last5Min') {
continue;
}
const id = this.typeObjects[dayTypes[t]][s];
this.tasks.push({
name: 'promise',
args: {
temp: `temp.${dayTypes[t]}.${id}.${nameObjId}`,
save: `save.${dayTypes[t]}.${id}.${nameObjId}`
},
callback: async (args) => {
await this.copyValue(args.temp, args.save);
}
});
}
}
// avg
if (this.typeObjects.avg) {
for (let s = 0; s < this.typeObjects.avg.length; s++) {
this.tasks.push({
name: 'promise',
args: {
id: this.typeObjects.avg[s],
timePeriod: timePeriod
},
callback: async (args) => {
await this.copyValue(`temp.avg.${args.id}.${timePeriod}Avg`, `save.avg.${args.id}.${timePeriod}Avg`);
const prevValue = await this.getValueAsync(`temp.avg.${args.id}.last`);
await this.setValueStatAsync(`temp.avg.${args.id}.${timePeriod}Avg`, prevValue);
await this.setValueStatAsync(`temp.avg.${args.id}.${timePeriod}Count`, 1);
await this.setValueStatAsync(`temp.avg.${args.id}.${timePeriod}Sum`, prevValue);
}
});
}
}
// fiveMin
if (timePeriod === DAY && this.typeObjects.fiveMin) {
for (let s = 0; s < this.typeObjects.fiveMin.length; s++) {
const id = this.typeObjects.fiveMin[s];
this.tasks.push({
name: 'promise',
args: {
temp: `temp.fiveMin.${id}.dayMin5Min`,
save: `save.fiveMin.${id}.dayMin5Min`
},
callback: async (args) => {
await this.copyValue(args.temp, args.save);
}
});
this.tasks.push({
name: 'promise',
args: {
temp: `temp.fiveMin.${id}.dayMax5Min`,
save: `save.fiveMin.${id}.dayMax5Min`
},
callback: async (args) => {
await this.copyValue(args.temp, args.save);
}
});
}
}
// timeCount
// DAY, WEEK, MONTH, QUARTER, YEAR
if (tp >= 2) {
if (this.typeObjects.timeCount) {
for (let s = 0; s < this.typeObjects.timeCount.length; s++) {
const id = this.typeObjects.timeCount[s];
this.tasks.push({
name: 'promise',
args: {
temp: 'temp.timeCount.' + id + '.' + nameObjects.timeCount.temp[tp - 2], // 0 is onDay
save: 'save.timeCount.' + id + '.' + nameObjects.timeCount.temp[tp - 2],
},
callback: async (args) => {
await this.copyValue(args.temp, args.save);
}
});
this.tasks.push({
name: 'promise',
args: {
temp: 'temp.timeCount.' + id + '.' + nameObjects.timeCount.temp[tp + 3], // +5 is offDay
save: 'save.timeCount.' + id + '.' + nameObjects.timeCount.temp[tp + 3],
},
callback: async (args) => {
await this.copyValue(args.temp, args.save);
}
});
}
}
}
// minmax
// DAY, WEEK, MONTH, QUARTER, YEAR
if (tp >= 2) {
if (this.typeObjects.minmax) {
for (let s = 0; s < this.typeObjects.minmax.length; s++) {
const id = this.typeObjects.minmax[s];
this.tasks.push({
name: 'promise',
args: {
temp: 'temp.minmax.' + id + '.' + nameObjects.minmax.temp[tp - 2], // 0 ist minDay
save: 'save.minmax.' + id + '.' + nameObjects.minmax.temp[tp - 2],
actual: 'temp.minmax.' + id + '.last',
},
callback: this.copyValueActMinMax.bind(this)
});
this.tasks.push({
name: 'promise',
args: {
temp: 'temp.minmax.' + id + '.' + nameObjects.minmax.temp[tp + 3], // +5 ist maxDay
save: 'save.minmax.' + id + '.' + nameObjects.minmax.temp[tp + 3],
actual: 'temp.minmax.' + id + '.last',
},
callback: this.copyValueActMinMax.bind(this)