forked from DrozmotiX/ioBroker.sourceanalytix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1748 lines (1461 loc) · 69.1 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
/* eslint-disable no-mixed-spaces-and-tabs */
'use strict';
/*
* Created with @ioBroker/create-adapter v1.11.0
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
const adapterHelpers = require('iobroker-adapter-helpers'); // Lib used for Unit calculations
const schedule = require('cron').CronJob; // Cron Scheduler
// Sentry error reporting, disable when testing alpha source code locally!
const disableSentry = false;
// Store all days and months
const basicStates = ['01_currentDay', '02_currentWeek', '03_currentMonth', '04_currentQuarter', '05_currentYear'];
const basicPreviousStates = ['01_previousDay', '02_previousWeek', '03_previousMonth', '04_previousQuarter', '05_previousYear'];
const weekdays = JSON.parse('["07_Sunday","01_Monday","02_Tuesday","03_Wednesday","04_Thursday","05_Friday","06_Saturday"]');
const months = JSON.parse('["01_January","02_February","03_March","04_April","05_May","06_June","07_July","08_August","09_September","10_October","11_November","12_December"]');
const stateDeletion = true, previousCalculationRounded = {};
const storeSettings = {};
let calcBlock = null; // Global variable to block all calculations
let delay = null; // Global array for all running timers
let useCurrency = null;
// Create variables for object arrays
const actualDate = {}; //, currentDay = null;
class Sourceanalytix extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
// @ts-ignore
super({
...options,
name: 'sourceanalytix',
});
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));
// Unit and price definitions, will be loaded at adapter start.
this.unitPriceDef = {
unitConfig: {},
pricesConfig: {}
};
this.activeStates = {}; // Array of activated states for SourceAnalytix
this.validStates = {}; // Array of all created states
this.visWidgetJson ={}; // Array containing all calculation values to use in vis widget
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
try {
this.log.info('Welcome to SourceAnalytix, making things ready ... ');
// Block all calculation functions during startup
calcBlock = true;
// Get system currency, use € as fallback in case of errors
const sys_conf = await this.getForeignObjectAsync('system.config');
if (sys_conf && sys_conf.common.currency){
useCurrency = sys_conf.common.currency;
} else {
useCurrency = '€';
}
// Load Unit definitions from helper library & prices from admin to workable memory array
await this.definitionLoader();
// Store current data/time information to memory
await this.refreshDates();
// Load setting for Year statistics from admin settings
storeSettings.storeWeeks = this.config.store_weeks;
storeSettings.storeMonths = this.config.store_months;
storeSettings.storeQuarters = this.config.store_quarters;
// Get all objects with custom configuration items
const customStateArray = await this.getObjectViewAsync('system', 'custom', {});
this.log.debug(`All states with custom items : ${JSON.stringify(customStateArray)}`);
// List all states with custom configuration
if (customStateArray && customStateArray.rows) { // Verify first if result is not empty
// Loop truth all states and check if state is activated for SourceAnalytix
for (const index in customStateArray.rows) {
if (customStateArray.rows[index].value) { // Avoid crash if object is null or empty
// Check if custom object contains data for SourceAnalytix
// @ts-ignore
if (customStateArray.rows[index].value[this.namespace]){
// Simplify stateID
const stateID = customStateArray.rows[index].id;
this.log.debug(`SourceAnalytix configuration found for ${stateID}`);
// Check if custom object is enabled for SourceAnalytix
// @ts-ignore
if(customStateArray.rows[index].value[this.namespace].enabled){
// Prepare array in constructor for further processing
this.activeStates[stateID] = {};
this.log.debug(`SourceAnalytix enabled state found ${stateID}`);
} else {
this.log.debug(`SourceAnalytix configuration found but not Enabled, skipping ${stateID}`);
}
} else {
this.log.debug(`No SourceAnalytix configuration found, skipping state`);
}
}
}
}
// Prepare memory values to count amount of activated states
const totalEnabledStates = Object.keys(this.activeStates).length;
let totalInitiatedStates = 0;
let totalFailedStates = 0;
this.log.info(`Found ${totalEnabledStates} SourceAnalytix enabled states`);
// Initialize all discovered states
let count = 1;
for (const stateID in this.activeStates) {
this.log.info(`Initialising "${stateID}" | (${count} of ${totalEnabledStates})`);
// Store relevant information into memory to handle calculations
const memoryReady = await this.buildStateDetailsArray(stateID);
if (memoryReady) {
await this.initialize(stateID);
totalInitiatedStates = totalInitiatedStates + 1;
this.log.info(`Initialization of ${stateID} successfully`);
} else {
this.log.error(`Initialization of ${stateID} failed, check warn messages !`);
totalFailedStates = totalFailedStates + 1;
}
count = count + 1;
}
// Start Daily reset function by cron job
await this.resetStartValues();
// Subscribe on all foreign objects to detect (de)activation of sourceanalytix enabled states
this.subscribeForeignObjects('*');
// Enable all calculations with timeout of 500 ms
if (delay) {
clearTimeout(delay);
delay = null;
}
delay = setTimeout(function () {
calcBlock = false;
}, 500);
if (totalFailedStates > 0) {
this.log.error(`Cannot handle calculations for ${totalFailedStates} of ${totalEnabledStates} enabled states, check error messages`);
if (totalFailedStates < totalEnabledStates){
this.log.warn(`Partially activated SourceAnalytix for ${totalInitiatedStates} of ${totalEnabledStates} states, check error messages!`);
}
} else {
this.log.info(`Successfully activated SourceAnalytix for all ${totalInitiatedStates} of ${totalEnabledStates} states, will do my Job until you stop me!`);
}
//ToDo: add cleanup for unused states
// this.cleanupUnused()
} catch (error) {
this.errorHandling('[onReady]', error);
}
}
//ToDo 0.5: Implement cleanup for unused states
// async cleanupUnused() {
// const allStates = await this.getAdapterObjectsAsync()
// this.log.info((JSON.stringify(allStates)))
// }
/**
* Load calculation factors from helper library and store to memory
*/
async definitionLoader() {
try {
// Load energy array and store exponents related to unit
let catArray = ['Watt', 'Watt_hour'];
const unitStore = this.unitPriceDef.unitConfig;
for (const item in catArray) {
const unitItem = adapterHelpers.units.electricity[catArray[item]];
for (const unitCat in unitItem) {
unitStore[unitItem[unitCat].unit] = {
exponent: unitItem[unitCat].exponent,
category: catArray[item],
};
}
}
// Load volumes array and store exponents related to unit
catArray = ['Liter', 'Cubic_meter'];
for (const item in catArray) {
const unitItem = adapterHelpers.units.volume[catArray[item]];
for (const unitCat in unitItem) {
unitStore[unitItem[unitCat].unit] = {
exponent: unitItem[unitCat].exponent,
category: catArray[item],
};
}
}
// Load price definition from admin configuration
const pricesConfig = this.config.pricesDefinition;
const priceStore = this.unitPriceDef.pricesConfig;
for (const priceDef in pricesConfig) {
priceStore[pricesConfig[priceDef].cat] = {
cat: pricesConfig[priceDef].cat,
uDes: pricesConfig[priceDef].cat,
uPpU: pricesConfig[priceDef].uPpU,
uPpM: pricesConfig[priceDef].uPpM,
costType: pricesConfig[priceDef].costType,
unitType: pricesConfig[priceDef].unitType,
};
}
console.debug(`All Unit category's ${JSON.stringify(this.unitPriceDef)}`);
} catch (error) {
this.errorHandling('[definitionLoader]', error);
}
}
/**
* Load state definitions to memory this.activeStates[stateID]
* @param {string} stateID ID of state to refresh memory values
*/
async buildStateDetailsArray(stateID) {
let initError = false;
this.log.debug(`[buildStateDetailsArray] started for ${stateID}`);
try {
let stateInfo;
try {
// Load configuration as provided in object
stateInfo = await this.getForeignObjectAsync(stateID);
if (!stateInfo) {
this.log.error(`Can't get information for ${stateID}, state will be ignored`);
delete this.activeStates[stateID];
this.unsubscribeForeignStates(stateID);
initError = true;
return false;
}
} catch (error) {
this.log.error(`${stateID} is incorrectly correctly formatted, ${JSON.stringify(error)}`);
delete this.activeStates[stateID];
this.unsubscribeForeignStates(stateID);
initError = true;
return false;
}
// Replace not allowed characters for state name
const newDeviceName = stateID.split('.').join('__');
// Check if configuration for SourceAnalytix is present, trow error in case of issue in configuration
if (stateInfo && stateInfo.common && stateInfo.common.custom && stateInfo.common.custom[this.namespace]) {
const customData = stateInfo.common.custom[this.namespace];
const commonData = stateInfo.common;
this.log.debug(`[buildStateDetailsArray] commonData ${JSON.stringify(commonData)}`);
// Load start value from config to memory (avoid wrong calculations at meter reset, set to 0 if empty)
const valueAtDeviceReset = (customData.valueAtDeviceReset || customData.valueAtDeviceReset === 0) ? customData.valueAtDeviceReset : null;
// Always set init value to null at first start, will take init value at first calculation from state
const valueAtDeviceInit = null;
// Read current known total value to memory (if present)
let cumulativeValue = await this.getCumulatedValue(stateID, newDeviceName);
cumulativeValue = cumulativeValue ? cumulativeValue : 0;
this.log.debug(`[buildStateDetailsArray] cumulativeValue ${JSON.stringify(cumulativeValue)} | valueAtDeviceReset ${JSON.stringify(valueAtDeviceReset)} | valueAtDeviceInit ${JSON.stringify(valueAtDeviceInit)}`);
// Check and load unit definition
let useUnit = '';
// Check if a unit is manually selected, if yes use that one
if (this.unitPriceDef.unitConfig[customData.selectedUnit]) {
useUnit = customData.selectedUnit;
this.log.debug(`[buildStateDetailsArray] unit manually chosen ${JSON.stringify(useUnit)}`);
// If not, try to automatically get unit from state object
} else if (commonData.unit && commonData.unit !== '' && this.unitPriceDef.unitConfig[commonData.unit]) {
useUnit = commonData.unit;
this.log.debug(`[buildStateDetailsArray] unit automatically detected ${JSON.stringify(useUnit)}`);
} else {
this.log.error(`No unit defined for ${stateID}, cannot execute calculations !`);
this.log.error(`Please choose unit manually in state configuration`);
initError = true;
}
// Load state price definition
if (!customData.selectedPrice || customData.selectedPrice === '' || customData.selectedPrice === 'Choose') {
this.log.error(`No cost type defined for ${stateID}, please Select Type of calculation at state setting`);
initError = true;
} else if (!this.unitPriceDef.pricesConfig[customData.selectedPrice]) {
this.log.error(`Selected Type ${customData.selectedPrice} does not exist in Price Definitions`);
this.log.error(`Please choose proper type for state ${stateID}`);
this.log.error(`Or add price definition ${customData.selectedPrice} in adapter settings`);
initError = true;
}
if (valueAtDeviceReset > cumulativeValue){
// Ignore issue if categories = Watt, init value not used
if (useUnit !== 'W') {
this.log.error(`Check settings for ${stateID} ! Known valueAtDeviceReset : (${valueAtDeviceReset}) > known cumulative value (${cumulativeValue}) cannot proceed`);
this.log.error(`Troubleshoot Data ${stateID} custom Data : ${JSON.stringify(stateInfo)} `);
initError = true;
}
}
// In case of one of above checks fails, abort procedure
if (initError){
this.log.error(`Cannot handle calculations for ${stateID}, check log messages and adjust settings!`);
delete this.activeStates[stateID];
this.unsubscribeForeignStates(stateID);
return false;
}
// Load price definition from settings & library
const stateType = this.unitPriceDef.pricesConfig[customData.selectedPrice].costType;
// Load state settings to memory
this.activeStates[stateID] = {
stateDetails: {
alias: customData.alias !== '' ? customData.alias : '',
consumption: customData.consumption,
costs: customData.costs,
deviceName: newDeviceName.toString(),
financialCategory: stateType,
headCategory: stateType === 'earnings' ? 'delivered' : 'consumed',
meter_values: customData.meter_values,
name: stateInfo.common.name !== '' ? customData.alias : 'No name known, please provide alias',
stateType: customData.selectedPrice,
stateUnit: useUnit,
useUnit: this.unitPriceDef.pricesConfig[customData.selectedPrice].unitType,
deviceResetLogicEnabled: customData.deviceResetLogicEnabled != null ? customData.deviceResetLogicEnabled || true : true,
threshold: customData.threshold != null ? customData.threshold || 1 : 1,
},
calcValues: {
cumulativeValue: cumulativeValue,
start_day: customData.start_day,
start_month: customData.start_month,
start_quarter: customData.start_quarter,
start_week: customData.start_week,
start_year: customData.start_year,
valueAtDeviceReset: valueAtDeviceReset,
valueAtDeviceInit: valueAtDeviceInit,
},
prices: {
basicPrice: this.unitPriceDef.pricesConfig[customData.selectedPrice].uPpM,
unitPrice: this.unitPriceDef.pricesConfig[customData.selectedPrice].uPpU,
},
};
// Extend memory with objects for watt to kWh calculation
if (useUnit === 'W') {
this.activeStates[stateID].calcValues.previousReadingWatt = null;
this.activeStates[stateID].calcValues.previousReadingWattTs = null;
}
this.log.debug(`[buildStateDetailsArray] completed for ${stateID}: with content ${JSON.stringify(this.activeStates[stateID])}`);
return true;
}
} catch (error) {
this.errorHandling(`[buildStateDetailsArray] ${stateID}`, error);
return false;
}
}
// Create object tree and states for all devices to be handled
async initialize(stateID) {
try {
this.log.debug(`Initialising ${stateID} with configuration ${JSON.stringify(this.activeStates[stateID])}`);
// Shorten configuration details for easier access
if (!this.activeStates[stateID] || !this.activeStates[stateID].stateDetails) {
this.log.error(`Cannot handle initialisation for ${stateID}`);
return;
}
const stateDetails = this.activeStates[stateID].stateDetails;
this.log.debug(`Defined calculation attributes for ${stateID} : ${JSON.stringify(this.activeStates[stateID])}`);
// Check if alias is used and update object with new naming (if changed)
let alias = stateDetails.name;
if (stateDetails.alias && stateDetails.alias !== '') {
alias = stateDetails.alias;
}
this.log.debug('Name after alias renaming' + alias);
// Create Device Object
await this.extendObjectAsync(stateDetails.deviceName, {
type: 'device',
common: {
name: alias
},
native: {},
});
// create states for day value storage
for (const x in weekdays) {
if (this.config.currentYearDays === true) {
await this.doLocalStateCreate(stateID, `currentWeek.${weekdays[x]}`, weekdays[x], false, false, true);
} else if (stateDeletion) {
this.log.debug(`Deleting states for week ${weekdays[x]} (if present)`);
await this.doLocalStateCreate(stateID, `currentWeek.${weekdays[x]}`, weekdays[x], false, true, true);
}
if (this.config.currentYearPrevious === true) {
await this.doLocalStateCreate(stateID, `previousWeek.${weekdays[x]}`, weekdays[x], false, false, true);
} else if (stateDeletion) {
this.log.debug(`Deleting states for week ${weekdays[x]} (if present)`);
await this.doLocalStateCreate(stateID, `previousWeek.${weekdays[x]}`, weekdays[x], false, true, true);
}
}
// create states for weeks
for (let y = 1; y < 54; y++) {
let weekNr;
if (y < 10) {
weekNr = '0' + y;
} else {
weekNr = y.toString();
}
const weekRoot = `weeks.${weekNr}`;
if (this.config.store_weeks) {
this.log.debug(`Creating states for week ${weekNr}`);
await this.doLocalStateCreate(stateID, weekRoot, weekNr);
} else if (stateDeletion) {
this.log.debug(`Deleting states for week ${weekNr} (if present)`);
await this.doLocalStateCreate(stateID, weekRoot, weekNr, false, true);
}
}
// create states for months
for (const month in months) {
const monthRoot = `months.${months[month]}`;
if (this.config.store_months) {
this.log.debug(`Creating states for month ${month}`);
await this.doLocalStateCreate(stateID, monthRoot, months[month]);
} else if (stateDeletion) {
this.log.debug(`Deleting states for month ${month} (if present)`);
await this.doLocalStateCreate(stateID, monthRoot, months[month], false, true);
}
}
// create states for quarters
for (let y = 1; y < 5; y++) {
const quarterRoot = `quarters.Q${y}`;
if (this.config.store_quarters) {
this.log.debug(`Creating states for quarter ${quarterRoot}`);
await this.doLocalStateCreate(stateID, quarterRoot, `Q${y}`);
} else if (stateDeletion) {
this.log.debug(`Deleting states for quarter ${quarterRoot} (if present)`);
await this.doLocalStateCreate(stateID, quarterRoot, quarterRoot, false, true);
}
}
// Create basic current states
for (const state of basicStates) {
await this.doLocalStateCreate(stateID, state, state, false, false, true);
// .${actualDate.year}.
//ToDo 0.4.9: Check if current year storage in Year root should be configurable
if (state === '05_currentYear' && ((stateDetails.consumption || stateDetails.costs)
&& (this.config.store_quarters || this.config.store_months || this.config.store_weeks ))){
await this.doLocalStateCreate(stateID, `${actualDate.year}.${stateDetails.headCategory}Cumulative`, `${stateDetails.headCategory}Cumulative`, true, false, false);
await this.doLocalStateCreate(stateID, `${actualDate.year}.${stateDetails.financialCategory}Cumulative`, `${stateDetails.financialCategory}Cumulative`, true, false, false, useCurrency);
} else if (state === '05_currentYear' && (!this.config.store_weeks && !this.config.store_months && !this.config.store_quarters)) {
await this.doLocalStateCreate(stateID, `${actualDate.year}.${stateDetails.headCategory}Cumulative`, `${stateDetails.headCategory}Cumulative`, true, true, false);
await this.doLocalStateCreate(stateID, `${actualDate.year}.${stateDetails.financialCategory}Cumulative`, `${stateDetails.financialCategory}Cumulative`, true, true, false, useCurrency);
}
}
// Create basic current states for previous periods
if (this.config.currentYearPrevious) {
for (const state of basicPreviousStates) {
await this.doLocalStateCreate(stateID, state, state, false, false, true);
}
}
// Create state for cumulative reading
const stateName = 'cumulativeReading';
await this.doLocalStateCreate(stateID, stateName, 'Cumulative Reading', true);
// Create state for cumulative reading at Year statistics
if (this.config.store_weeks || this.config.store_months || this.config.store_quarters){
await this.doLocalStateCreate(stateID, `${actualDate.year}.readingCumulative`, 'Cumulative Reading of Year total', true);
}
// Handle calculation
const value = await this.getForeignStateAsync(stateID);
this.log.debug(`First time calc result after initialising ${stateID} with value ${JSON.stringify(value)}`);
if (value) {
// await this.buildVisWidgetJson(stateID);
await this.calculationHandler(stateID, value);
}
// Subscribe state, every state change will trigger calculation now automatically
this.subscribeForeignStates(stateID);
} catch (error) {
this.errorHandling(`[initialize] ${stateID}`, error);
}
}
/**
* Is called if an object changes to ensure (de-) activation of calculation or update configuration settings
* @param {string} id
* @param {ioBroker.Object | null | undefined} obj
*/
async onObjectChange(id, obj) {
//ToDo : Verify with test-results if debounce on object change must be implemented
if (calcBlock) return; // cancel operation if calculation block is activate
try {
const stateID = id;
// Check if object is activated for SourceAnalytix
if (obj && obj.common) {
// if (obj.from === `system.adapter.${this.namespace}`) return; // Ignore object change if cause by SourceAnalytix to prevent overwrite
// Verify if custom information is available regarding SourceAnalytix
if (obj.common.custom && obj.common.custom[this.namespace] && obj.common.custom[this.namespace].enabled) {
// ignore object changes when caused by SA (memory is handled internally)
// if (obj.from !== `system.adapter.${this.namespace}`) {
this.log.debug(`Object array of SourceAnalytix activated state changed : ${JSON.stringify(obj)} stored config : ${JSON.stringify(this.activeStates)}`);
// const newDeviceName = stateID.split('.').join('__');
// Verify if the object was already activated, if not initialize new device
if (!this.activeStates[stateID]) {
this.log.info(`Enable SourceAnalytix for : ${stateID}`);
await this.buildStateDetailsArray(id);
this.log.debug(`Active state array after enabling ${stateID} : ${JSON.stringify(this.activeStates)}`);
if (this.activeStates[stateID]){
await this.initialize(stateID);
} else {
this.log.warn(`[Cannot enable SourceAnalytix for ${stateID}, check settings and error messages`);
}
} else {
this.log.info(`Updating SourceAnalytix configuration for : ${stateID}`);
await this.buildStateDetailsArray(id);
this.log.debug(`Active state array after updating configuration of ${stateID} : ${JSON.stringify(this.activeStates)}`);
// Only run initialisation if state is successfully created during buildStateDetailsArray
if (this.activeStates[stateID]){
await this.initialize(stateID);
} else {
this.log.warn(`[Cannot update SourceAnalytix configuration for ${stateID}, check settings and error messages`);
}
}
} else if (this.activeStates[stateID]) {
delete this.activeStates[stateID];
this.log.info(`Disabled SourceAnalytix for : ${stateID}`);
this.log.debug(`Active state array after deactivation of ${stateID} : ${JSON.stringify(this.activeStates)}`);
this.unsubscribeForeignStates(stateID);
}
} else {
// Object change not related to this adapter, ignoring
}
} catch (error) {
// Send code failure to sentry
this.errorHandling(`[onObjectChange] ${id}`, error);
}
}
/**
* Is called if a subscribed state changes
* @param {string} id of state
* @param {ioBroker.State | null | undefined} state
*/
onStateChange(id, state) {
if (calcBlock) return; // cancel operation if global calculation block is activate
try {
// Check if a valid state change has been received
if (state) {
// The state was changed
this.log.debug(`state ${id} changed : ${JSON.stringify(state)} SourceAnalytix calculation executed`);
//ToDo: Implement x ignore time (configurable) to avoid overload of unneeded calculations
// Avoid unneeded calculation if value is equal to known value in memory
// 10-01-2021 : disable IF check for new value to analyse if this solves 0 watt calc bug
// 11-01-2021 : removing if successfully result, but need to check debounce !
// Handle calculation for state
// Check if for some reason calculation handler ist called for an object not initialised
if (this.activeStates[id]){
this.calculationHandler(id, state);
} else {
this.log.debug(`[onStateChange] state not initialised, calculation cancelled]`);
}
// } else {
// this.log.debug(`Update of state ${id} received with equal value ${state.val} ignoring`);
// }
}
} catch (error) {
this.errorHandling(`[onStateChange] for ${id}`, error);
}
}
/**
* Daily logic to store start values in memory and previous values at states
*/
async resetStartValues() {
try {
const resetDay = new schedule('0 0 * * *', async () => {
// const resetDay = new schedule('* * * * *', async () => { // testing schedule
calcBlock = true; // Pause all calculations
const beforeReset = await this.refreshDates(); // Reset date values in memory
this.log.debug(`[resetStartValues] Dates current : ${JSON.stringify(actualDate)} | beforeReset ${JSON.stringify(this.activeStates[beforeReset])}`);
// Read state array and write Data for every active state
for (const stateID in this.activeStates) {
this.log.info(`Reset start values for : ${stateID}`);
this.log.info(`Memory values before reset : ${JSON.stringify(this.activeStates[stateID])}`);
try {
if (this.activeStates[stateID] == null || this.activeStates[stateID].calcValues == null || this.activeStates[stateID].stateDetails == null) {
this.log.error(`Cannot handle Day reset for ${stateID}, check your configuration (error messages at adapter start)`);
continue;
}
const stateValues = this.activeStates[stateID].calcValues;
const stateDetails = this.activeStates[stateID].stateDetails;
// get current meter value
const reading = this.activeStates[stateID].calcValues.cumulativeValue;
if (reading === null || reading === undefined) continue;
this.log.debug(`Memory values for ${stateID} before reset : ${JSON.stringify(this.activeStates[stateID])}`);
this.log.debug(`Current known state values : ${JSON.stringify(stateValues)}`);
// Prepare custom object and store correct values
const obj = {};
obj.common = {};
obj.common.custom = {};
obj.common.custom[this.namespace] = {
start_day: reading,
start_month: beforeReset.month === actualDate.month ? stateValues.start_month : reading,
start_quarter: beforeReset.quarter === actualDate.quarter ? stateValues.start_quarter : reading,
start_week: beforeReset.week === actualDate.week ? stateValues.start_week : reading,
start_year: beforeReset.year === actualDate.year ? stateValues.start_year : reading,
valueAtDeviceInit: this.activeStates[stateID].calcValues.valueAtDeviceInit,
valueAtDeviceReset: this.activeStates[stateID].calcValues.valueAtDeviceReset,
};
// Extend memory with objects for watt to kWh calculation
if (stateDetails.stateUnit === 'W') {
this.activeStates[stateID].calcValues.previousReadingWatt = null;
this.activeStates[stateID].calcValues.previousReadingWattTs = null;
}
this.activeStates[stateID].calcValues = obj.common.custom[this.namespace];
this.activeStates[stateID].calcValues.cumulativeValue = reading;
//At week reset ensure current week values are moved to previous week and current set to 0
if (beforeReset.week !== actualDate.week) {
for (const x in weekdays) {
if (this.config.currentYearDays) {
// Handle consumption states consumption states
if (stateDetails.consumption) {
switch (stateDetails.headCategory) {
case 'consumed':
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.consumed.currentWeek.${weekdays[x]}`, `${stateDetails.deviceName}.currentYear.consumed.previousWeek.${weekdays[x]}`);
await this.setStateAsync(`${stateDetails.deviceName}.currentYear.consumed.currentWeek.${weekdays[x]}`, {
val: 0,
ack: true
});
break;
case 'delivered':
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.delivered.currentWeek.${weekdays[x]}`, `${stateDetails.deviceName}.currentYear.delivered.previousWeek.${weekdays[x]}`);
await this.setStateAsync(`${stateDetails.deviceName}.currentYear.delivered.currentWeek.${weekdays[x]}`, {
val: 0,
ack: true
});
break;
default:
}
}
// Handle financial states consumption states
switch (stateDetails.financialCategory) {
case 'costs':
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.costs.currentWeek.${weekdays[x]}`, `${stateDetails.deviceName}.currentYear.costs.previousWeek.${weekdays[x]}`);
await this.setStateAsync(`${stateDetails.deviceName}.currentYear.costs.currentWeek.${weekdays[x]}`, {
val: 0,
ack: true
});
break;
case 'earnings':
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.earnings.currentWeek.${weekdays[x]}`, `${stateDetails.deviceName}.currentYear.earnings.previousWeek.${weekdays[x]}`);
await this.setStateAsync(`${stateDetails.deviceName}.currentYear.earnings.currentWeek.${weekdays[x]}`, {
val: 0,
ack: true
});
break;
default:
}
// Handle meter reading states
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.meterReadings.currentWeek.${weekdays[x]}`, `${stateDetails.deviceName}.currentYear.meterReadings.previousWeek.${weekdays[x]}`);
await this.setStateAsync(`${stateDetails.deviceName}.currentYear.meterReadings.currentWeek.${weekdays[x]}`, {
val: 0,
ack: true
});
}
}
}
// Handle all "previous states"
if (this.config.currentYearPrevious) {
// Handle consumption states consumption states
if (stateDetails.consumption) {
switch (stateDetails.headCategory) {
case 'consumed':
if (beforeReset.day !== actualDate.day) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.consumed.01_currentDay`,
`${stateDetails.deviceName}.currentYear.consumed.01_previousDay`);
}
if (beforeReset.week !== actualDate.week) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.consumed.02_currentWeek`, `${stateDetails.deviceName}.currentYear.consumed.02_previousWeek`);
}
if (beforeReset.month !== actualDate.month) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.consumed.03_currentMonth`, `${stateDetails.deviceName}.currentYear.consumed.03_previousMonth`);
}
if (beforeReset.quarter !== actualDate.quarter) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.consumed.04_currentQuarter`, `${stateDetails.deviceName}.currentYear.consumed.04_previousQuarter`);
}
if (beforeReset.year !== actualDate.year) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.consumed.05_currentYear`, `${stateDetails.deviceName}.currentYear.consumed.05_previousYear`);
}
break;
case 'delivered':
if (beforeReset.day !== actualDate.day) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.delivered.01_currentDay`, `${stateDetails.deviceName}.currentYear.delivered.01_previousDay`);
}
if (beforeReset.week !== actualDate.week) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.delivered.02_currentWeek`, `${stateDetails.deviceName}.currentYear.delivered.02_previousWeek`);
}
if (beforeReset.month !== actualDate.month) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.delivered.03_currentMonth`, `${stateDetails.deviceName}.currentYear.delivered.03_previousMonth`);
}
if (beforeReset.quarter !== actualDate.quarter) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.delivered.04_currentQuarter`, `${stateDetails.deviceName}.currentYear.delivered.04_previousQuarter`);
}
if (beforeReset.year !== actualDate.year) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.delivered.05_currentYear`, `${stateDetails.deviceName}.currentYear.delivered.05_previousYear`);
}
break;
default:
}
}
// Handle financial states consumption states
switch (stateDetails.financialCategory) {
case 'costs':
if (beforeReset.day !== actualDate.day) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.costs.01_currentDay`, `${stateDetails.deviceName}.currentYear.costs.01_previousDay`);
}
if (beforeReset.week !== actualDate.week) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.costs.02_currentWeek`, `${stateDetails.deviceName}.currentYear.costs.02_previousWeek`);
}
if (beforeReset.month !== actualDate.month) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.costs.03_currentMonth`, `${stateDetails.deviceName}.currentYear.costs.03_previousMonth`);
}
if (beforeReset.quarter !== actualDate.quarter) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.costs.04_currentQuarter`, `${stateDetails.deviceName}.currentYear.costs.04_previousQuarter`);
}
if (beforeReset.year !== actualDate.year) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.costs.05_currentYear`, `${stateDetails.deviceName}.currentYear.costs.05_previousYear`);
}
break;
case 'earnings':
if (beforeReset.day !== actualDate.day) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.earnings.01_currentDay`, `${stateDetails.deviceName}.currentYear.earnings.01_previousDay`);
}
if (beforeReset.week !== actualDate.week) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.earnings.02_currentWeek`, `${stateDetails.deviceName}.currentYear.earnings.02_previousWeek`);
}
if (beforeReset.month !== actualDate.month) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.earnings.03_currentMonth`, `${stateDetails.deviceName}.currentYear.earnings.03_previousMonth`);
}
if (beforeReset.quarter !== actualDate.quarter) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.earnings.04_currentQuarter`, `${stateDetails.deviceName}.currentYear.earnings.04_previousQuarter`);
}
if (beforeReset.year !== actualDate.year) {
await this.setPreviousValues(`${stateDetails.deviceName}.currentYear.earnings.05_currentYear`, `${stateDetails.deviceName}.currentYear.earnings.05_previousYear`);
}
break;
default:
}
//ToDo: Think / discuss what to do with meter readings
// Handle meter reading states
// if (this.config.currentYearPrevious) await this.setStateAsync(`${stateID}.currentYear.meterReadings.previousWeek.${weekdays[x]}`, {
// val: await this.getStateAsync(`${stateID}.currentYear.meterReadings.previousWeek.${weekdays[x]}`),
// ack: true
// })
//derelvis
if (beforeReset.day !== actualDate.day) {
await this.setPreviousValues(`${stateDetails.deviceName}.cumulativeReading`, `${stateDetails.deviceName}.currentYear.meterReadings.01_previousDay`);
}
if (beforeReset.week !== actualDate.week) {
await this.setPreviousValues(`${stateDetails.deviceName}.cumulativeReading`, `${stateDetails.deviceName}.currentYear.meterReadings.02_previousWeek`);
}
if (beforeReset.month !== actualDate.month) {
await this.setPreviousValues(`${stateDetails.deviceName}.cumulativeReading`, `${stateDetails.deviceName}.currentYear.meterReadings.03_previousMonth`);
}
if (beforeReset.quarter !== actualDate.quarter) {
await this.setPreviousValues(`${stateDetails.deviceName}.cumulativeReading`, `${stateDetails.deviceName}.currentYear.meterReadings.04_previousQuarter`);
}
if (beforeReset.year !== actualDate.year) {
await this.setPreviousValues(`${stateDetails.deviceName}.cumulativeReading`, `${stateDetails.deviceName}.currentYear.meterReadings.05_previousYear`);
}
//derelvis end
}
await this.extendForeignObject(stateID, obj);
this.log.info(`Memory values after reset : ${JSON.stringify(this.activeStates[stateID])}`);
} catch (error) {
this.errorHandling(`[resetStartValues] ${stateID}`, error);
}
}
// Enable all calculations with timeout of 500 ms
if (delay) {
clearTimeout(delay);
delay = null;
}
delay = setTimeout(function () {
calcBlock = false;
}, 500);
});
resetDay.start();
} catch (error) {
this.errorHandling(`[resetStartValues]`, error);
calcBlock = false; // Continue all calculations
}
}
/**
* Function to handle previousState values
* @param {string} currentState - RAW state ID currentValue
* @param {string} [previousState] - RAW state ID previousValue
*/
async setPreviousValues(currentState, previousState) {
// Only set previous state if option is chosen
try {
if (this.config.currentYearPrevious) {
// Check if function input is correctly
if (currentState && previousState) {
// Get value of currentState
const currentVal = await this.getStateAsync(currentState);
if (currentVal) {
// Set current value to previous state
await this.setStateAsync(previousState, {
val: currentVal.val,
ack: true
});
}
} else {
this.log.debug(`[setPreviousValues] invalid data for currentState ${currentState} and/or previousState ${previousState} received`);
}
}
} catch (e) {
this.errorHandling(`[setPreviousValues]`, e);
}
}
/**
* Function to handle state creation
* @param {string} stateID - RAW state ID of monitored state
* @param {string} stateRoot - Root folder location
* @param {string} name - Name of state (also used for state ID !
* @param {boolean} [atDeviceRoot=FALSE] - store value at root instead of Year-Folder
* @param {boolean} [deleteState=FALSE] - Set to true will delete the state
* @param {boolean} [isCurrent=FALSE] - Store value in current Year
* @param {string} [forceUnit=''] - Force unit to be set on state
*/
async doLocalStateCreate(stateID, stateRoot, name, atDeviceRoot, deleteState, isCurrent, forceUnit) {
this.log.debug(`[doLocalStateCreate] ${stateID} | root : ${stateRoot} | name : ${name}) | atDeviceRoot ${atDeviceRoot} | isCurrent : ${isCurrent}`);
// Check if stateDetails are preset in memory, other wise abort
if (this.activeStates[stateID] == null || this.activeStates[stateID].stateDetails == null) return;
this.log.debug(`[doLocalStateCreate] stateDetails ${stateID} : ${JSON.stringify(this.activeStates[stateID].stateDetails)}`);
try {
const stateDetails = this.activeStates[stateID].stateDetails;
const dateRoot = isCurrent ? `currentYear` : actualDate.year;
let stateName = null;
// Common object content
const commonData = {
name: name,
type: 'number',
role: 'value',
read: true,
write: false,
unit: forceUnit ? forceUnit : stateDetails.useUnit,
def: 0,
};
// Define if state should be created at root level
if (atDeviceRoot) {
stateName = `${stateDetails.deviceName}.${stateRoot}`;
if (!deleteState){
await this.localSetObject(stateName, commonData);
} else {
await this.localDeleteState(stateName);
}
} else {
// Create consumption states
if (!deleteState && stateDetails.consumption) {
switch (stateDetails.headCategory) {
case 'consumed':
await this.localSetObject(`${stateDetails.deviceName}.${dateRoot}.consumed.${stateRoot}`, commonData);
await this.localDeleteState(`${stateDetails.deviceName}.${dateRoot}.delivered.${stateRoot}`);
break;