-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.js
1694 lines (1507 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 v2.3.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 fs = require('fs');
const path = require('path');
const systemDictionary = require('./lib/dictionary.js');
let instanceDir;
const backupDir = '/backup';
/* Variables for runtime */
let globalConfig = {};
let sourceObject = {};
let settingsObj = {};
let rawValues = {};
let outputValues = {
values: {},
unit: {},
animations: {},
fillValues: {},
borderValues: {},
prepend: {},
append: {},
css: {},
override: {},
img_href: {}
};
let relativeTimeCheck = {};
let globalInterval;
let subscribeArray = new Array();
let _this;
let systemLang = 'en';
class EnergieflussErweitert extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'energiefluss-erweitert',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
// this.on('objectChange', this.onObjectChange.bind(this));
this.on('message', this.onMessage.bind(this));
this.on('unload', this.onUnload.bind(this));
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Initialize your adapter here
_this = this;
/* Create Adapter Directory - Backup */
instanceDir = utils.getAbsoluteInstanceDataDir(this);
if (!fs.existsSync(instanceDir + backupDir)) {
fs.mkdirSync(instanceDir + backupDir, { recursive: true });
}
/* Check, if we have an old backup state */
let tmpBackupState = await this.getStateAsync('backup');
if (tmpBackupState) {
let tmpBackup = JSON.parse(tmpBackupState.val);
this.log.info('Migrating old backup to new strategy. Please wait!');
if (Object.keys(tmpBackup).length > 0) {
this.log.info(`${Object.keys(tmpBackup).length} Backup's found. Converting!`);
for (var key of Object.keys(tmpBackup)) {
let datetime = key;
let [date, time] = datetime.split(', ');
let [day, month, year] = date.split('.');
let [hour, minutes, seconds] = time.split(':');
let fileName = new Date(year, month - 1, day, hour, minutes, seconds).getTime();
const newFilePath = path.join(instanceDir + backupDir, `BACKUP_${fileName}.json`);
fs.writeFile(newFilePath, JSON.stringify(tmpBackup[key]), (err) => {
if (err) {
this.log.error(`Could not create Backup ${newFilePath}. Error: ${err}`);
}
});
}
}
// After creation of new backup - delete the state
this.log.info('Convertion of backups finished');
}
// Get language of ioBroker
this.getForeignObjectAsync('system.config', function (err, obj) {
if (err) {
_this.log.warn('Could not get language of ioBroker! Using english instead!');
} else {
systemLang = obj.common.language;
_this.log.debug(`Using language: ${systemLang}`);
}
});
// Delete old Objects
this.delObjectAsync('backup');
this.delObjectAsync('battery_remaining');
this.log.info('Adapter started. Loading config!');
this.getConfig();
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
// Here you must clear all timeouts or intervals that may still be active
this.clearInterval(globalInterval);
this.log.info('Cleared interval for relative values!');
callback();
} catch (e) {
callback();
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state) {
// The state was changed
if (id && state) {
// The state is acknowledged
if (state.ack) {
this.log.debug('Refreshing ACK state from foreign state!');
await this.refreshData(id, state);
}
// For userdata and Javascript
if (id.toLowerCase().startsWith('0_userdata.') || id.toLowerCase().startsWith('javascript.') || id.toLowerCase().startsWith('alias.')) {
this.log.debug(`Refreshing state from user environment! ${id}`);
await this.refreshData(id, state);
}
}
}
/**
* Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
* Using this method requires "common.messagebox" property to be set to true in io-package.json
* @param {ioBroker.Message} obj
*/
async onMessage(obj) {
//this.log.debug(`[onMessage] received command: ${obj.command} with message: ${JSON.stringify(obj.message)}`);
if (obj && obj.message) {
if (typeof obj.message === 'object') {
// Request the list of Backups
let fileList = [];
switch (obj.command) {
case '_getBackups':
const listBackups = path.join(instanceDir + backupDir)
fs.readdir(listBackups, (err, files) => {
if (err) {
this.sendTo(obj.from, obj.command, { err }, obj.callback);
} else {
files.forEach(file => {
let tmpFile = path.parse(file).name;
tmpFile = tmpFile.replace('BACKUP_', '');
fileList.push(tmpFile);
});
this.sendTo(obj.from, obj.command, { error: null, data: fileList }, obj.callback);
}
});
break;
case '_restoreBackup':
// Restore Backup
this.log.info('Starting restoring Backup from disk!');
const restorePath = path.join(instanceDir + backupDir, `BACKUP_${obj.message.filename}.json`);
fs.readFile(restorePath, 'utf8', (err, data) => {
if (err) {
this.log.info(`Error during ${err}`);
this.sendTo(obj.from, obj.command, { error: err }, obj.callback);
} else {
// Send new config back to workspace and store in state
this.setStateChangedAsync('configuration', { val: data, ack: true });
this.sendTo(obj.from, obj.command, { error: null, data: JSON.parse(data) }, obj.callback);
this.log.info('Backup restored and activated!');
}
});
break;
case '_saveConfiguration':
// Store Backup
this.log.debug('Saving Backup to disk!');
const filename = new Date().getTime();
const storePath = path.join(instanceDir + backupDir, `BACKUP_${filename}.json`);
// Get current configuration
const tmpConfig = await this.getStateAsync('configuration');
fs.writeFile(storePath, tmpConfig.val, (err) => {
if (err) {
this.sendTo(obj.from, obj.command, { err }, obj.callback);
} else {
this.sendTo(obj.from, obj.command, { error: null, data: 'Backup stored successfully!' }, obj.callback);
}
});
// Store the new configuration in state
await this.setStateChangedAsync('configuration', { val: JSON.stringify(obj.message), ack: true });
// Recycle old Backups
fileList = [];
fs.readdir(instanceDir + backupDir, (err, files) => {
if (!err) {
files.forEach(file => {
fileList.push(file);
});
// Walk through the list an delete all files after index 9
if (fileList.length > 10) {
// Order the List
fileList.sort((a, b) => -1 * a.localeCompare(b));
for (let i = 10; i < fileList.length; i++) {
fs.unlink(`${instanceDir}${backupDir}/${fileList[i]}`, (err) => {
if (err) {
this.log.warn(err);
}
this.log.info(`${fileList[i]} successfully deleted!`);
});
}
} else {
this.log.info('The amount of current stored backups does not exceed the number of 10!');
}
}
});
break;
case '_updateElementInView':
// Receive Object from ioBroker to show it in Configuration
const originID = obj.message.id;
const id = `tmp_${originID}`;
const originSource = obj.message.source;
const state = await this.getForeignStateAsync(originSource);
let objectUnit = '';
rawValues[id] = state.val;
// Modify the source
obj.message.source = id;
if (state) {
// Get the type if auto
if (obj.message.source_display == 'auto') {
const type = await this.getForeignObjectAsync(originSource);
obj.message.source_type = type.common.type;
objectUnit = type.common.unit;
}
await this.calculateValue(id, obj.message, state);
this.log.debug(`Found ${obj.message.source} and calculated the value for Web-ID: ${id}!`);
if (outputValues.values.hasOwnProperty(id)) {
let returnObj = {
values: {},
unit: {},
override: {}
}
returnObj.values[originID] = outputValues.values[id];
returnObj.unit[originID] = objectUnit;
returnObj.override[originID] = outputValues.override[id];
this.sendTo(obj.from, obj.command, {
error: null,
data: returnObj
}, obj.callback);
// Delete temporary values
delete outputValues.override[id];
delete outputValues.values[id];
delete rawValues[id];
} else {
this.sendTo(obj.from, obj.command, { error: 'There was an error, while getting the updated value!' }, obj.callback);
}
}
break;
default:
this.log.warn(`[onMessage] Received command "${obj.command}" via 'sendTo', which is not implemented!`);
this.sendTo(obj.from, obj.command, { error: `Received command "${obj.command}" via 'sendTo', which is not implemented!` }, obj.callback);
break;
}
} else {
this.log.error(`[onMessage] Received incomplete message via 'sendTo'`);
if (obj.callback) {
this.sendTo(obj.from, obj.command, { error: 'Incomplete message' }, obj.callback);
}
}
}
}
/**
* Converts minutes to a string representation of hours and minutes.
*
* @param {number} mins - The number of minutes to convert.
* @return {string} The string representation of the hours and minutes.
*/
getMinHours(mins) {
const m = mins % 60;
const h = (mins - m) / 60;
return (h < 10 ? '0' : '') + h.toString() + ':' + (m < 10 ? '0' : '') + m.toString();
}
/**
*
* @param {string} id
* @param {object} obj
* @param {object} state
*/
async calculateValue(id, obj, state /* value */) {
this.log.debug(`Values for: ${id} - Using source: ${obj.source} rawValue: ${rawValues[obj.source]} Settings: ${JSON.stringify(obj)}`);
let sourceValue = globalConfig.datasources[obj.source] ? rawValues[obj.source] * globalConfig.datasources[obj.source].factor : rawValues[obj.source];
// Decide, which type we have
switch (obj.type) {
case 'image':
// Check, if we have a static picture or one via state
if (obj.href) {
let tmpImg = await this.getForeignStateAsync(obj.href);
outputValues.img_href[id] = tmpImg.val || '#';
this.log.debug(`Loading Image for ${id} with: ${JSON.stringify(obj)} Result: ${outputValues.img_href[id]}`);
}
break;
case 'circle':
case 'rect':
// Element is not Text - It is Rect or Circle
if (obj.fill_type != -1 && obj.fill_type) {
outputValues.fillValues[id] = sourceValue;
}
if (obj.border_type != -1 && obj.border_type) {
outputValues.borderValues[id] = sourceValue;
}
break;
case 'text':
if (obj.source_option != -1 || obj.source_option_lc != -1) {
let timeStamp;
if (obj.source_option != -1) {
this.log.debug(`Source Option 'last update' detected! ${obj.source_option} Generating DateString for ${state.ts} ${this.getTimeStamp(state.ts, obj.source_option)}`);
timeStamp = this.getTimeStamp(state.ts, obj.source_option);
}
if (obj.source_option_lc != -1) {
this.log.debug(`Source Option 'last change' detected! ${obj.source_option_lc} Generating DateString for ${state.lc} ${this.getTimeStamp(state.lc, obj.source_option_lc)}`);
timeStamp = this.getTimeStamp(state.lc, obj.source_option_lc);
}
outputValues.values[id] = timeStamp;
} else {
const checkDisplay = async (method) => {
switch (method) {
case 'auto':
switch (obj.source_type) {
case 'boolean':
checkDisplay('bool');
break;
case 'number':
checkDisplay('');
break;
case 'string':
checkDisplay('text');
break;
}
break;
case 'text':
// Linebreak Option
let strOutput;
if (obj.linebreak > 0 && state.val && state.val.length > 0) {
let splitOpt = new RegExp(`.{0,${obj.linebreak}}(?:\\s|$)`, 'g');
let splitted = state.val.toString().match(splitOpt);
strOutput = splitted.join('<br>');
} else {
strOutput = state.val;
}
outputValues.values[id] = strOutput;
sourceValue = strOutput;
break;
case 'bool':
outputValues.values[id] = sourceValue ? systemDictionary['on'][systemLang] : systemDictionary['off'][systemLang];
break;
case 'own_text':
outputValues.values[id] = obj.text;
break;
default:
// Threshold need to be positive
if (obj.threshold >= 0) {
this.log.debug(`Threshold for: ${id} is: ${obj.threshold}`);
// Check, if we have Subtractions for this value
const subArray = obj.subtract;
let subValue = 0;
if (Array.isArray(subArray) && subArray.length > 0 && subArray[0] != -1) {
subValue = subArray.reduce((acc, idx) => acc - (rawValues[idx] * globalConfig.datasources[idx].factor || 0), 0);
this.log.debug(`Subtracted by: ${subArray.toString()}`);
// Set the subtraction state
await this.setStateChangedAsync(`calculation.elements.element_${id}.subtract`, { val: Number(sourceValue) + Number(subValue), ack: true });
}
// Check, if we have Additions for this value
const addArray = obj.add;
let addValue = 0;
if (Array.isArray(addArray) && addArray.length > 0 && addArray[0] != -1) {
addValue = addArray.reduce((acc, idx) => acc + (rawValues[idx] * globalConfig.datasources[idx].factor || 0), 0);
this.log.debug(`Added to Value: ${addArray.toString()}`);
// Set the addition state
await this.setStateChangedAsync(`calculation.elements.element_${id}.addition`, { val: Number(sourceValue) + Number(addValue), ack: true });
}
let formatValue = (Number(sourceValue) + Number(subValue) + Number(addValue));
// Check if value is over threshold
if (Math.abs(formatValue) >= obj.threshold) {
// Convert Value to positive
let cValue = obj.convert ? Math.abs(formatValue) : formatValue;
// Calculation
switch (obj.calculate_kw) {
case 'calc':
case true:
// Convert to kW if set
cValue = (Math.round((cValue / 1000) * 100) / 100);
break;
case 'auto':
if (Math.abs(cValue) >= 1000000000) {
outputValues.unit[id] = 'GW';
// Convert to GW if set
cValue = (Math.round((cValue / 1000000000) * 100) / 100);
} else if (Math.abs(cValue) >= 1000000) {
outputValues.unit[id] = 'MW';
// Convert to MW if set
cValue = (Math.round((cValue / 1000000) * 100) / 100);
} else if (Math.abs(cValue) >= 1000) {
outputValues.unit[id] = 'kW';
// Convert to kW if set
cValue = (Math.round((cValue / 1000) * 100) / 100);
} else {
outputValues.unit[id] = 'W';
}
break;
case 'none':
case false:
break;
default:
cValue = cValue;
break;
}
outputValues.values[id] = obj.decimal_places >= 0 ? this.decimalPlaces(cValue, obj.decimal_places) : cValue;
} else {
outputValues.values[id] = obj.decimal_places >= 0 ? this.decimalPlaces(0, obj.decimal_places) : sourceValue;
}
}
break;
}
};
checkDisplay(obj.source_display);
}
break;
}
// Overrides for elements
if (obj.override) {
this.log.debug(`Gathering override for ID: ${id}, Processed-value: ${sourceValue}, Raw-value: ${rawValues[obj.source]}, Override: ${JSON.stringify(obj.override)}`);
outputValues.override[id] = await this.getOverridesAsync(sourceValue, obj.override);
}
}
/**
* Converts a duration in milliseconds to a human-readable time string.
*
* @param {number} duration - The duration in milliseconds.
* @return {string} The human-readable time string.
*/
msToTime(duration) {
const seconds = Math.floor((duration / 1000) % 60);
const minutes = Math.floor((duration / (1000 * 60)) % 60);
const hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
let value = systemDictionary['timer_now'][systemLang];
if (hours > 0) {
if (hours < 5 && hours >= 2) {
value = systemDictionary['timer_few_hours'][systemLang];;
} else if (hours == 1) {
value = this.sprintf(systemDictionary['timer_hour_ago'][systemLang], hours);
} else {
value = this.sprintf(systemDictionary['timer_hours_ago'][systemLang], hours);
}
return value;
}
if (minutes > 0) {
if (minutes < 5 && minutes >= 2) {
value = systemDictionary['timer_few_minutes'][systemLang];
} else if (minutes == 1) {
value = this.sprintf(systemDictionary['timer_minute_ago'][systemLang], minutes);
} else {
value = this.sprintf(systemDictionary['timer_minutes_ago'][systemLang], minutes);
}
return value;
}
if (seconds > 0) {
if (seconds < 5 && seconds >= 2) {
value = systemDictionary['timer_few_seconds'][systemLang];
} else if (seconds == 1) {
value = this.sprintf(systemDictionary['timer_second_ago'][systemLang], seconds);
} else {
value = this.sprintf(systemDictionary['timer_seconds_ago'][systemLang], seconds);
}
}
return value;
}
/**
* Replaces occurrences of `%s` in the given format string with the corresponding
* elements from the arguments array.
*
* @param {string} format - The format string with `%s` placeholders.
* @return {string} The formatted string with placeholders replaced by the corresponding values.
*/
sprintf(format) {
var args = Array.prototype.slice.call(arguments, 1);
var i = 0;
return format.replace(/%s/g, function () {
return args[i++];
});
}
/**
* Returns a formatted timestamp based on the given mode.
*
* @param {number} ts - The timestamp in milliseconds.
* @param {string} mode - The mode to determine the format of the timestamp.
* @return {string} The formatted timestamp.
*/
getTimeStamp(ts, mode) {
if (!ts || ts <= 0) {
return '';
}
const date = new Date(ts);
switch (mode) {
case 'timestamp_de':
default:
return date.toLocaleString('de-DE', {
hour: 'numeric',
minute: 'numeric',
day: '2-digit',
month: '2-digit',
year: 'numeric',
second: '2-digit',
hour12: false
});
case 'timestamp_de_short':
return date.toLocaleString('de-DE', {
hour: '2-digit',
minute: '2-digit',
day: '2-digit',
month: '2-digit',
year: '2-digit',
hour12: false
});
case 'timestamp_de_short_wo_year':
return date.toLocaleString('de-DE', {
hour: '2-digit',
minute: '2-digit',
day: '2-digit',
month: '2-digit',
hour12: false
});
case 'timestamp_de_hhmm':
return date.toLocaleString('de-DE', {
hour: '2-digit',
minute: '2-digit'
});
case 'timestamp_us':
return date.toLocaleString('en-US', {
hour: 'numeric',
minute: 'numeric',
day: '2-digit',
month: '2-digit',
year: 'numeric',
second: '2-digit',
hour12: true
});
case 'timestamp_us_short':
return date.toLocaleString('en-US', {
hour: '2-digit',
minute: '2-digit',
day: '2-digit',
month: '2-digit',
year: '2-digit',
hour12: true
});
case 'timestamp_us_short_wo_year':
return date.toLocaleString('en-US', {
hour: '2-digit',
minute: '2-digit',
day: '2-digit',
month: '2-digit',
hour12: true
});
case 'timestamp_us_hhmm':
return date.toLocaleString('de-DE', {
hour: '2-digit',
minute: '2-digit',
hour12: true
});
case 'relative':
const now = new Date();
return this.msToTime(now - date);
case 'ms':
return ts;
}
}
/**
* Convert a timestamp to datetime.
*
* @param {number} ts Timestamp to be converted to date-time format (in ms)
*
*/
getDateTime(ts) {
if (!ts || ts <= 0) {
return '';
}
const date = new Date(ts);
let day = '0' + date.getDate();
let month = '0' + (date.getMonth() + 1);
let year = date.getFullYear();
let hours = '0' + date.getHours();
let minutes = '0' + date.getMinutes();
let seconds = '0' + date.getSeconds();
return day.substr(-2) + '.' + month.substr(-2) + '.' + year + ' ' + hours.substr(-2) + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
}
/**
* Asynchronously retrieves the relative time objects for the given object.
*
* @param {Object} obj - The object containing the keys and their corresponding source and option properties.
* @return {Promise<void>} A promise that resolves once all relative time objects have been retrieved and assigned.
*/
async getRelativeTimeObjects(obj) {
const keys = Object.keys(obj);
const promises = keys.map(async (key) => {
const stateValue = await this.getForeignStateAsync(obj[key].source);
if (stateValue) {
outputValues.values[key] = this.getTimeStamp(stateValue.ts, obj[key].option);
}
});
await Promise.all(promises);
}
/**
* Returns a string representation of a number with the specified number of decimal places.
*
* @param {number} value - The number to be converted to a string.
* @param {number} decimal_places - The number of decimal places to include in the string representation.
* @return {string} A string representation of the number with the specified number of decimal places.
*/
decimalPlaces(value, decimal_places) {
return Number(value).toFixed(decimal_places);
}
/**
* Calculates the duration based on the maximum duration, maximum power, and current power.
*
* @param {number} maxDuration - The maximum duration.
* @param {number} maxPower - The maximum power.
* @param {number} currentPower - The current power.
* @return {number} The calculated duration, limited to a maximum of 60000.
*/
calculateDuration(maxDuration, maxPower, currentPower) {
// Max Duration
let cur = Number(currentPower);
let max = Number(maxPower);
let dur = Number(maxDuration);
// Calculate the result and limit it to 60000 if necessary
return Math.min(Math.round((max / cur) * dur), 60000);
}
/**
* Calculates the stroke dash array for an SVG path element based on the maximum number of dots, maximum power, and current power.
*
* @param {number} maxDots - The maximum number of dots to be drawn.
* @param {number} maxPower - The maximum power.
* @param {number} currentPower - The current power.
* @return {string} The stroke dash array for the SVG path element.
*/
calculateStrokeArray(maxDots, maxPower, currentPower) {
const totalLength = 136;
const l_distance = globalConfig.animation_configuration.distance;
const l_length = globalConfig.animation_configuration.length;
// Calculate the number of dots to be drawn
let l_amount = Math.round(((currentPower / maxPower) * maxDots));
l_amount = Math.min(l_amount, maxDots);
// Initialize stroke dash array
let strokeDash = '';
let total = totalLength;
if (l_amount > 0 && l_length > 0 && l_distance > 0) {
for (let i = 0; i < l_amount; i++) {
strokeDash += `${l_length} `;
if (i !== l_amount - 1) {
strokeDash += `${l_distance} `;
total -= l_distance;
}
total -= l_length;
}
strokeDash += ` ${total < 0 ? l_distance : total}`;
} else {
strokeDash = `${l_length} ${totalLength - l_length}`;
}
return strokeDash;
}
/**
*
* @param {number} condValue
* @param {object} obj
* @returns {Promise} tmpWorker
*/
async getOverridesAsync(condValue, obj) {
return new Promise(async (resolve) => {
let tmpWorker = {};
const workObj = typeof (obj) === 'string' ? JSON.parse(obj) : JSON.parse(JSON.stringify(obj));
if (workObj.hasOwnProperty(condValue)) {
// Check, if Property exists - if yes, directly return it, because thats the best match
tmpWorker = workObj[condValue];
} else {
// Property not found. We need to check the values!
const operators = new RegExp('[=><!]');
Object.keys(workObj)
.sort(
(a, b) => a.toLowerCase().localeCompare(b.toLowerCase(), undefined, { numeric: true, sensitivity: 'base' }))
.forEach((item) => {
if (operators.test(item)) {
// Now, we need to check, if condValue is a number
if (!isNaN(condValue)) {
// Operator found - check for condition
try {
const func = Function(`return ${condValue}${item} `)();
if (func) {
tmpWorker = workObj[item];
}
}
catch (func) {
tmpWorker.error = {
status: false,
error: func.toString(),
function: condValue + item
}
}
}
}
});
}
if (Object.keys(tmpWorker).length == 0) {
// Check, if we have a default fallback for it
if (workObj.hasOwnProperty('default')) {
tmpWorker = workObj['default'];
}
}
// Now we process the found values inside tmpWorker Obj
if (Object.keys(tmpWorker).length > 0) {
for (var item of Object.keys(tmpWorker)) {
// Temp Storage of workerValue
let itemToWorkWith = tmpWorker[item];
// Check if we are not destroying the error object
if (typeof itemToWorkWith != 'object') {
itemToWorkWith = itemToWorkWith.toString();
const dp_regex = /{([^}]+)}/g;
const foundDPS = [...itemToWorkWith.matchAll(dp_regex)];
if (foundDPS.length > 0) {
for (const match of foundDPS) {
// Check, if match contains min. 2 dots - then its a state
const checkForState = match[1].match(/\./g);
if (checkForState != null && checkForState.length >= 2) {
const state = await this.getForeignStateAsync(match[1]);
if (state) {
if (state.val) {
itemToWorkWith = itemToWorkWith.replace(match[0], state.val);
}
}
}
}
}
try {
const func = new Function(`return ${itemToWorkWith} `)();
tmpWorker[item] = func(condValue);
}
catch (func) {
if (itemToWorkWith.includes('=>')) {
tmpWorker[item] = {
status: false,
error: func.toString(),
function: itemToWorkWith
}
} else {
tmpWorker[item] = itemToWorkWith;
}
}
}
}
}
resolve(tmpWorker);
});
}
/**
* @param {string} id ID of the state
* @param {object} state State itself
*/
async refreshData(id, state) {
if (id == this.namespace + '.configuration') {
this.log.info('Configuration changed via Workspace! Reloading config!');
this.getConfig();
} else {
let cssRules = new Array();
// Check, if we handle this source inside our subscribtion
if (sourceObject.hasOwnProperty(id)) {
// sourceObject for this state-id
const soObj = sourceObject[id];
// Number for calculation
const stateValue = state.val;
const calcNumber = (typeof (state.val) === 'string' ? Number(state.val.replace(/[^\d.-]/g, '')) : state.val) * soObj.factor;
// Check, if the value has been updated - if not, dont refresh it
this.log.debug(`Current Value of ${id}: ${stateValue} - saved Value: ${rawValues[soObj.id]}`);
if (stateValue == rawValues[soObj.id]) {
this.log.debug(`Value of ${id} did not change. Ignoring!`);
} else {
this.log.debug(`Value of ${id} changed! Old Value: ${rawValues[soObj.id]} | New Value: ${stateValue} Processing!`);
// Put Value into RAW-Source-Values
rawValues[soObj.id] = stateValue;
// Runner for calculating the values
const sourceRunner = async (what) => {
this.log.debug(`Updated through ${what}: ${JSON.stringify(rawValues)}`);
// Run through the provided object
for (const key of Object.keys(soObj[what])) {
const elmID = soObj[what][key];
if (what == 'elmSources') {
// Put ID into CSS-Rule for later use
cssRules.push(elmID);
}
if (settingsObj.hasOwnProperty(elmID)) {
this.log.debug(`Value-Settings for Element ${elmID} found! Applying Settings!`);
await this.calculateValue(elmID, settingsObj[elmID], state);
}
}
};
// Loop through each addSource
if (soObj.hasOwnProperty('addSources') && soObj['addSources'].length) {
await sourceRunner('addSources');
}
// Loop through each subtractSource
if (soObj.hasOwnProperty('subtractSources') && soObj['subtractSources'].length) {
await sourceRunner('subtractSources');
}
// Loop through each Element, which belongs to that source
if (soObj.hasOwnProperty('elmSources') && soObj['elmSources'].length) {
await sourceRunner('elmSources');
}
// Check, if that Source belongs to battery-charge or discharge, to determine the time
if (globalConfig.hasOwnProperty('calculation')) {
// Check, if the provided source is a valid source
const isValidDatasource = (value) => {
if (value === null || value === undefined || value === '') {
return false;
}
// Check, if value is type 'number'
if (typeof value !== 'number') {
return false;
}
// Check, if value is greater than or equal 0 ist
return !isNaN(value) && Number(value) >= 0;
};
// Battery Remaining
if (globalConfig.calculation.hasOwnProperty('battery')) {
const batObj = globalConfig.calculation.battery;
const isRelevantId = soObj.id == batObj.charge || soObj.id == batObj.discharge;
if (isRelevantId && isValidDatasource(batObj.charge) && isValidDatasource(batObj.discharge) && isValidDatasource(batObj.percent)) {
let direction = 'none';
let energy = 0;
const batteryValue = Math.abs(calcNumber);
const setDirectionAndEnergy = (dir, en) => {
direction = dir;
energy = en;
};
if (batObj.charge !== batObj.discharge) {
if (soObj.id === batObj.charge) {
setDirectionAndEnergy('charge', batteryValue);
}
if (soObj.id === batObj.discharge) {
setDirectionAndEnergy('discharge', batteryValue);
}
} else {
if (calcNumber > 0) {
if (!batObj.charge_prop) {
setDirectionAndEnergy('charge', batteryValue);
}
if (!batObj.discharge_prop) {
setDirectionAndEnergy('discharge', batteryValue);
}
} else if (calcNumber < 0) {
if (batObj.charge_prop) {
setDirectionAndEnergy('charge', batteryValue);
}
if (batObj.discharge_prop) {
setDirectionAndEnergy('discharge', batteryValue);
}
}
}
// Calculate the rest time of the battery
this.getForeignStateAsync(globalConfig.datasources[batObj.percent].source).then(state => {
const capacity = isValidDatasource(batObj.capacity) ? rawValues[batObj.capacity] * globalConfig.datasources[batObj.capacity].factor : 0;
const dod = isValidDatasource(batObj.dod) ? rawValues[batObj.dod] * globalConfig.datasources[batObj.dod].factor : 0;
const percent = state.val;
let rest = 0;
let mins = 0;
let string = '--:--h';
let target = 0;
const batt_energy = (capacity * (percent - dod)) / 100 || 0;
if (percent > 0 && energy > 0) {
if (direction === 'charge') {
rest = capacity - ((capacity * percent) / 100);
} else if (direction === 'discharge') {
rest = (capacity * (percent - dod)) / 100;
}
mins = Math.round((rest / energy) * 60);
if (mins > 0) {
string = this.getMinHours(mins) + 'h';
target = Math.floor(Date.now() / 1000) + (mins * 60);
}
}
this.log.debug(`Direction: ${direction} Time to fully ${direction}: ${string} Percent: ${percent} Energy: ${energy} Rest Energy to ${direction}: ${rest} DoD: ${dod}`);
// Set the states
this.setStateChangedAsync('calculation.battery.remaining_energy', { val: batt_energy, ack: true });
this.setStateChangedAsync('calculation.battery.remaining', { val: string, ack: true });
this.setStateChangedAsync('calculation.battery.remaining_target', { val: target, ack: true });