forked from weberk/ioBroker.ta-blnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
1694 lines (1604 loc) · 94.9 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.6.5
*/
// The adapter-core module gives you access to the core ioBroker functions
const utils = require("@iobroker/adapter-core");
// The net module is used to create TCP clients and servers
const net = require("node:net");
//const os = require("node:os");
const http = require("node:http");
/**
* Adapter class for UVR16xx BL-NET devices.
*
*/
class TaBlnet extends utils.Adapter {
/**
* Constructor for the adapter instance
*
* @param {Partial<utils.AdapterOptions>} [options={}] - The adapter options.
*/
constructor(options) {
// Call the parent constructor with the adapter name and options
super({
...options,
name: "ta-blnet",
});
this.on("ready", this.onReady.bind(this)); // Bind the onReady method
// this.on("stateChange", this.onStateChange.bind(this)); // Bind the onStateChange method
// this.on("objectChange", this.onObjectChange.bind(this)); // Uncomment to bind the onObjectChange method
// this.on("message", this.onMessage.bind(this)); // Uncomment to bind the onMessage method
this.on("unload", this.onUnload.bind(this)); // Bind the onUnload method
// Initialize the adapter's state
this.initialized = false;
// Memorize uvr_mode
this.uvr_mode = 0;
// Memorize the current timeout ID; later used for clearing the timeout
this.currentTimeoutId = null;
this.numberOfDataFrames = 0; // Number of data frames to process
// memorize systemConfiguration
this.systemConfiguration = {
success: false,
stateValues: {},
deviceInfo: {},
};
// define constants
// Topics according TA Documentation "CMI-JSON-API Version 7"
this.cmiUnits = [
"", // index 0
"°C", // index 1
"W/m²", // index 2
"l/h", // index 3
"sec", // index 4
"min", // index 5
"l/Imp", // index 6
"K", // index 7
"%", // index 8
"", // index 9
"kW", // index 10
"kWh", // index 11
"MWh", // index 12
"V", // index 13
"mA", // index 14
"hr", // index 15
"Days", // index 16
"Imp", // index 17
"kΩ", // index 18
"l", // index 19
"km/h", // index 20
"Hz", // index 21
"l/min", // index 22
"bar", // index 23
"", // index 24
"km", // index 25
"m", // index 26
"mm", // index 27
"m³", // index 28
"", // index 29
"", // index 30
"", // index 31
"", // index 32
"", // index 33
"", // index 34
"l/d", // index 35
"m/s", // index 36
"m³/min", // index 37
"m³/h", // index 38
"m³/d", // index 39
"mm/min", // index 40
"mm/h", // index 41
"mm/d", // index 42
"ON/OFF", // index 43
"NO/YES", // index 44
"", // index 45
"°C", // index 46
"", // index 47
"", // index 48
"", // index 49
"€", // index 50
"$", // index 51
"g/m³", // index 52
"", // index 53
"°", // index 54
"", // index 55
"°", // index 56
"sec", // index 57
"", // index 58
"%", // index 59
"h", // index 60
"", // index 61
"", // index 62
"A", // index 63
"", // index 64
"mbar", // index 65
"Pa", // index 66
"ppm", // index 67
"", // index 68
"W", // index 69
"t", // index 70
"kg", // index 71
"g", // index 72
"cm", // index 73
"K", // index 74
"lx", // index 75
"Bg/m³", // index 76
];
// CMI-JSON-API Version 7
this.cmiAttachedDevices = {
"7F": "CoE",
"80": "UVR1611",
"81": "CAN-MT",
"82": "CAN-I/O44",
"83": "CAN-I/O35",
"84": "CAN-BC",
"85": "CAN-EZ",
"86": "CAN-TOUCH",
"87": "UVR16x2",
"88": "RSM610",
"89": "CAN-I/O45",
"8A": "CMI",
"8B": "CAN-EZ2",
"8C": "CAN-MTx2",
"8D": "CAN-BC2",
"8E": "UVR65",
"8F": "CAN-EZ3",
"91": "UVR610",
"92": "UVR67",
"A3": "BL-NET",
};
// Define sections to be used for ioBroker adapter objects CMI-JSON-API Version 7
// Parameter Description Supported devices
this.cmiSections = [
// La Analog logging x2-tech
"Logging Analog",
// Ld Digital logging x2-tech
"Logging Digital",
// I Inputs 1611, x2-tech
"Inputs",
// O Outputs 1611, x2-tech
"Outputs",
// Na Analog network inputs 1611
"Network Analog",
// Nd Digital network inputs 1611
"Network Digital",
// D DL-inputs x2-tech
"DL-Bus",
// Sg System-values: General x2-tech
"General",
// Sd System-values: Date x2-tech
"Date",
// St System-values: Time x2-tech
"Time",
// Ss System-values: Sun x2-tech
"Sun",
// Sp System-values: Electrical power CAN-EZ2, CAN-EZ3
"Electrical power",
// Sp System-values: Electrical power CAN-EZ2, CAN-EZ3
"Electrical Power",
// M M-Bus CAN-BC2, RSM610-M, UVR610
"MBus",
// M M-Bus CAN-BC2, RSM610-M, UVR610
"M-Bus",
// AM Modbus CAN-BC2, UVR610S-MODB, CAN-EZ3
"Modbus",
// AK KNX CAN-BC2
"KNX",
];
// this.config.can_node_list
this.can_node_list = {};
this.jsConfigObject = {};
}
/**
* Is called when the adapter is ready
*/
async onReady() {
// The adapter's config (in the instance object everything under the attribute "native") is accessible via
// this.config. Check whats in the config
this.log.info("config ip_address: " + this.config.ip_address);
this.log.info("config port: " + this.config.port);
this.log.info("config poll_interval: " + this.config.poll_interval);
this.log.info("expert_username: " + this.config.expert_username);
this.log.info("expert_password: " + this.config.expert_password);
this.log.info("selected_ta_logger: " + this.config.selected_ta_logger);
// Konvertiere das JSON-Dokument in ein JavaScript-Objekt
try {
this.jsConfigObject = JSON.parse(this.config.json);
this.log.info("JavaScript Configuration Object: " + JSON.stringify(this.jsConfigObject));
} catch (error) {
this.log.error("Error parsing JSON Configuration: " + error.message);
}
// Subscribe to all objects
this.initialized = false;
// this.subscribeObjects("system.adapter.ta-blnet.*.alive");
// this.subscribeForeignStates("system.adapter.ta-blnet.*.alive");
//this.subscribeObjects(`system.adapter.${this.namespace}`);
// Check if the selected TA logger has changed
const devicePath = this.name2id(this.namespace + "." + this.config.selected_ta_logger);
const initializedLogger = await this.getObjectAsync(devicePath);
if (initializedLogger) {
this.log.debug("onReady: Initialization time logger is the same as in configuration.");
} else {
this.log.debug("onReady: Initialization time logger has changed.");
await this.deleteObjectsUnderInstance(this.namespace);
}
//Test code for "CPU Model Name Resolved as Unknown for Raspberry PI2" https://github.com/nodejs/node/issues/56105
// const cpus = os.cpus();
// cpus.forEach((cpu, index) => {
// this.log.debug(`CPU ${index}: ${JSON.stringify(cpu)}`);
// });
// const cpuModel = cpus && cpus[0] && cpus[0].model ? cpus[0].model : "unknown";
// this.log.debug("CPU Model: " + cpuModel + " cpus[0]:" + JSON.stringify(cpus[0]));
// Start polling
this.startPolling();
}
/**
* Polling function to fetch state values from the IoT device at regular intervals.
*/
startPolling() {
const pollInterval = Math.min(this.config.poll_interval * 1000, 3600000); // Poll interval in milliseconds, with a maximum of 3600000 ms (1 hour)
const poll = async () => {
// Perform an initialization read attempt, if failed do not start polling
if (!this.initialized) {
try {
this.systemConfiguration = await this.readSystemConfiguration();
// Set status for info.connection
this.log.debug("Setting connection status to: " + this.systemConfiguration.success);
await this.setState("info.connection", this.systemConfiguration.success, true);
if (this.systemConfiguration.success === true) {
// Declare objects
await this.declareOrUpdateObjects();
this.log.debug("objects for metrics declared.");
this.initialized = true;
this.log.debug("Initialization succeeded.");
}
} catch (error) {
this.log.error("Initialization failed: " + error);
return; // Stop polling if initialization fails
}
}
// Perform polling operations only if initialization was successful
if (this.initialized) {
try {
const stateValuesArray = []; // Create a local array
const deviceInfo = this.systemConfiguration.deviceInfo;
// loop through all data frames evident from the header_frame
this.log.debug("Polling state values from devices: " + JSON.stringify(deviceInfo.channelNodes));
for (const data_frame_index of deviceInfo.channelNodes) {
const currentStateValuesArray = await this.fetchStateValuesFromDevice(data_frame_index);
// loop through all currentStateValues returned by the current data frame read (2DL = 2, 1DL = 1, CAN = 1)
for (let j = 0; j < currentStateValuesArray.length; j++) {
stateValuesArray.push(currentStateValuesArray[j]);
}
}
this.systemConfiguration.stateValues = stateValuesArray; // Assign the local array to systemConfiguration
await this.setState("info.connection", this.systemConfiguration.success, true);
// Update objects
await this.declareOrUpdateObjects();
this.log.debug("objects for metrics updated.");
} catch (error) {
await this.setState("info.connection", false, true);
this.log.error("Error polling state values: " + error);
}
}
// Schedule the next poll
this.currentTimeoutId = this.setTimeout(poll, pollInterval);
};
// Start the polling loop
this.currentTimeoutId = this.setTimeout(poll, pollInterval);
}
/**
* Reads the system configuration from the device.
*
* @returns {Promise<{success: boolean, stateValues: object, deviceInfo: object}>} - The result of the read with success status, state values, device info, and units.
*/
async readSystemConfiguration() {
let deviceInfo;
const stateValuesArray = []; // Create a local array
// Try to read some metadata on the devices
try {
// BL-NET selected
if (this.config.selected_ta_logger === "BL-NET") {
deviceInfo = await this.read_BLNET_DeviceInfo();
this.log.debug("deviceInfo is defined as:" + JSON.stringify(deviceInfo));
// Try to read the state values from the device
try {
// loop through all data frames evident from the header_frame
for (let i = 0; i < this.numberOfDataFrames; i++) {
const currentStateValuesArray = await this.fetchStateValuesFromDevice(deviceInfo.channelNodes[i]);
// loop through all currentStateValues returned by the current data frame read (2DL = 2, 1DL = 1, CAN = 1)
for (let j = 0; j < currentStateValuesArray.length; j++) {
stateValuesArray.push(currentStateValuesArray[j]);
}
}
} catch (error) {
this.log.error("readSystemConfiguration reading stateValues failed: " + error);
return {
success: false,
stateValues: [],
deviceInfo: {},
};
}
} else {
// CMI selected
// check the CAN nodes from CMI configuration
const canNodesArray = this.jsConfigObject.requests.map(request => request.can_node_number);
this.log.info("CAN Node Numbers Array: " + JSON.stringify(canNodesArray));
this.numberOfDataFrames = canNodesArray.length;
deviceInfo = {
uvr_mode: this.numberOfDataFrames + "CAN",
uvr_type_str: {},
uvr_type_code: {},
channelNodes: canNodesArray,
module_id: "--",
firmware_version: "--",
transmission_mode: "--",
};
// Fetch JSON data from device for each CAN node and update deviceInfo
const uvr_type_str = [];
const uvr_type_code = [];
for (const data_frame_index of deviceInfo.channelNodes) {
try {
this.log.debug("readSystemConfiguration reading data for CAN node: " + data_frame_index);
const res = await this.fetchJSONDataFromDevice(data_frame_index);
// use the header data to get the device type
const deviceCode = res.data.Header.Device; // take hex number as capital letter string
uvr_type_code.push(deviceCode);
const deviceName = this.cmiAttachedDevices[deviceCode] || "Unknown";
uvr_type_str.push(deviceName);
// reuse res to get the values
const currentUvrJSONRecord = this.parseUvrRecordFromJSON(res.data);
stateValuesArray.push(currentUvrJSONRecord);
} catch (error) {
this.log.error("Error fetching data for CAN node " + data_frame_index + ": " + error.message);
return {
success: false,
stateValues: [],
deviceInfo: {},
};
}
}
// Update deviceInfo with the fetched data
deviceInfo.uvr_type_code = uvr_type_code;
deviceInfo.uvr_type_str = uvr_type_str;
this.log.debug("deviceInfo is defined as:" + JSON.stringify(deviceInfo));
}
} catch (error) {
this.log.debug("readSystemConfiguration reading of DeviceInfo failed: " + error);
return {
success: false,
stateValues: [],
deviceInfo: {},
};
}
// all succeeded
this.log.info("readSystemConfiguration succeeded.");
// returned system configuration will be stored in the adapter instance
return {
success: true,
stateValues: stateValuesArray,
deviceInfo: deviceInfo,
};
}
/**
* Reads device information from the BL-NET device.
*
* This method sends various commands to the device to retrieve information such as
* module ID, UVR mode, UVR type, firmware version, and transmission mode. It processes
* the received data and returns an object containing these details.
*
* @returns {Promise<object>} An object containing the device information:
* - {string} uvr_mode - The UVR mode (e.g., "1DL", "2DL", "CAN").
* - {Array<string>} uvr_type_str - The UVR type(s) as strings (e.g., ["UVR61-3", "UVR1611"]).
* - {Array<number>} uvr_type_code - The UVR type(s) as numbers.
* - {Array<number>} channelNodes - The channel nodes (e.g., [1, 2, 3]).
* - {string} module_id - The module ID of the BL-NET device.
* - {string} firmware_version - The firmware version of the BL-NET device.
* - {string} transmission_mode - The transmission mode (e.g., "Current Data").
* @throws {Error} If there is an error during communication with the device.
*/ async read_BLNET_DeviceInfo() {
// Define constants
const VERSION_REQUEST = 0x81;
const HEADER_READ = 0xaa;
const FIRMWARE_REQUEST = 0x82;
const MODE_REQUEST = 0x21;
const devices = [];
try {
let data;
const uvr_type_code = [];
let command;
// Send version request
command = new Uint8Array([VERSION_REQUEST]);
data = await this.sendCommand(command);
const module_id = data.toString("hex");
this.log.debug("Received module ID of BL-NET: 0x" + module_id.toUpperCase());
// Query UVR type
command = new Uint8Array([HEADER_READ]);
data = await this.fetchDataBlockFromDevice(command);
// Guess the uvr_mode based on the length of the data array
// const HEADER_A8_FRAME_LENGTH = 13;
// const HEADER_D1_FRAME_LENGTH = 14;
// const HEADER_DC_FRAME_LENGTH = 14 - 21;
// 0xA8 (1DL) / 0xD1 (2DL) / 0xDC (CAN) */
let uvr_mode_str;
// typedef struct {
// UCHAR identifier;
// UCHAR version; <--- uvr_mode
// ...
// } Header_FRAME;
// Define the offsets based on the C struct definitions
const HEADER_D1_DEVICE1_LENGTH_OFFSET = 5;
const HEADER_D1_DEVICE2_LENGTH_OFFSET = 6;
const HEADER_A8_DEVICE1_LENGTH_OFFSET = 5;
const HEADER_DC_DEVICE1_LENGTH_OFFSET = 6;
// Mode 0xD1 - Length 14 bytes
/* Data structure of the header from D-LOGG or BL-Net */
// typedef struct {
// UCHAR identifier;
// UCHAR version;
// UCHAR timestamp[3];
// UCHAR recordLengthDevice1;
// UCHAR recordLengthDevice2;
// UCHAR startAddress[3];
// UCHAR endAddress[3];
// UCHAR checksum; /* Sum of bytes mod 256 */
// } Header_D1_FRAME;
// Mode 0xA8 - Length 13 bytes
/* Data structure of the header from D-LOGG or BL-Net */
/* Mode 0xA8 - Length 13 bytes - HeaderA8 - */
// typedef struct {
// UCHAR identifier;
// UCHAR version;
// UCHAR timestamp[3];
// UCHAR recordLengthDevice1;
// UCHAR startAddress[3];
// UCHAR endAddress[3];
// UCHAR checksum; /* Sum of bytes mod 256 */
// } Header_A8_FRAME;
// CAN-Logging only with UVR1611
// You can log either from the DL bus (max. 2 data lines) or from the CAN bus (max. 8 data records).
// Max. number of data records from points-in-time or data links/sources when CAN data logging is used: 8
// struct {
// UCHAR identifier;
// UCHAR version;
// UCHAR timestamp[3];
// UCHAR numberOfCANFrames;
// UCHAR recordLengthFrame1;
// UCHAR ...;
// UCHAR recordLengthFrame8;
// UCHAR startAddress[3];
// UCHAR endAddress[3];
// UCHAR checksum; /* Sum of bytes mod 256 */
// } HEADER_DC_Frame8
this.uvr_mode = data[1]; // identifier
switch (this.uvr_mode) {
case 0xa8:
uvr_mode_str = "1DL";
this.numberOfDataFrames = 1;
uvr_type_code.push(data[HEADER_A8_DEVICE1_LENGTH_OFFSET].toString(16).toUpperCase());
break;
case 0xd1:
uvr_mode_str = "2DL";
this.numberOfDataFrames = 1;
uvr_type_code.push(data[HEADER_D1_DEVICE1_LENGTH_OFFSET].toString(16).toUpperCase());
uvr_type_code.push(data[HEADER_D1_DEVICE2_LENGTH_OFFSET].toString(16).toUpperCase());
break;
case 0xdc:
this.numberOfDataFrames = data[5];
uvr_mode_str = this.numberOfDataFrames + "CAN";
for (let i = 0; i < this.numberOfDataFrames; i++) {
uvr_type_code.push(data[HEADER_DC_DEVICE1_LENGTH_OFFSET + i].toString(16).toUpperCase());
}
break;
default:
throw new Error("Unknown mode: 0x" + this.uvr_mode.toString(16).toUpperCase());
}
this.log.debug("Received UVR mode of BL-NET: " + uvr_mode_str);
// derive device type as a string from length of data record of a data frame
for (let i = 0; i < this.numberOfDataFrames; i++) {
let uvr_type_str;
switch (uvr_type_code[i]) {
case "5A":
uvr_type_str = "UVR61-3";
break;
case "76":
uvr_type_str = "UVR1611";
break;
default:
uvr_type_str = "Unknown";
}
devices.push(uvr_type_str);
this.log.debug("Received UVR type of BL-NET: " + uvr_type_str);
}
// Send firmware version request
command = new Uint8Array([FIRMWARE_REQUEST]);
data = await this.sendCommand(command);
const firmwareVersion = (data.readUInt8(0) / 100).toString();
this.log.debug("Received firmware version of BL-NET: " + firmwareVersion);
// Send transmission mode request
command = new Uint8Array([MODE_REQUEST]);
data = await this.sendCommand(command);
const transmission_mode = "0x" + data.readUInt8(0).toString(16).toUpperCase();
this.log.debug("Received mode of BL-NET: 0x" + transmission_mode);
// Create an array with the frame indices [1, 2, ..., 8]
const frameIndexArray = [];
for (let i = 1; i <= this.numberOfDataFrames; i++) {
frameIndexArray.push(i);
}
return {
uvr_mode: uvr_mode_str,
uvr_type_str: devices,
uvr_type_code: uvr_type_code,
channelNodes: frameIndexArray,
module_id: "0x" + module_id.toUpperCase(),
firmware_version: firmwareVersion,
transmission_mode: transmission_mode,
};
} catch (error) {
this.log.error("Error during communication with BL-NET: " + error);
throw error;
} finally {
this.log.debug("End readDeviceInfo");
}
}
/**
* Declares various objects (device information, outputs, speed levels, inputs, thermal energy counters status, and thermal energy counters)
* based on the provided system configuration.
*
* @returns {Promise<void>} - A promise that resolves when all objects have been declared.
*/
async declareOrUpdateObjects() {
const deviceInfo = this.systemConfiguration.deviceInfo;
const stateValues = this.systemConfiguration.stateValues;
// Check if deviceInfo is defined
const device_node_name = this.name2id(this.config.selected_ta_logger);
if (deviceInfo) {
// create device node
if (!this.initialized) {
await this.setObjectNotExistsAsync(device_node_name, {
type: "device",
common: {
name: "Door to Climate Controls",
role: "gateway",
},
native: {},
});
}
// Declare device information
for (const [key, value] of Object.entries(deviceInfo)) {
const currentKeyName = this.name2id("info." + key);
if (!this.initialized) {
await this.setObjectNotExistsAsync(currentKeyName, {
type: "state",
common: {
name: key,
type: "string",
role: "info",
read: true,
write: false,
},
native: {},
});
}
await this.setState(currentKeyName, {
val: JSON.stringify(value),
ack: true,
});
}
} else {
this.log.error("deviceInfo is undefined or null");
}
// Check if stateValues is defined
if (stateValues) {
// Declare objects for each data frame
for (let i = 0; this.numberOfDataFrames && i < this.numberOfDataFrames; i++) {
const channelNode = deviceInfo.channelNodes[i].toString().padStart(4, "0");
const currentFrameName = this.name2id(device_node_name + "." + channelNode + "-" + deviceInfo.uvr_type_str[i]);
if (!this.initialized) {
await this.setObjectNotExistsAsync(currentFrameName, {
type: "channel",
common: {
name: "Channel " + deviceInfo.channelNodes[i] + " (" + this.config.selected_ta_logger + ")",
role: "climate",
},
native: {},
});
}
// Create full path prefix
const path_pre = currentFrameName + ".";
let currentFolderName = "";
// iterate through all sections
for (const section of this.cmiSections) {
// Check if stateValues of section is defined
if (stateValues[i][section]) {
// create folder node for section
currentFolderName = this.name2id(path_pre + section);
if (!this.initialized) {
await this.setObjectNotExistsAsync(currentFolderName, {
type: "folder",
common: {
name: "Metrics for " + section,
},
native: {},
});
}
// Declare objects for each section
this.log.debug(this.name2id(section) + " status: " + JSON.stringify(stateValues[i][section]));
for (const [key, value] of Object.entries(stateValues[i][section])) {
const currentKeyName = this.name2id(currentFolderName + "." + key);
if (!this.initialized) {
//this.log.debug("creating currentKeyName: " + currentKeyName);
await this.setObjectNotExistsAsync(currentKeyName, {
type: "state",
common: {
name: key,
type: "number",
role: "value",
unit: value.unit,
read: true,
write: false,
},
native: {},
});
}
// Set the state value
//this.log.debug("setting state value for currentKeyName: " + currentKeyName);
await this.setState(currentKeyName, {
val: value.value,
ack: true,
});
}
} else {
this.log.debug(this.name2id(section) + " section: " + stateValues[i][section]);
}
}
// BL-NET selected
if (this.config.selected_ta_logger === "BL-NET") {
// create folder node for speed_levels
currentFolderName = this.name2id(path_pre + "speed_levels");
if (!this.initialized) {
await this.setObjectNotExistsAsync(currentFolderName, {
type: "folder",
common: {
name: "Metrics for Speed Levels",
},
native: {},
});
}
// Declare speed levels
this.log.debug("speed_levels status: " + JSON.stringify(stateValues[i].speed_levels));
if (stateValues[i].speed_levels) {
for (const [key, value] of Object.entries(stateValues[i].speed_levels)) {
const currentKeyName = this.name2id(currentFolderName + "." + key);
if (!this.initialized) {
await this.setObjectNotExistsAsync(currentKeyName, {
type: "state",
common: {
name: key,
type: "number",
role: "value.speed",
unit: value.type,
read: true,
write: false,
},
native: {},
});
}
await this.setState(currentKeyName, {
val: value.value,
ack: true,
});
}
} else {
this.log.error("stateValues.speed_levels is undefined or null");
}
// create folder node for thermal_energy_counters_status
currentFolderName = this.name2id(path_pre + "thermal_energy_counters_status");
if (!this.initialized) {
await this.setObjectNotExistsAsync(currentFolderName, {
type: "folder",
common: {
name: "Metrics for Thermal Energy Counters Activation",
},
native: {},
});
}
// Declare thermal energy counters status
this.log.debug("thermal_energy_counters_status status: " + JSON.stringify(stateValues[i].thermal_energy_counters_status));
if (stateValues[i].thermal_energy_counters_status) {
for (const [key, value] of Object.entries(stateValues[i].thermal_energy_counters_status)) {
const currentKeyName = this.name2id(currentFolderName + "." + key);
if (!this.initialized) {
await this.setObjectNotExistsAsync(currentKeyName, {
type: "state",
common: {
name: key,
type: "boolean",
role: "sensor.switch",
unit: value.type,
read: true,
write: false,
},
native: {},
});
}
await this.setState(currentKeyName, {
val: value.value,
ack: true,
});
}
} else {
this.log.error("stateValues.thermal_energy_counters_status is undefined or null");
}
// create folder node for thermal_energy_counters
currentFolderName = this.name2id(path_pre + "thermal_energy_counters");
if (!this.initialized) {
await this.setObjectNotExistsAsync(currentFolderName, {
type: "folder",
common: {
name: "Metrics for Thermal Energy Counters",
},
native: {},
});
}
// Declare thermal energy counters
this.log.debug("thermal_energy_counters status: " + JSON.stringify(stateValues[i].thermal_energy_counters));
if (stateValues[i].thermal_energy_counters) {
for (const [key, value] of Object.entries(stateValues[i].thermal_energy_counters)) {
const currentKeyName = this.name2id(currentFolderName + "." + key);
let currentRole = "";
if (key.startsWith("current_heat_power")) {
currentRole = "value.power";
} else if (key.startsWith("total_heat_energy")) {
currentRole = "value.energy";
}
if (!this.initialized) {
await this.setObjectNotExistsAsync(currentKeyName, {
type: "state",
common: {
name: key,
type: "number",
role: currentRole,
unit: value.type,
read: true,
write: false,
},
native: {},
});
}
await this.setState(currentKeyName, {
val: value.value,
ack: true,
});
}
} else {
this.log.error("stateValues.thermal_energy_counters is undefined or null");
}
}
}
} else {
this.log.error("stateValues is undefined or null");
}
}
/**
* Fetches state values from the device.
*
* This method sends a command to the device to read the current data and processes the response.
* It parses the response data and updates the state values accordingly.
*
* @async
* @param {number} data_frame_index - The index of the data frame to fetch state values for.
* @returns {Promise<object>} A promise that resolves to an object containing the state values.
* @throws {Error} If there is an error during communication with the device or if the response format is unexpected.
*/
async fetchStateValuesFromDevice(data_frame_index) {
const stateValuesArray = [];
const READ_CURRENT_DATA = 0xab; // Command byte to read current data
const LATEST_SIZE = 56; // Size of one UVR1611 record
try {
if (this.config.selected_ta_logger === "BL-NET") {
this.log.debug("fetchStateValuesFromDevice BL-NET for data frame: " + data_frame_index);
const command = new Uint8Array([READ_CURRENT_DATA, data_frame_index]);
const data = await this.fetchDataBlockFromDevice(command);
// Process the received data here
if (data[0] === 0x80) {
// Process the first UVR record
const response1 = this.readBlock(data, 0, LATEST_SIZE);
if (response1) {
const currentUvrRecord1 = this.parseUvrRecordFromBuffer(response1);
this.log.debug("UVR record created from binary record 1: " + JSON.stringify(currentUvrRecord1));
stateValuesArray.push(currentUvrRecord1);
// Check if there is a second UVR record
if (data.length >= 1 + LATEST_SIZE * 2) {
const response2 = this.readBlock(data, 1 + LATEST_SIZE, LATEST_SIZE);
if (response2) {
const currentUvrRecord2 = this.parseUvrRecordFromBuffer(response2);
this.log.debug("UVR record created from binary record 2: " + JSON.stringify(currentUvrRecord2));
stateValuesArray.push(currentUvrRecord2);
}
}
this.log.debug("fetchStateValuesFromDevice successful.");
return stateValuesArray; // Return the state values
}
// else: Invalid response
this.log.debug("Invalid response from device");
throw new Error("Invalid response from device");
} else {
// Unexpected response
this.log.debug("Unexpected data format");
this.logHexDump("fetchStateValuesFromDevice", data); // Log hex dump of the data
throw new Error("Unexpected data format");
}
} else {
// CMI selected
this.log.debug("fetchStateValuesFromDevice CMI for CAN node id: " + data_frame_index);
const data = await this.fetchJSONDataFromDevice(data_frame_index);
// Process the received data here
if (data.httpStatusCode === 200) {
// Process the first UVR record
const currentUvrJSONRecord = this.parseUvrRecordFromJSON(data.data);
this.log.debug("JS Record created from JSON response: " + JSON.stringify(currentUvrJSONRecord));
stateValuesArray.push(currentUvrJSONRecord);
this.log.debug("fetchStateValuesFromDevice successful.");
return stateValuesArray; // Return the state values
}
// else: Invalid response
this.log.debug("Invalid response from device");
throw new Error("Invalid response from device");
}
} catch (error) {
this.log.error("Error during communication with device: " + error);
throw error; // Re-throw the error to reject the promise
}
}
/**
* Fetches a data block from the device by sending a specified command.
* The method will retry up to a maximum number of attempts if the communication fails or if an invalid response is received.
*
* @param {Uint8Array} command - The command to be sent to the device.
* @returns {Promise<Buffer>} - A promise that resolves with the data received from the device, or rejects with an error if the maximum number of retries is reached.
* @throws {Error} - Throws an error if the maximum number of retries is reached without successful communication.
*/
async fetchDataBlockFromDevice(command) {
return new Promise((resolve, reject) => {
const maxRetries = 5; // Maximum number of retries
let attempt = 0; // Current attempt
const attemptFetch = async () => {
while (attempt < maxRetries) {
attempt++;
try {
const data = await this.sendCommand(command);
this.log.debug("Sent command as attempt: " + attempt);
if (data && data.length > 3) {
// Treat responses like "BA 02 BC" as invalid, infact 0x=02 means to retry after 2 seconds
resolve(data); // Successfully, exit the loop
// Log hex dump of the data
this.logHexDump("fetchDataBlockFromDevice", data);
return;
}
// else - ignore the non-expected short response
this.log.debug("Invalid short response from device");
// Log hex dump of the data
this.logHexDump("fetchDataBlockFromDevice", data);
} catch (error) {
this.log.error("Error during communication with device on attempt " + attempt + ": " + error);
if (attempt >= maxRetries) {
reject(new Error("Max retries reached. Unable to communicate with device."));
}
}
}
reject(new Error("Max retries reached. Unable to communicate with device."));
};
this.log.debug("Initiate attempt to fetch data block from BL-NET");
attemptFetch(); // Start with the first attempt
});
}
/**
* Fetches JSON data from a device with retry logic.
*
* @param {number} canNode - The CAN node to query.
* @returns {Promise<{data: object, httpStatusCode: number, httpStatusMessage: string, debug: string}>} A promise that resolves with the fetched data or rejects with an error.
* @throws {Error} If the maximum number of retries is reached.
*/
async fetchJSONDataFromDevice(canNode) {
return new Promise((resolve, reject) => {
const maxRetries = 5; // Maximum number of retries
let attempt = 0; // Current attempt
const attemptFetch = async () => {
while (attempt < maxRetries) {
attempt++;
let res = {
data: {},
httpStatusCode: -7,
httpStatusMessage: "",
debug: "",
};
try {
res = await this.sendHttpRequest(canNode); // Wait for the request to complete
resolve(res); // Successfully, exit the loop
return;
} catch (error) {
this.log.error("Error during communication with device on attempt " + attempt + ": " + error);
} // End of try-catch
// Log the res object for debugging purposes
this.log.debug("Response object on attempt " + attempt + ": " + JSON.stringify(res));
} // End of for loop
reject(new Error("Max retries reached. Unable to communicate with device."));
}; // End of attemptFetch
this.log.debug("Initiate attempt to fetch JSON data from CMI");
attemptFetch(); // Start with the first attempt
});
}
static CURRENT_DATA_UVR61_3 = {
IDENTIFIER: 0,
SENSORS: {
S01: [1, 2],
S02: [3, 4],
S03: [5, 6],
S04: [7, 8],
S05: [9, 10],
S06: [11, 12],
},
OUTPUTS: {
OUTPUT_BYTE1: 13,
},
SPEED_LEVELS: {
SPEED: 14,
},
ANALOG_OUTPUT: 15,
HEAT_METER: 16,
VOLTAGE_CURRENT: [17, 18],
SOLAR1: {
POWER: [19, 20],