-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.js
1496 lines (1404 loc) · 58.8 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';
/*
* Created with @iobroker/create-adapter v1.27.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 cron = require('node-cron'); // Cron Schedulervar
const ObjectSettings = require('./ObjectSettings.js');
const historyData = require('./historyData.js');
const KWInfo = require('./KWInfo.js');
const DateHelper = require('./dateHelper.js');
const TimeFrames = {
Minute: 'Minute',
Hour: 'Hour',
Day: 'Day',
Week: 'Week',
Month: 'Month',
Quarter: 'Quarter',
Year: 'Year',
Infinite: 'Infinite',
};
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const TimeFramesNumber = {
Minute: '001',
Hour: '002',
Day: '01',
Week: '02',
Month: '03',
Quarter: '04',
Year: '05',
Infinite: '06',
};
// Load your modules here, e.g.:
// const fs = require("fs");
class valuetrackerovertime extends utils.Adapter {
/**
* @param [options]
*/
constructor(options) {
super({
...options,
name: 'valuetrackerovertime',
});
this.dicDatas = {};
this.myObjects = {};
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('objectChange', this.onObjectChange.bind(this));
this.on('unload', this.onUnload.bind(this));
this.writeTrimeFrameInfo = true;
this.historyWrite = 0;
this.crons = [];
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
await this.subscribeForeignObjectsAsync('*');
await this.initialObjects();
this.crons.push(
cron.schedule('* * * * *', async () => {
await this._timeFrameFinished(TimeFrames.Minute);
}),
);
this.crons.push(
cron.schedule('0 * * * *', async () => {
await this._timeFrameFinished(TimeFrames.Hour);
}),
);
this.crons.push(
cron.schedule('0 0 * * *', async () => {
await this._timeFrameFinished(TimeFrames.Day);
}),
);
this.crons.push(
cron.schedule('0 0 * * 1', async () => {
await this._timeFrameFinished(TimeFrames.Week);
}),
);
this.crons.push(
cron.schedule('0 0 1 * *', async () => {
await this._timeFrameFinished(TimeFrames.Month);
}),
);
this.crons.push(
cron.schedule('0 0 1 1,4,7,10 *', async () => {
await this._timeFrameFinished(TimeFrames.Quarter);
}),
);
this.crons.push(
cron.schedule('0 0 1 1 *', async () => {
await this._timeFrameFinished(TimeFrames.Year);
}),
);
this.crons.push(
cron.schedule('0 0 1 1 *', async () => {
//await this._timeFrameFinished(TimeFrames.Infinite);
}),
);
}
/**
* Is called if a subscribed object changes
*
* @param id
* @param obj
*/
async onObjectChange(id, obj) {
await this._initialObject(obj);
}
/**
* Is called if a subscribed state changes
*
* @param id
* @param state
*/
async onStateChange(id, state) {
if (state) {
if (id in this.dicDatas) {
await this._publishCurrentValue(
this.dicDatas[id],
new Date(state.ts),
await this._getNumberfromState(state),
);
} else if (id.startsWith(this.namespace) && id.includes('_startValues.start_')) {
const TimeFrame = id.substring(id.lastIndexOf('_') + 1);
const idsplit = id.split('.');
for (const oneoSID in this.dicDatas) {
/**@type {ObjectSettings} */
const oS = this.dicDatas[oneoSID];
if (oS.alias == idsplit[2]) {
if (state.ack) {
oS.startValues[TimeFrame] = await this._getNumberfromState(state);
} else {
this.log.warn(
`${id} changed, recalc Timeframe, old-Value: ${await this._getStartValue(
oS,
TimeFrame,
)} new-value: ${await this._getNumberfromState(state)}`,
);
await this._setStartValue(oS, TimeFrame, await this._getNumberfromState(state));
}
}
}
}
}
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
*
* @param callback
*/
async onUnload(callback) {
try {
await this.unsubscribeForeignStatesAsync('*');
await this.unsubscribeForeignObjectsAsync('*');
for (const cron_i in this.crons) {
const onecron = this.crons[cron_i];
onecron.destroy();
}
callback();
} catch {
callback();
}
}
/**
* Is called if a subscribed object changes
*
* @param TimeFrame
*/
async _timeFrameFinished(TimeFrame) {
const date = new Date();
for (const oneOD in this.dicDatas) {
const oS = this.dicDatas[oneOD];
this.log.debug(`${oS.alias} TimeFrame ${TimeFrame} end, insert now previous values `);
await this._pushNewPreviousSates(
oS,
TimeFrame,
oS.lastGoodValue - (await this._getStartValue(oS, TimeFrame)),
await this._getDateTimeInfoForPrevious(TimeFrame, date, 1),
);
this.log.debug(`${oS.alias} set startValue from TimeFrame ${TimeFrame} to ${oS.lastGoodValue}`);
await this._setStartValue(oS, TimeFrame, oS.lastGoodValue);
}
}
/**
* Get the Number from Iobroker State
*
* @param State
* @returns
*/
async _getNumberfromState(State) {
if (State && State.val && !isNaN(Number(State.val))) {
return Number(State.val);
}
return 0;
}
/**
* Read all Objects in iobroker and try to initial every Datapoint (only wenn custom set)
*/
async initialObjects() {
this.log.info('inital all Objects');
const objectschannels = await this.getForeignObjectsAsync(`${this.namespace}*`, 'channel');
for (const id in objectschannels) {
await this._setMyObject(id, objectschannels[id]);
}
const objectView = await this.getObjectViewAsync('system', 'custom', null);
if (objectView && objectView.rows) {
for (const counterObjectView in objectView.rows) {
const oneObjectview = objectView.rows[counterObjectView];
if (oneObjectview && oneObjectview.value && this.namespace in oneObjectview.value) {
await this._initialObject(await this.getForeignObjectAsync(oneObjectview.id));
}
}
}
this.log.info('initial completed');
}
async _getObjectAsync(ObjectID) {
if (!(ObjectID in this.myObjects)) {
this.myObjects[ObjectID] = await this.getObjectAsync(ObjectID);
}
return this.myObjects[ObjectID];
}
_setMyObject(id, obj) {
if (id.startsWith(this.namespace)) {
this.myObjects[id.substring(this.namespace.length + 1)] = obj;
}
}
/**
* Try to Initial an Datapoint (if Custom Setting exists, otherwise it is uninitial)
*
* @param iobrokerObject
*/
async _initialObject(iobrokerObject) {
if (iobrokerObject && iobrokerObject != undefined) {
await this._setMyObject(iobrokerObject._id, iobrokerObject);
// uninitialize ID
if (iobrokerObject._id in this.dicDatas) {
this.log.info(`disable : ${iobrokerObject._id}`);
await this._setExtendChannel(this.dicDatas[iobrokerObject._id], '', 'disabled', true);
await this.unsubscribeForeignStatesAsync(iobrokerObject._id);
delete this.dicDatas[iobrokerObject._id];
}
// only do something when enabled
if (
iobrokerObject &&
iobrokerObject.common &&
iobrokerObject.common.custom &&
iobrokerObject.common.custom[this.namespace] &&
iobrokerObject.common.custom[this.namespace].enabled
) {
const oS = new ObjectSettings(iobrokerObject, this.namespace);
//HistoryLoad
if (oS.history_work) {
iobrokerObject.common.custom[this.namespace].history_work = false;
await this.setForeignObjectAsync(oS.id, iobrokerObject);
await this._history_readDataFromHistory(oS);
return;
}
if (
iobrokerObject.common.custom[this.namespace].work !== undefined &&
!iobrokerObject.common.custom[this.namespace].work
) {
this.log.info(`not initial (work disabled)): ${iobrokerObject._id}`);
} else {
this.log.info(`initial (enabled): ${iobrokerObject._id}`);
//Check for duplicate Alias
for (const oneoSIdtoCheck in this.dicDatas) {
/**@type {ObjectSettings} */
const oStoCheck = this.dicDatas[oneoSIdtoCheck];
if (oStoCheck.alias.toLowerCase() == oS.alias.toLowerCase()) {
this.log.error(
`The Datapoint ${oS.id} have the same Alias (${oS.alias}) as the Datapoint ${
oStoCheck.id
}, ${oS.id} is now disabled`,
);
return;
}
}
//Do Subcribe and Create Objects
await this._generateTreeStructure(oS);
this.log.debug(`subscribeForeignStates ${oS.id}`);
await this.subscribeStatesAsync(`${oS.alias}._startValues.*`);
await this.subscribeForeignStatesAsync(oS.id);
//Read out last good value
const currentval = await this._getNumberfromState(await this.getForeignStateAsync(oS.id));
const startDay = await this._getStartValue(oS, TimeFrames.Day);
if (currentval < startDay) {
oS.lastGoodValue = startDay;
} else {
oS.lastGoodValue = currentval;
}
await this._publishCurrentValue(oS, new Date(), currentval);
this.dicDatas[oS.id] = oS;
}
this.log.debug(`initial done ${iobrokerObject._id} -> ${this.namespace}.${oS.alias}`);
}
}
}
/**
* Pull the before Values one level back and write set the latest with current TimeFrameValue
*
* @param oS
* @param TimeFrame
* @param TimeFrameValue
* @param DateTimeInfo
*/
async _pushNewPreviousSates(oS, TimeFrame, TimeFrameValue, DateTimeInfo) {
//Days before befüllen
let iBeforeCount;
//Die PreviousValues jeweils ein nach hinten schieben (von hinten anfangen um keine Daten zu verlieren)
for (iBeforeCount = oS.beforeCount(TimeFrame); iBeforeCount > 1; iBeforeCount--) {
const theValBefore = await this.getStateAsync(
oS.alias + (await this._GetObjectIdPrevious(oS, TimeFrame, iBeforeCount - 1)),
);
const theObjectBefore = await this._getObjectAsync(
oS.alias + (await this._GetObjectIdPrevious(oS, TimeFrame, iBeforeCount - 1)),
);
if (theValBefore && theObjectBefore && typeof theValBefore.val === 'number') {
await this._setStateRoundedAsync(
oS,
await this._GetObjectIdPrevious(oS, TimeFrame, iBeforeCount),
theValBefore.val,
false,
);
await this._setExtendObject(
oS,
await this._GetObjectIdPrevious(oS, TimeFrame, iBeforeCount),
theObjectBefore.common.name.toString(),
`value.history.${TimeFrame}`,
true,
false,
oS.output_unit,
'number',
);
}
}
//den jetzigen previous Wert speichern
if (oS.beforeCount(TimeFrame) >= 1) {
await this._setStateRoundedAsync(
oS,
await this._GetObjectIdPrevious(oS, TimeFrame, iBeforeCount),
TimeFrameValue,
true,
);
await this._setExtendObject(
oS,
await this._GetObjectIdPrevious(oS, TimeFrame, iBeforeCount),
DateTimeInfo,
`value.history.${TimeFrame}`,
true,
false,
oS.output_unit,
'number',
);
}
}
/**
* Analyse for CounterReset and recalc current TimeFrames
*
* @param oS
* @param date
* @param current_value
*/
async _publishCurrentValue(oS, date, current_value) {
if (oS.counterResetDetection && current_value < oS.lastGoodValue) {
//Verringerung erkannt -> neuanpassung der startWerte
if (Number.isNaN(oS.FirstWrongValue)) {
oS.FirstWrongValue = current_value;
oS.counterResetDetetion_CurrentCountAfterReset = 0;
oS.lastWrongValue = NaN;
}
//nur veränderte werte werden gezählt
if (oS.lastWrongValue != current_value) {
oS.counterResetDetetion_CurrentCountAfterReset += 1;
oS.lastWrongValue = current_value;
}
// Wenn der counterResetDetetion_CountAfterReset noch nicht erreicht ist, diesen Wert einfach ignorieren
if (oS.counterResetDetetion_CurrentCountAfterReset <= oS.counterResetDetetion_CountAfterReset) {
return;
}
//Ein Counter-Reset wurde erkannt, passe Startwerte an
this.log.warn(
`${oS.id} wurde scheinbar resetet! Reset von ${oS.lastGoodValue} nach ${
current_value
} passe alle Startwerte an`,
);
const theAnpassung = oS.lastGoodValue - oS.FirstWrongValue;
oS.lastGoodValue = current_value;
for (const TimeFrame in TimeFrames) {
await this._setStartValue(oS, TimeFrame, (await this._getStartValue(oS, TimeFrame)) - theAnpassung);
}
}
oS.lastGoodValue = current_value;
oS.FirstWrongValue = NaN;
for (const TimeFrame in TimeFrames) {
await this._calcCurrentTimeFrameValue(oS, date, TimeFrame);
}
}
/**
* Recalculate the Current and Detailed Values
*
* @param oS
* @param date
* @param TimeFrame
*/
async _calcCurrentTimeFrameValue(oS, date, TimeFrame) {
const TimeFrame_value = oS.lastGoodValue - (await this._getStartValue(oS, TimeFrame));
//Set Current_TimeframeValue
if (oS.beforeCount(TimeFrame) >= 0) {
await this._setStateRoundedAsync(oS, await this._getObjectIDCurrent(TimeFrame), TimeFrame_value, true);
}
//Set Detailed
await this._CreateAndSetObjectIdDetailed(oS, TimeFrame, date, TimeFrame_value);
}
/**
* round and set the State in iobroker
*
* @param oS
* @param id
* @param value
* @param outputMultiplie
*/
async _setStateRoundedAsync(oS, id, value, outputMultiplie) {
if (value) {
if (outputMultiplie) {
value *= oS.output_multiplier;
}
value = Number(value.toFixed(10));
}
await this.setStateAsync(oS.alias + id, value, true);
}
/**
* returns the quarter of the date
*
* @param date
*/
_getQuarter(date) {
return Math.ceil((date.getMonth() + 1) / 3);
}
/**
* create for every enabled object the needed current, history and before Datapoints
*
* @param oS
*/
async _generateTreeStructure(oS) {
await this._setExtendChannel(oS, '', `CounterData for ${oS.id}`, true);
await this._setExtendObject(oS, '._counterID', 'ObjectID', '', true, false, null, 'string');
await this.setStateAsync(`${oS.alias}._counterID`, oS.id, true);
await this._setExtendChannel(oS, '._startValues', 'startValues for TimeFrames', true);
for (const TimeFrame in TimeFrames) {
//Current_DP erzeugen/anpassen
if (oS.beforeCount(TimeFrame) >= 0) {
await this._setExtendObject(
oS,
await this._getObjectIDCurrent(TimeFrame),
`Current ${TimeFrame}`,
`value.Current.${TimeFrame}`,
true,
false,
oS.output_unit,
'number',
);
} else {
await this._setExtendObject(
oS,
await this._getObjectIDCurrent(TimeFrame),
'Disabled',
'value.Current.disabled',
false,
false,
oS.output_unit,
'number',
);
}
//Before erzeugen bzw leeren
let iBefore = 1;
for (iBefore = 1; iBefore <= oS.beforeCount(TimeFrame); iBefore++) {
const thePreviousID = await this._GetObjectIdPrevious(oS, TimeFrame, iBefore);
const oldObject = await this._getObjectAsync(oS.alias + thePreviousID);
let touseName = 'no data yet';
if (oldObject) {
touseName = oldObject.common.name.toString();
}
await this._setExtendObject(
oS,
await this._GetObjectIdPrevious(oS, TimeFrame, iBefore),
touseName,
`value.history.${TimeFrame}`,
true,
false,
oS.output_unit,
'number',
);
}
//Before Objecte die existieren aber nicht mehr aktiv sind auf diabled stellen
let theObject = await this._getObjectAsync(
oS.alias + (await this._GetObjectIdPrevious(oS, TimeFrame, iBefore)),
);
while (theObject != null) {
await this._setExtendObject(
oS,
await this._GetObjectIdPrevious(oS, TimeFrame, iBefore),
theObject.common.name.toString(),
'value.history.disabled',
false,
false,
oS.output_unit,
'number',
);
iBefore++;
theObject = await this._getObjectAsync(
oS.alias + (await this._GetObjectIdPrevious(oS, TimeFrame, iBefore)),
);
}
//CurrentYear Detailed erzeugen
const oneDateThisYear = new Date();
if (oS.detailed_current(TimeFrame)) {
for (let i = 0; i < 366; i++) {
oneDateThisYear.setDate(oneDateThisYear.getDate() - 1);
await this._CreateAndGetObjectIdDetailedCurrent(oS, TimeFrame, oneDateThisYear);
}
}
}
}
/**
* Change or Create a iobroker Object if it is necessary
*
* @param oS
* @param id
* @param name
* @param role
* @param createIfnotExists
* @param writeable
* @param writeable
* @param unit
* @param type
*/
async _setExtendObject(oS, id, name, role, createIfnotExists, writeable, unit, type) {
name = await this._replaceTimeFrameInfo(name, id);
if (!name.includes(` (${oS.alias})`)) {
name += ` (${oS.alias})`;
}
let theObject = await this._getObjectAsync(oS.alias + id);
if (
theObject == null ||
theObject.common.name != name ||
theObject.common.role != role ||
theObject.common.unit != unit ||
theObject.common.write != writeable ||
theObject.common.type != type
) {
if (createIfnotExists || theObject != null) {
if (theObject == null || theObject == undefined) {
theObject = {
type: 'state',
common: {
desc: `Created by ${this.namespace}`,
},
native: {},
};
}
theObject.type = 'state';
theObject.common.name = name;
theObject.common.role = role;
theObject.common.type = type;
theObject.common.unit = unit;
theObject.common.write = writeable;
theObject.common.read = true;
await this.setObjectAsync(oS.alias + id, theObject);
this.myObjects[oS.alias + id] = await this._getObjectAsync(oS.alias + id);
}
}
}
/**
* Replace the Timeframe info on Datapoints with variable data (previous and Current History) with static Text (reduce ObjectChanges)
*
* @param name
* @param id
*/
async _replaceTimeFrameInfo(name, id) {
if (this.writeTrimeFrameInfo == false) {
if (name.startsWith('Timeframe ') && !id.startsWith('20')) {
name = id.split('.').join(' ');
}
}
return name;
}
/**
* Change or Create a iobroker Channel if necessary
*
* @param oS
* @param id
* @param name
* @param createIfnotExists
*/
async _setExtendChannel(oS, id, name, createIfnotExists) {
name = await this._replaceTimeFrameInfo(name, id);
if (!name.includes(` (${oS.alias})`)) {
name += ` (${oS.alias})`;
}
let theObject = await this._getObjectAsync(oS.alias + id);
if (
theObject == null ||
theObject == undefined ||
theObject.common.name != name ||
theObject.type != 'channel'
) {
if (createIfnotExists || theObject != null) {
if (theObject == null || theObject == undefined) {
theObject = {
common: {
desc: `Created by ${this.namespace}`,
},
native: {},
};
}
theObject.common.name = name;
theObject.type = 'channel';
await this.setObjectAsync(oS.alias + id, theObject);
this.myObjects[oS.alias + id] = await this._getObjectAsync(oS.alias + id);
}
}
}
/**
* Build the ObjectID String for Previous Datapoints
*
* @param oS
* @param TimeFrame
* @param beforeCounter
*/
async _GetObjectIdPrevious(oS, TimeFrame, beforeCounter) {
if (oS.beforeCount(TimeFrame) > 0) {
await this._setExtendChannel(
oS,
`.${TimeFramesNumber[TimeFrame]}_previous${TimeFrame}s`,
`${TimeFrame}s Before`,
true,
);
} else {
//Channel Auf disabled setzen wenn es bereits gibt
await this._setExtendChannel(
oS,
`.${TimeFramesNumber[TimeFrame]}_previous${TimeFrame}s`,
'disabled',
false,
);
}
const theID = `.${TimeFramesNumber[TimeFrame]}_previous${TimeFrame}s.Before_${beforeCounter
.toString()
.padStart(2, '0')}_${TimeFrame}`;
return theID;
}
/**
* Build a string for DatapointName for a Previous DP
*
* @param TimeFrame
* @param theDate
* @param beforeZähler
*/
async _getDateTimeInfoForPrevious(TimeFrame, theDate, beforeZähler) {
const newdate = await this._dateChangeTimeFrame(TimeFrame, theDate, beforeZähler * -1);
return await this._getTimeFrameInfo(TimeFrame, newdate);
}
/**
* Build a string for DatapointName
*
* @param TimeFrame
* @param theDate
*/
async _getTimeFrameInfo(TimeFrame, theDate) {
let ret = '';
if (TimeFrame == TimeFrames.Minute) {
ret = `minute ${DateHelper.GetTime(theDate)}`;
} else if (TimeFrame == TimeFrames.Hour) {
ret = `hour ${DateHelper.GetTime(theDate)}`;
} else if (TimeFrame == TimeFrames.Day) {
ret = `${DateHelper.GetDateNumber(theDate)} ${DateHelper.GetMonthName(theDate)} ${theDate.getFullYear()}`;
} else if (TimeFrame == TimeFrames.Week) {
const theKW = new KWInfo(theDate);
ret = theKW.InfoString;
} else if (TimeFrame == TimeFrames.Month) {
ret = `${DateHelper.GetMonthName(theDate)} ${theDate.getFullYear()}`;
} else if (TimeFrame == TimeFrames.Quarter) {
const myquarter = await this._getQuarter(theDate);
ret = `quarter ${myquarter} `;
ret += `${DateHelper.GetMonthNamefromNumber((myquarter - 1) * 3 + 0)},`;
ret += `${DateHelper.GetMonthNamefromNumber((myquarter - 1) * 3 + 1)},`;
ret += `${DateHelper.GetMonthNamefromNumber((myquarter - 1) * 3 + 2)} `;
ret += ` ${theDate.getFullYear()}`;
} else if (TimeFrame == TimeFrames.Year) {
ret = `year ${theDate.getFullYear().toString()}`;
} else if (TimeFrame == TimeFrames.Infinite) {
ret = 'Infinite';
}
return `Timeframe ${ret}`;
}
/**
* Build a substring for ObjectID
*
* @param TimeFrame
* @param theDate
*/
async _getTimeFrameObjectID(TimeFrame, theDate) {
if (TimeFrame == TimeFrames.Minute) {
return 'not valid';
} else if (TimeFrame == TimeFrames.Hour) {
return 'not valid';
} else if (TimeFrame == TimeFrames.Day) {
return DateHelper.GetDateNumber(theDate);
} else if (TimeFrame == TimeFrames.Week) {
const theKW = new KWInfo(theDate);
return `KW${theKW.weekNumberString}`;
} else if (TimeFrame == TimeFrames.Month) {
return `${DateHelper.GetMonthNumber(theDate)}_${DateHelper.GetMonthName(theDate)}`;
} else if (TimeFrame == TimeFrames.Quarter) {
return `quater_${await this._getQuarter(theDate)}`;
} else if (TimeFrame == TimeFrames.Year) {
return `${TimeFramesNumber.Year}_Year_${theDate.getFullYear()}`;
} else if (TimeFrame == TimeFrames.Infinite) {
return `${TimeFramesNumber.Year}_Infinite`;
}
return '';
}
/**
* Create and Fill Detailed Datapoints (Current year and Detailed)
*
* @param oS
* @param TimeFrame
* @param date
* @param TimeFrame_value
*/
async _CreateAndSetObjectIdDetailed(oS, TimeFrame, date, TimeFrame_value) {
const a = await this._CreateAndGetObjectIdDetailed(oS, TimeFrame, date);
if (a) {
await this._setStateRoundedAsync(oS, a, TimeFrame_value, true);
}
const b = await this._CreateAndGetObjectIdDetailedCurrent(oS, TimeFrame, date);
if (b) {
await this._setStateRoundedAsync(oS, b, TimeFrame_value, true);
}
}
/**
* Creates the needed TreeStructure and returns the Id after alias-name
*
* @param oS
* @param TimeFrame
* @param date
*/
async _CreateAndGetObjectIdDetailed(oS, TimeFrame, date) {
if (oS.detailed(TimeFrame)) {
let mydetailedObjectId = '';
mydetailedObjectId = `.${date.getFullYear()}`;
await this._setExtendChannel(oS, mydetailedObjectId, String(date.getFullYear()), true);
if (TimeFrame == TimeFrames.Infinite) {
//nothing to do
} else if (TimeFrame == TimeFrames.Year) {
mydetailedObjectId = `${mydetailedObjectId}.${await this._getTimeFrameObjectID(TimeFrames.Year, date)}`;
await this._setExtendObject(
oS,
mydetailedObjectId,
await this._getTimeFrameInfo(TimeFrames.Year, date),
`value.history.${TimeFrame}`,
true,
false,
oS.output_unit,
'number',
);
} else {
mydetailedObjectId = `${mydetailedObjectId}.${TimeFramesNumber[TimeFrame]}_${TimeFrame}s`;
await this._setExtendChannel(oS, mydetailedObjectId, `${TimeFrame}s`, true);
if (TimeFrame == TimeFrames.Day) {
mydetailedObjectId = `${mydetailedObjectId}.${await this._getTimeFrameObjectID(TimeFrames.Month, date)}`;
await this._setExtendChannel(
oS,
mydetailedObjectId,
await this._getTimeFrameInfo(TimeFrames.Month, date),
true,
);
mydetailedObjectId = `${mydetailedObjectId}.${await this._getTimeFrameObjectID(TimeFrames.Day, date)}`;
await this._setExtendObject(
oS,
mydetailedObjectId,
await this._getTimeFrameInfo(TimeFrames.Day, date),
`value.history.${TimeFrame}`,
true,
false,
oS.output_unit,
'number',
);
}
if (TimeFrame == TimeFrames.Week) {
const theKWInfo = new KWInfo(date);
if (date.getFullYear() != theKWInfo.yearOfThursday) {
mydetailedObjectId.replace(date.getFullYear().toString(), theKWInfo.yearOfThursday.toString());
}
mydetailedObjectId = `${mydetailedObjectId}.${await this._getTimeFrameObjectID(TimeFrames.Week, date)}`;
await this._setExtendObject(
oS,
mydetailedObjectId,
await this._getTimeFrameInfo(TimeFrames.Week, date),
`value.history.${TimeFrame}`,
true,
false,
oS.output_unit,
'number',
);
}
if (TimeFrame == TimeFrames.Month) {
mydetailedObjectId = `${mydetailedObjectId}.${await this._getTimeFrameObjectID(TimeFrames.Month, date)}`;
await this._setExtendObject(
oS,
mydetailedObjectId,
await this._getTimeFrameInfo(TimeFrames.Month, date),
`value.history.${TimeFrame}`,
true,
false,
oS.output_unit,
'number',
);
}
if (TimeFrame == TimeFrames.Quarter) {
mydetailedObjectId = `${mydetailedObjectId}.${await this._getTimeFrameObjectID(TimeFrames.Quarter, date)}`;
await this._setExtendObject(
oS,
mydetailedObjectId,
await this._getTimeFrameInfo(TimeFrames.Quarter, date),
`value.history.${TimeFrame}`,
true,
false,
oS.output_unit,
'number',
);
}
}
return mydetailedObjectId;
}
return null;
}
/**
* Creates the needed TreeStructure and returns the Id after alias-name
*
* @param TimeFrame
* @param date
*/
async _getTimeFrameBeginn(TimeFrame, date) {
const Checkdate = new Date(date);
Checkdate.setMilliseconds(0);
Checkdate.setSeconds(0);
if (TimeFrame == TimeFrames.Minute) {
return Checkdate;
}
Checkdate.setMinutes(0);
if (TimeFrame == TimeFrames.Hour) {
return Checkdate;
}
Checkdate.setHours(0);
if (TimeFrame == TimeFrames.Day) {
return Checkdate;
}
if (TimeFrame == TimeFrames.Week) {
Checkdate.setDate(Checkdate.getDate() - (Checkdate.getDay() == 0 ? 6 : Checkdate.getDay() - 1));
return Checkdate;
}
Checkdate.setDate(1);
if (TimeFrame == TimeFrames.Month) {
return Checkdate;
}
if (TimeFrame == TimeFrames.Quarter) {
Checkdate.setMonth(Checkdate.getMonth() - (Checkdate.getMonth() % 3));
return Checkdate;
}
Checkdate.setMonth(0);
if (TimeFrame == TimeFrames.Year) {
return Checkdate;
}
Checkdate.setFullYear(1990);
if (TimeFrame == TimeFrames.Infinite) {
return Checkdate;
}
return Checkdate;
}
/**
* Creates the needed TreeStructure and returns the Id after alias-name, returns null if date not should write in current
*
* @param oS
* @param TimeFrame
* @param date
*/
async _CreateAndGetObjectIdDetailedCurrent(oS, TimeFrame, date) {
if (oS.detailed_current(TimeFrame)) {
let mydetailedObjectId = '';
let endOfTimeFrame = await this._getTimeFrameBeginn(TimeFrame, new Date());
endOfTimeFrame = await this._dateChangeTimeFrame(TimeFrame, endOfTimeFrame, 1);
endOfTimeFrame.setMilliseconds(-1);
const currentDataRelevantBegin = new Date(endOfTimeFrame);
if (TimeFrame != TimeFrames.Year) {
mydetailedObjectId = `${mydetailedObjectId}.${TimeFramesNumber[TimeFrame]}_${TimeFrame}s`;
await this._setExtendChannel(oS, mydetailedObjectId, `${TimeFrame}s`, true);
if (TimeFrame == TimeFrames.Day) {
if (date >= (await this._dateChangeTimeFrame(TimeFrames.Day, endOfTimeFrame, -7))) {
let myDayNumber = date.getDay();
if (myDayNumber == 0) {
myDayNumber = 7;
}
mydetailedObjectId = `${mydetailedObjectId}.${myDayNumber}_${days[date.getDay()]}`;
await this._setExtendObject(
oS,
mydetailedObjectId,
await this._getTimeFrameInfo(TimeFrames.Day, date),
`value.currenthistory.${TimeFrame}`,
true,
false,
oS.output_unit,
'number',
);
return mydetailedObjectId;
}
}
if (TimeFrame == TimeFrames.Week) {
currentDataRelevantBegin.setFullYear(currentDataRelevantBegin.getFullYear() - 1);
if (date >= currentDataRelevantBegin) {
{
mydetailedObjectId = `${mydetailedObjectId}.${await this._getTimeFrameObjectID(TimeFrames.Week, date)}`;
await this._setExtendObject(
oS,
mydetailedObjectId,
await this._getTimeFrameInfo(TimeFrames.Week, date),
`value.currenthistory.${TimeFrame}`,
true,
false,
oS.output_unit,
'number',
);
return mydetailedObjectId;
}
}
}