-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.js
1399 lines (1062 loc) · 46.4 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
/*
* ebus adapter für iobroker
*
* Created: 15.09.2016 21:31:28
* Author: Rene
*/
/* jshint -W097 */// jshint strict:false
/*jslint node: true */
"use strict";
const utils = require("@iobroker/adapter-core");
const ebusdMinVersion = [24, 1];
const ebusdVersion = [0, 0];
const ebusdUpdateVersion = [0, 0];
let adapter;
function startAdapter(options) {
options = options || {};
Object.assign(options, {
name: "ebus",
//#######################################
//
ready: function () {
try {
//adapter.log.debug('start');
main();
}
catch (e) {
adapter.log.error("exception catch after ready [" + e + "]");
}
},
//#######################################
// is called when adapter shuts down
unload: function (callback) {
try {
if (intervalID != null) {
clearInterval(intervalID);
}
if (updateTimerID != null) {
clearTimeout(updateTimerID);
}
adapter && adapter.log && adapter.log.info && adapter.log.info("cleaned everything up...");
//to do stop intervall
callback();
} catch (e) {
callback();
}
},
stateChange: async (id, state) => {
await HandleStateChange(id, state);
},
//#######################################
//
message: async (obj) => {
if (obj) {
switch (obj.command) {
case "findParams":
// e.g. send email or pushover or whatever
//adapter.log.debug("findParams command");
// Send response in callback if required
await FindParams(obj);
break;
default:
adapter.log.error("unknown message " + obj.command);
break;
}
}
}
//#######################################
//
});
adapter = new utils.Adapter(options);
return adapter;
}
const axios = require("axios");
const net = require("net");
const { PromiseSocket } = require("promise-socket");
let intervalID=null;
let updateTimerID=null;
async function main() {
adapter.log.debug("start with interface ebusd ");
FillPolledVars();
FillHistoryVars();
FillHTTPParamsVars();
await checkVariables();
await subscribeVars();
let readInterval = 5;
if (parseInt(adapter.config.readInterval) > 0) {
readInterval = adapter.config.readInterval;
}
adapter.log.debug("read every " + readInterval + " minutes");
intervalID = setInterval(Do, readInterval * 60 * 1000);
//read at adapterstart
await Do();
}
let requestRunning = false;
async function DoRequest() {
adapter.log.debug("DoRequest ");
if (!requestRunning) {
requestRunning = true;
await ebusd_ReadValues();
await ebusd_ReceiveData();
}
else {
adapter.log.debug("DoRequest: do nothing already running ");
}
requestRunning = false;
}
async function Do() {
adapter.log.debug("starting ... " );
await ebusd_Command();
await DoRequest();
}
async function HandleStateChange(id, state) {
if (state != null && state.ack !== true) {
adapter.log.debug("handle state change " + id);
const ids = id.split(".");
if (ids[2] === "cmd") {
await ebusd_Command();
StartDataRequest();
//see issue #77: only one request possible
//await Do();
}
//unhandled state change ebus.0.find
else if (ids[2] === "find") {
await ebusd_find();
}
else {
adapter.log.warn("unhandled state change " + id);
}
}
}
function StartDataRequest() {
if (updateTimerID != null) {
//already running
clearTimeout(updateTimerID);
updateTimerID = null;
}
//start or restart
updateTimerID = setTimeout(DataRequest, 500);
adapter.log.debug("StartDataRequest");
}
async function DataRequest() {
adapter.log.debug("get data after command and timeout");
if (updateTimerID != null) {
clearTimeout(updateTimerID);
updateTimerID = null;
}
await DoRequest();
}
const oPolledVars = [];
function FillPolledVars() {
if ( adapter.config.PolledDPs !== undefined && adapter.config.PolledDPs != null && adapter.config.PolledDPs.length > 0) {
adapter.log.debug("use new object list for polled vars");
//2023-02-10 only active vars
for (let i = 0; i < adapter.config.PolledDPs.length; i++) {
if (adapter.config.PolledDPs[i].active) {
oPolledVars.push(adapter.config.PolledDPs[i]);
}
}
}
else {
//make it compatible to old versions
adapter.log.debug("check old comma separeted list for polled vars");
const oPolled = adapter.config.PolledValues.split(",");
if (oPolled.length > 0) {
for (let i = 0; i < oPolled.length; i++) {
if (oPolled[i].length > 0) {
//console.log('add ' + oPolled[i]);
const value = {
circuit: "",
name: oPolled[i],
parameter: ""
};
oPolledVars.push(value);
}
}
}
}
adapter.log.info("list of polled vars " + JSON.stringify(oPolledVars));
}
let oHistoryVars = [];
function FillHistoryVars() {
if (adapter.config.HistoryDPs !== undefined && adapter.config.HistoryDPs != null && adapter.config.HistoryDPs.length > 0) {
adapter.log.debug("use new object list for history vars");
oHistoryVars = adapter.config.HistoryDPs;
}
else {
//make it compatible to old versions
adapter.log.debug("check old comma separeted list for history vars");
const oHistory = adapter.config.HistoryValues.split(",");
if (oHistory.length > 0) {
for (let i = 0; i < oHistory.length; i++) {
if (oHistory[i].length > 0) {
console.log("add " + oHistory[i]);
const value = {
name: oHistory[i],
};
oHistoryVars.push(value);
}
}
}
}
}
let oHTTPParamsVars = [];
function FillHTTPParamsVars() {
if (adapter.config.HTTPparameter !== undefined && adapter.config.HTTPparameter != null && adapter.config.HTTPparameter.length > 0) {
oHTTPParamsVars = adapter.config.HTTPparameter;
adapter.log.debug("use optionally HTTP parameter " + JSON.stringify(oHTTPParamsVars));
}
}
//===================================================================================================
// ebusd interface
async function ebusd_Command() {
const obj = await adapter.getStateAsync("cmd");
if (obj !== undefined && obj != null) {
const cmds = obj.val;
if (cmds !== "") {
adapter.log.debug("got command(s): " + cmds);
adapter.log.debug("connect telnet to IP " + adapter.config.targetIP + " port " + parseInt(adapter.config.targetTelnetPort));
try {
const socket = new net.Socket();
const promiseSocket = new PromiseSocket(socket);
await promiseSocket.connect(parseInt(adapter.config.targetTelnetPort), adapter.config.targetIP);
adapter.log.debug("telnet connected for cmd");
promiseSocket.setTimeout(5000);
const oCmds = cmds.split(",");
if (oCmds.length > 0) {
let received = "";
for (let n = 0; n < oCmds.length; n++) {
adapter.log.debug("send " + oCmds[n]);
await promiseSocket.write(oCmds[n] + "\n");
const data = await promiseSocket.read();
if (data.includes("ERR")) {
adapter.log.warn("sent " + oCmds[n] + ", received " + data + " please check ebusd logs for details!");
}
else {
adapter.log.debug("received " + data);
}
received += data.toString();
received += ", ";
}
//see issue #78: remove CR, LF and last comma
received = received.replace(/\r?\n|\r/g,"");
received = received.slice(0, -2);
//set result to cmdResult
await adapter.setStateAsync("cmdResult", { ack: true, val: received });
}
else {
adapter.log.warn("no commands in list " + cmds + " " + JSON.stringify(oCmds));
}
await adapter.setStateAsync("cmd", { ack: true, val: "" });
promiseSocket.destroy();
} catch (e) {
adapter.log.error("exception from tcp socket" + "[" + e + "]");
}
}
}
else {
adapter.log.debug("object cmd not found " + JSON.stringify(obj));
}
}
async function ebusd_find(){
try {
const socket = new net.Socket();
const promiseSocket = new PromiseSocket(socket);
await promiseSocket.connect(parseInt(adapter.config.targetTelnetPort), adapter.config.targetIP);
adapter.log.debug("telnet connected for cmd");
promiseSocket.setTimeout(5000);
await promiseSocket.write("find -F circuit,name,comment\n");
const data = await promiseSocket.read();
if (data.includes("ERR")) {
adapter.log.warn("received error! sent find, received " + data + " please check ebusd logs for details!");
}
else {
adapter.log.debug("received " + typeof data + " " + data);
}
const str = new TextDecoder().decode(data);
const datas = str.split(/\r?\n/);
for (let i = 0; i < datas.length; i++) {
//adapter.log.debug(JSON.stringify(datas[i]));
const names = datas[i].split(",");
//circuit,name,comment
await UpdateDP(names[0], names[1], names[2]);
let cmd = "read -f -c " + names[0] + " " + names[1] ;
adapter.log.debug("send cmd " + cmd);
cmd += "\n";
await promiseSocket.write(cmd);
const result = await promiseSocket.read();
adapter.log.debug("received " + typeof result + " " + result);
}
promiseSocket.destroy();
} catch (e) {
adapter.log.error("exception from tcp socket in ebusd_find" + "[" + e + "]");
}
}
//just call http://192.168.0.123:8889/data
/*
http://localhost:8080/data/mc?verbose&since=1483890000&exact
since=seconds: limit to messages that have changed since the specified UTC seconds
poll=prio: set the poll priority of matching message(s) to prio
exact[=true]: exact search for circuit/message name
verbose[=true]: include comments and field units
indexed[=true]: return field indexes instead of names
numeric[=true]: return numeric values of value list entries
valuename[=true]: include value and name of value list entries
full[=true]: include all available attributes
required[=true]: retrieve the data from the bus if not yet cached
maxage[=seconds]: retrieve the data from the bus if cached value is older than specified seconds (or not present at all)
write[=true]: include write messages in addition to read
raw[=true]: include the raw master/slave symbols as int arrays
def[=true]: include message/field definition (qq, id, fielddefs)
define=DEFINITION: (re-)define the message from DEFINITION (in CSV format)
user=USER: authenticate with USER name
secret=SECRET: authenticate with user SECRET
*/
async function subscribeVars() {
adapter.subscribeStates("cmd");
adapter.subscribeStates("find");
await adapter.setStateAsync("cmdResult", { ack: true, val: "" });
}
async function CreateObject(key, obj) {
const obj_new = await adapter.getObjectAsync(key);
//adapter.log.warn("got object " + JSON.stringify(obj_new));
if (obj_new != null) {
if ((obj_new.common.role != obj.common.role
|| obj_new.common.type != obj.common.type
|| (obj_new.common.unit != obj.common.unit && obj.common.unit != null)
|| obj_new.common.read != obj.common.read
|| obj_new.common.write != obj.common.write
|| obj_new.common.name != obj.common.name)
&& obj.type === "state"
) {
adapter.log.warn("change object " + JSON.stringify(obj) + " " + JSON.stringify(obj_new));
await adapter.extendObject(key, {
common: {
name: obj.common.name,
role: obj.common.role,
type: obj.common.type,
unit: obj.common.unit,
read: obj.common.read,
write: obj.common.write
}
});
}
}
else {
await adapter.setObjectNotExistsAsync(key, obj);
}
}
//circuit,name,comment
async function UpdateDP(circuit, name, comment) {
const key = circuit + ".messages." + name;
adapter.log.debug("update check for " + key);
// ehp.messages.Injection
//ebus.0.ehp.messages.Injection
const obj = await adapter.getObjectAsync(key);
adapter.log.debug("update check got " + JSON.stringify(obj));
//update check got null
if (obj != null) {
if (obj.common.name != comment) {
adapter.log.debug("update " + key + " " + comment);
await adapter.extendObject(key, {
common: {
name: comment,
read: true,
write: false
}
});
}
}
else {
await adapter.setObjectNotExistsAsync(key, {
type: "channel",
common: {
name: comment,
read: true,
write: false
}
});
}
}
async function checkVariables() {
adapter.log.debug("init variables ");
let key;
let obj;
key = "cmd";
obj= {
type: "state",
common: {
name: "ebusd command",
type: "string",
role: "text",
read: true,
write: true
}
};
await CreateObject(key, obj);
key = "cmdResult";
obj = {
type: "state",
common: {
name: "ebusd command result",
type: "string",
role: "text",
read: true,
write: false
}
};
await CreateObject(key, obj);
key = "find";
obj = {
type: "state",
common: {
name: "find existing data points",
type: "boolean",
role: "button",
read: false,
write: true
}
};
await CreateObject(key, obj);
adapter.log.debug("init common variables and " + oHistoryVars.length + " history DP's");
if (oHistoryVars.length > 0) {
if (oHistoryVars.length > 4) {
adapter.log.warn("too many history values " + oHistoryVars.length + " -> maximum is 4");
}
for (let n = 1; n <= oHistoryVars.length; n++) {
if (oHistoryVars[n - 1].name.length > 0) {
const name = "history value " + n + " as JSON " + oHistoryVars[n - 1].name;
key = "history.value" + n;
obj= {
type: "state",
common: {
name: name,
type: "string",
role: "value",
unit: "",
read: true,
write: false
},
native: { location: key }
};
await CreateObject(key, obj);
}
else {
adapter.log.warn("ignoring history value " + n + " (invalid name)");
}
}
key = "history.date";
obj= {
type: "state",
common: {
name: "ebus history date / time as JSON",
type: "string",
role: "value",
unit: "",
read: true,
write: false
},
native: {
location: key
}
};
await CreateObject(key, obj);
}
key = "history.error";
obj= {
type: "state",
common: {
name: "ebus error",
type: "string",
role: "value",
unit: "",
read: true,
write: false
},
native: { location: key }
};
await CreateObject(key, obj);
}
function VersionCheck() {
if (ebusdVersion[0] > 0 ) {
if (ebusdVersion[0] < ebusdMinVersion[0] || (ebusdVersion[0] == ebusdMinVersion[0] && ebusdVersion[1] < ebusdMinVersion[1])) {
adapter.log.info("please update ebusd, old version found: " + ebusdVersion[0] + "." + ebusdVersion[1] + " supported version is " + ebusdMinVersion[0] + "." + ebusdMinVersion[1]);
}
if (ebusdVersion[0] > ebusdMinVersion[0] || (ebusdVersion[0] >= ebusdMinVersion[0] && ebusdVersion[1] > ebusdMinVersion[1])) {
adapter.log.info("unsupported ebusd version found (too new): " + ebusdVersion[0] + "." + ebusdVersion[1] + " supported version is " + ebusdMinVersion[0] + "." + ebusdMinVersion[1]);
}
}
if (ebusdUpdateVersion[0] > 0 && ebusdVersion[0] > 0) {
if (ebusdUpdateVersion[0] > ebusdVersion[0] || (ebusdUpdateVersion[0] == ebusdVersion[0] && ebusdUpdateVersion[1] > ebusdVersion[1])) {
adapter.log.info("new ebusd version found: " + ebusdUpdateVersion[0] + "." + ebusdUpdateVersion[1] + " supported version is " + ebusdMinVersion[0] + "." + ebusdMinVersion[1]);
}
}
}
//get data via https in json -> this is the main data receiver; telnet just triggers ebusd to read data;
//https://github.com/john30/ebusd/wiki/3.2.-HTTP-client
async function ebusd_ReceiveData() {
let sUrl = "http://" + adapter.config.targetIP + ":" + parseInt(adapter.config.targetHTTPPort) + "/data";
//Erweiterung mit optionalen parametern
var paramsCnt = 0;
if (oHTTPParamsVars !== undefined && oHTTPParamsVars != null && oHTTPParamsVars.length > 0) {
for (let i = 0; i < oHTTPParamsVars.length; i++) {
if (oHTTPParamsVars[i].active) {
if (paramsCnt == 0) {
sUrl += "?" ;
}
else {
sUrl += "&";
}
sUrl += oHTTPParamsVars[i].name + "=" + oHTTPParamsVars[i].value;
paramsCnt++;
}
}
}
adapter.log.debug("request data from " + sUrl);
try {
const buffer = await axios.get(sUrl);
adapter.log.debug("got data " + typeof buffer.data + " " + JSON.stringify(buffer.data));
//workaround issue #338
//const oData = buffer.data;
//erst nach string
const sData = JSON.stringify(buffer.data);
const oData = JSON.parse(sData.replace('\"updatecheck\": \"\n', '\"updatecheck\": \"'));
//adapter.log.debug("000 " + typeof oData + JSON.stringify(oData));
//adapter.log.debug("oData " + oData);
const flatten = require("flat");
const newData = flatten(oData);
//adapter.log.debug("111 " + JSON.stringify(newData));
const keys = Object.keys(newData);
//adapter.log.debug("222 " + JSON.stringify(keys));
//adapter.log.debug("history: " + options.historyValues);
const historyvalues = [];
const historydates = [];
const oToday = new Date();
const month = oToday.getMonth() + 1;
historydates.push({
"date": oToday.getDate() + "." + month + "." + oToday.getFullYear(),
"time": oToday.getHours() + ":" + oToday.getMinutes() + ":" + oToday.getSeconds()
});
//adapter.log.debug(JSON.stringify(historydates));
let name = "unknown";
let sError = "none";
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
const org_key = key;
if (key.includes("[") || key.includes("]")) {
adapter.log.debug("found unsupported chars in " + key);
const start = key.indexOf("[");
const end = key.lastIndexOf("]");
if (start > 0 && end > 0) {
const toReplace = key.slice(start, end + 1);
key = key.replace(toReplace, "");
}
//adapter.log.warn("new key is " + key);
}
const subnames = key.split(".");
const temp = subnames.length;
//adapter.log.debug('Key : ' + key + ', Value : ' + newData[key]);
//
//if (key.match(adapter.FORBIDDEN_CHARS)) { continue; }
if (key.includes("global.version")) {
const value = newData[org_key];
//adapter.log.info("in version, value " + value);
const versionInfo = value.split(".");
if (versionInfo.length > 1) {
adapter.log.info("installed ebusd version is " + versionInfo[0] + "." + versionInfo[1]);
ebusdVersion[0] = versionInfo[0];
ebusdVersion[1] = versionInfo[1];
VersionCheck();
}
}
if (key.includes("global.updatecheck")) {
let value = newData[org_key];
//adapter.log.info("in version, value " + value);
//revision v21.2 available
value = value.replace("revision v", "");
value = value.replace(" available", "");
const versionInfo = value.split(".");
if (versionInfo.length > 1) {
adapter.log.info("found ebusd update version " + versionInfo[0] + "." + versionInfo[1]);
ebusdUpdateVersion[0] = versionInfo[0];
ebusdUpdateVersion[1] = versionInfo[1];
VersionCheck();
}
}
if (subnames[temp - 1].includes("name")) {
name = newData[org_key];
}
else if (subnames[temp - 1].includes("value")) {
//adapter.log.debug('Key : ' + key + ', Value : ' + newData[key] + " name " + name);
let value = newData[org_key];
if (value == null || value === undefined) {
adapter.log.debug("Key : " + key + ", Value : " + newData[org_key] + " name " + name);
}
if (name === "hcmode2") {
if (parseInt(value) === 0) {
adapter.log.info(key + "in hcmode2 with value 0: off");
value = "off";
}
else if (parseInt(value) === 5) {
adapter.log.info(key + " with value 5: EVU Sperrzeit");
value = "EVU Sperrzeit";
}
else {
adapter.log.debug("in hcmode2, value " + value);
}
}
let type = typeof value;
if (adapter.config.useBoolean4Onoff) {
if (type == "string" && (value == "on" || value == "off")) {
adapter.log.debug("Key " + key + " change to boolean " + value);
//Key mc.messages.Status.fields.1.value could be boolean off
type = "boolean";
if (value == "on") {
value = true;
}
else {
value = false;
}
}
}
//value, change type if necessary
await AddObject(key, type);
await UpdateObject(key, value);
//name parallel to value: used for lists in admin...
const keyname = key.replace("value", "name");
await AddObject(keyname, "string");
await UpdateObject(keyname, name);
//push to history
//ebus.0.bai.messages.ReturnTemp.fields.temp.value
//ebus.0.bai.messages.ReturnTemp.fields.tempmirror.value
if (!subnames[temp - 2].includes("sensor") //ignore sensor states
&& !subnames[temp - 2].includes("mirror") //ignore mirror-data
) {
for (let ii = 0; ii < oHistoryVars.length; ii++) {
if (name === oHistoryVars[ii].name) {
const sTemp = '{"' + name + '": "' + value + '"}';
//adapter.log.debug(sTemp);
historyvalues[ii] = [];
historyvalues[ii].push(JSON.parse(sTemp));
//adapter.log.debug(JSON.stringify(historyvalues));
}
}
}
}
else if (subnames[temp - 1].includes("lastup")) {
const value = newData[org_key];
if (parseInt(value) > 0) {
//adapter.log.debug('Key : ' + key + ', Value : ' + newData[key] + " name " + name);
//umrechnen...
const oDate = new Date(value * 1000);
//const nDate = oDate.getDate();
//const nMonth = oDate.getMonth() + 1;
//const nYear = oDate.getFullYear();
//const nHours = oDate.getHours();
//const nMinutes = oDate.getMinutes();
//const nSeconds = oDate.getSeconds();
const sDate = oDate.toLocaleString();
await AddObject(key, "string");
await UpdateObject(key, sDate);
const oToday = new Date();
let bSkip = false;
if (subnames[0].includes("scan") ||
subnames[0].includes("Scan") ||
subnames[0].includes("ehp") ||
(subnames.length > 2 && subnames[2].includes("currenterror"))
) {
bSkip = true;
}
if (temp > 2) {
//adapter.log.debug("_______________size " + temp);
if (subnames[2].includes("Timer")) {
bSkip = true;
}
}
if (!bSkip && Math.abs(oDate.getTime() - oToday.getTime()) > 1 * 60 * 60 * 1000) {
/*2024-11-20
ebus: no update since 19.11.2024, 21:11:14 Scan.15.messages.Id.lastup no update since 19.11.2024, 21:11:19 Scan.23.messages.Id.lastup no update since 19.11.2024, 21:10:34 Scan.25.messages.Id.lastup no update since 19.11.2024, 21:12:04 Scan.50.messages.Id.lastup
*/
const sError1 = "no update since " + sDate + " " + key + " ";
if (sError.includes("none")) {
sError = "ebus: " + sError1;
}
else {
sError += sError1;
}
adapter.log.warn(sError1);
}
}
}
else if (subnames[0].includes("global")) {
//adapter.log.debug('Key : ' + key + ', Value : ' + newData[key] + " name " + name);
const value = newData[org_key];
await AddObject(key, typeof value);
await UpdateObject(key, value);
}
}
await adapter.setStateAsync("history.error", { ack: true, val: sError });
//adapter.log.debug(JSON.stringify(historyvalues));
adapter.log.info("all http done");
if (adapter.config.History4Vis2) {
await UpdateHistory_Vis2(historyvalues, historydates);
}
else {
await UpdateHistory(historyvalues, historydates);
}
}
catch (e) {
adapter.log.error("exception in ebusd_ReceiveData [" + e + "]");
await adapter.setStateAsync("history.error", { ack: true, val: "exception in receive" });
}
//});
}
async function UpdateHistory_Vis2(values, dates) {
adapter.log.debug("start history 4 VIS-2 " + JSON.stringify(values) + " " + JSON.stringify(dates));
//not used anymore
await adapter.setStateAsync("history.date", { ack: true, val: "" });
for (let s = 0; s < values.length; s++) {
const values1 = values[s];
//adapter.log.debug(s + " " + JSON.stringify(values1));
let val2Write = [];
const ctr = s + 1;
const obj = await adapter.getStateAsync("history.value" + ctr);
if (obj === null || obj === undefined) {
adapter.log.warn("history.value" + ctr + " not found, creating DP " + JSON.stringify(obj));
await adapter.setStateAsync("history.value" + ctr, { ack: true, val: "[]" });
}
val2Write = JSON.parse(obj.val);
adapter.log.debug("history.value" + ctr + " got " + JSON.stringify(val2Write));
for (let ss = 0; ss < values1.length; ss++) {
const values2 = values1[ss];
//adapter.log.debug(ss + " " + JSON.stringify(values2));
let d = 0;
for (const n in values2) {
const val = values2[n];
const time = dates[d]["time"];
const date = dates[d]["date"];
d++;
const times = time.split(":");
const datesl = date.split(".");
const day = parseInt(datesl[0]);
const month = parseInt(datesl[1]) - 1;
const year = parseInt(datesl[2]);
const hours = parseInt(times[0]);
const minutes = parseInt(times[1]);
const oDate = new Date(year, month, day, hours, minutes, 0, 0);
adapter.log.debug(n + " " + val + " " + oDate.toLocaleString());
val2Write.push(
[
oDate,
val
]
);
if (val2Write.length > 200) {
for (let i = val2Write.length; i > 200; i--) {
//adapter.log.debug("delete");
val2Write.shift();