-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbacnet_client.js
More file actions
2514 lines (2264 loc) · 80.7 KB
/
Copy pathbacnet_client.js
File metadata and controls
2514 lines (2264 loc) · 80.7 KB
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
/*
MIT License Copyright 2021, 2024 - Bitpool Pty Ltd
*/
const bacnet = require("./resources/node-bacstack-ts/dist/index.js");
const baEnum = bacnet.enum;
const { EventEmitter } = require("events");
const {
getUnit,
roundDecimalPlaces,
parseBacnetError,
getBacnetErrorString,
Read_Config_Async,
isNumber,
decodeBitArray,
} = require("./common");
const { ToadScheduler, SimpleIntervalJob, Task } = require("toad-scheduler");
const { BacnetDevice } = require("./bacnet_device");
const { Mutex } = require("async-mutex");
const { treeBuilder } = require("./treeBuilder.js");
class BacnetClient extends EventEmitter {
//client constructor
constructor(config) {
super();
let that = this;
that.config = config;
that.deviceList = [];
that.networkTree = {};
that.renderList = [];
that.lastWhoIs = null;
that.client = null;
that.lastNetworkPoll = null;
that.scheduler = new ToadScheduler();
that.mutex = new Mutex();
that.manualMutex = new Mutex();
that.pollInProgress = false;
that.buildJsonInProgress = false;
that.cacheLoaded = false;
that.scanMatrix = [];
that.renderListCount = 0;
that.portRangeMatrix = config.portRangeMatrix;
that._requestQueue = []; // Queue of waiting request resolvers
that._processingQueue = false; // Flag to prevent concurrent queue processing
that._maxQueueSize = 10000; // Maximum queued requests before rejecting (sized for large sites)
try {
that.roundDecimal = config.roundDecimal;
that.apduSize = config.apduSize;
that.maxSegments = config.maxSegments;
that.discover_polling_schedule = config.discover_polling_schedule;
that.deviceId = config.deviceId;
that.broadCastAddr = config.broadCastAddr;
that.device_read_schedule = config.device_read_schedule;
that.deviceRetryCount = parseInt(config.retries);
that.sanitise_device_schedule = config.sanitise_device_schedule;
that.buildTreeException = false;
that.enable_device_discovery = config.enable_device_discovery;
that.readPropertyMultipleOptions = {
maxSegments: 112,
maxApdu: 5,
};
try {
that.readCachedFile();
that.client = new bacnet.Client({
apduTimeout: config.apduTimeout,
interface: config.localIpAdrress,
port: config.port,
broadcastAddress: config.broadCastAddr,
portRangeMatrix: config.portRangeMatrix,
maxConcurrentRequests: config.maxConcurrentRequests,
});
that.setMaxListeners(1);
const task = new Task("simple task", () => {
that.globalWhoIs();
});
const job = new SimpleIntervalJob({ seconds: parseInt(that.discover_polling_schedule) }, task);
that.scheduler.addSimpleIntervalJob(job);
//query device task
const queryDevices = new Task("simple task", () => {
if (!that.cacheLoaded) return;
if (!that.pollInProgress && that.enable_device_discovery) {
that.queryDevices();
}
if (!that.buildJsonInProgress && that.enable_device_discovery) {
that.buildJsonTree();
}
});
const queryJob = new SimpleIntervalJob({ seconds: parseInt(that.device_read_schedule) }, queryDevices);
that.scheduler.addSimpleIntervalJob(queryJob);
//buildNetworkTreeData task
const buildNetworkTree = new Task("simple task", () => {
that.doTreeBuilder();
that.countDevices();
});
const buildNetworkTreeJob = new SimpleIntervalJob({ seconds: 5 }, buildNetworkTree);
that.scheduler.addSimpleIntervalJob(buildNetworkTreeJob);
setTimeout(() => {
that.globalWhoIs();
setTimeout(() => {
if (!that.pollInProgress && that.enable_device_discovery) {
that.queryDevices();
}
if (!that.buildJsonInProgress && that.enable_device_discovery) {
that.buildJsonTree();
}
}, "4000");
}, "15000");
} catch (e) {
that.logOut("Issue initializing client: ", e);
}
try {
//who is callback
that.client.on("iAm", (device) => {
if (device.address !== that.config.localIpAdrress) {
if (that.scanMatrix.length > 0) {
let matrixMap = that.scanMatrix.filter((ele) => device.deviceId >= ele.start && device.deviceId <= ele.end);
if (matrixMap.length > 0) {
//only add unique device to array
let foundIndex = that.deviceList.findIndex((ele) => ele.getDeviceId() == device.deviceId);
if (foundIndex == -1) {
let newBacnetDevice = new BacnetDevice(false, device);
newBacnetDevice.setLastSeen(Date.now());
if (newBacnetDevice.getIsMstpDevice()) {
that.addToParentMstpNetwork(newBacnetDevice);
}
that.deviceList.push(newBacnetDevice);
that.addToNetworkTree(newBacnetDevice);
} else if (foundIndex !== -1) {
that.deviceList[foundIndex].updateDeviceConfig(device);
that.deviceList[foundIndex].setLastSeen(Date.now());
if (that.deviceList[foundIndex].getIsMstpDevice()) {
that.addToParentMstpNetwork(that.deviceList[foundIndex]);
}
that.addToNetworkTree(that.deviceList[foundIndex]);
}
//emit event for node-red to log
that.emit("deviceFound", device);
}
} else {
//only add unique device to array
let foundIndex = that.deviceList.findIndex((ele) => ele.getDeviceId() == device.deviceId);
if (foundIndex == -1) {
let newBacnetDevice = new BacnetDevice(false, device);
newBacnetDevice.setLastSeen(Date.now());
if (newBacnetDevice.getIsMstpDevice()) {
that.addToParentMstpNetwork(newBacnetDevice);
}
that.deviceList.push(newBacnetDevice);
that.addToNetworkTree(newBacnetDevice);
} else if (foundIndex !== -1) {
that.deviceList[foundIndex].updateDeviceConfig(device);
that.deviceList[foundIndex].setLastSeen(Date.now());
if (that.deviceList[foundIndex].getIsMstpDevice()) {
that.addToParentMstpNetwork(that.deviceList[foundIndex]);
}
that.addToNetworkTree(that.deviceList[foundIndex]);
}
//emit event for node-red to log
that.emit("deviceFound", device);
}
}
});
} catch (e) {
that.logOut("Issue with creating bacnet client, see error: ", e);
}
that.client.on("error", (err) => {
that.logOut("Error occurred: ", err);
if (err.errno == -4090) {
that.logOut("Invalid Client information or incorrect IP address provided");
} else if (err.errno == -49) {
that.logOut("Invalid IP address provided");
} else {
that.reinitializeClient(that.config);
}
});
} catch (e) {
console.log("BACnet Client client binder error: ", e);
}
}
/**
* Waits until a request slot is available (throttling).
* Uses a queue to ensure only one waiter proceeds per available slot.
* Rejects if the queue is full (backpressure mechanism).
*
* The previous implementation used a `while` loop inside `processQueue` which
* called `nextResolve()` multiple times synchronously. Because Promise
* resolutions are scheduled as microtasks, none of those continuations ran
* before the next `canSendRequest()` check — so the while-loop could release
* dozens of waiters simultaneously even when only one slot was free. The fix
* is to release exactly ONE waiter per `requestComplete` event, letting the
* microtask queue drain before the next slot check.
*/
_waitForRequestSlot() {
let that = this;
return new Promise((resolve, reject) => {
// Fast path: a slot is available right now
if (that.client.canSendRequest()) {
resolve();
return;
}
// Backpressure: refuse to queue more work than the limit allows
if (that._requestQueue.length >= that._maxQueueSize) {
reject(new Error('ERR_REQUEST_QUEUE_FULL: Too many pending requests. Reduce polling frequency or increase Max Concurrent Requests.'));
return;
}
// Park this request until a slot opens
that._requestQueue.push(resolve);
if (!that._processingQueue) {
that._processingQueue = true;
const processQueue = () => {
// Release exactly ONE waiter per call. The 'requestComplete' event
// fires each time a slot is freed, so we will naturally be called
// again once the released request registers its own callback in the
// invoke store and eventually completes.
if (that._requestQueue.length > 0 && that.client.canSendRequest()) {
const nextResolve = that._requestQueue.shift();
nextResolve();
}
if (that._requestQueue.length === 0) {
that._processingQueue = false;
that.client.removeListener('requestComplete', processQueue);
}
};
that.client.on('requestComplete', processQueue);
}
});
}
async readCachedFile() {
let that = this;
try {
if (that.config.cacheFileEnabled) {
const cachedData = await Read_Config_Async();
const parsedData = JSON.parse(cachedData);
if (parsedData && typeof parsedData == "object") {
// renderList is no longer cached - will be rebuilt by tree builder
// if (parsedData.renderList) that.renderList = parsedData.renderList;
if (parsedData.deviceList) {
parsedData.deviceList.forEach(function (device) {
let newBacnetDevice = new BacnetDevice(true, device);
that.deviceList.push(newBacnetDevice);
});
}
if (parsedData.pointList) that.networkTree = parsedData.pointList;
// renderListCount is no longer cached - will be recalculated by tree builder
// if (parsedData.renderListCount) that.renderListCount = parsedData.renderListCount;
}
}
} finally {
that.cacheLoaded = true;
}
}
testFunction(address, port, type, instance, property, nodeWarnCallback) {
let that = this;
console.log("test function ");
let addressObject = {
address: address,
port: port,
};
// Try to find the device to use device-specific options
let device = null;
if (type === 8) {
// Device object - instance is the device ID
device = that.deviceList.find(ele => ele.getDeviceId() === instance);
} else {
// For non-device objects, we can't determine the device from just address/instance
// This is a limitation of testFunction's current signature
}
// Use device-specific options if we found the device, otherwise use safer defaults
let readOptions;
if (device) {
readOptions = that.getDeviceSpecificOptions(device);
} else {
// Conservative defaults for unknown devices (assume small MSTP)
readOptions = {
maxSegments: 0, // No segmentation
maxApdu: 2 // 206 octets - safe for most MSTP devices
};
}
const propertiesArray = [{ objectId: { type: type, instance: instance }, properties: [{ id: property }] }];
that.client.readPropertyMultiple(addressObject, propertiesArray, readOptions, (err, value) => {
console.log("1 - readPropertyMultiple: ");
console.log(value);
if (nodeWarnCallback) {
nodeWarnCallback(value);
}
if (value) {
// If the result has value, resolve the promise
console.log(value.values[0]);
value.values[0].values.forEach(function (value) {
console.log("value: ", value.value);
});
} else {
console.log(err);
}
});
that.client.readProperty(
addressObject,
{ type: type, instance: instance },
property,
readOptions,
(err, value) => {
console.log("2 - readProperty: ");
console.log(value);
if (value) {
// If the result has value, resolve the promise
console.log(value.values[0]);
value.values[0].values.forEach(function (value) {
console.log("value: ", value.value);
});
} else {
console.log(err);
}
}
);
}
addToNetworkTree(device) {
let that = this;
try {
const deviceKey = that.createDeviceKey(device);
let deviceName = device.getDeviceName();
if (deviceName !== null) {
const deviceId = device.getDeviceId();
if (deviceId !== null) {
let lastIndex = deviceName.lastIndexOf(deviceId);
if (lastIndex) {
let formattedName = deviceName.substring(0, lastIndex);
formattedName = `${formattedName.trim()}_Device_${deviceId}`;
if (
that.networkTree[deviceKey][formattedName] &&
Object.keys(that.networkTree[deviceKey][formattedName]).length > 0
) {
delete that.networkTree[deviceKey]["device"];
}
}
}
} else {
const json = {
objectId: {
type: 8,
instance: device.getDeviceId(),
},
};
if (that.networkTree[deviceKey] && that.networkTree[deviceKey]["device"]) {
that.networkTree[deviceKey]["device"]["meta"] = json;
} else {
that.networkTree[deviceKey] = {
device: {
meta: json,
},
};
}
}
} catch (e) {
that.logOut("addToNetworkTree error: ", e);
}
}
async getProtocolSupported(device) {
//return protocols support for device
let that = this;
let addressObject = {
address: device.getAddress(),
port: device.getPort(),
};
const readOptions = that.getDeviceSpecificOptions(device);
// Wait for a request slot before proceeding
await that._waitForRequestSlot();
return new Promise((resolve, reject) => {
that.client.readProperty(
addressObject,
{ type: baEnum.ObjectType.DEVICE, instance: device.getDeviceId() },
baEnum.PropertyIdentifier.PROTOCOL_SERVICES_SUPPORTED,
readOptions,
(err, value) => {
if (err) {
reject(err);
}
if (value) {
resolve(value);
}
}
);
});
}
addToParentMstpNetwork(device) {
let that = this;
let address = device.getAddress().address;
let deviceId = device.getDeviceId();
let foundParentIndex = that.deviceList.findIndex((ele) => that.getDeviceAddress(ele) == address && !ele.getIsMstpDevice());
if (foundParentIndex !== -1) {
that.deviceList[foundParentIndex].addChildDevice(deviceId);
device.setParentDeviceId(that.deviceList[foundParentIndex].getDeviceId());
}
}
logOut(param1, param2) {
let that = this;
that.emit("bacnetErrorLog", param1, param2);
}
rebuildDataModel() {
let that = this;
return new Promise((resolve, reject) => {
try {
that.deviceList = [];
that.renderList = [];
that.networkTree = {};
that.pollInProgress = false;
that.buildJsonInProgress = false;
that.renderListCount = 0;
resolve(true);
} catch (e) {
that.logOut("Error clearing BACnet data model: ", e);
reject(e);
}
});
}
purgeDevice(device) {
let that = this;
return new Promise((resolve, reject) => {
try {
let renderListIndex = that.renderList.findIndex((ele) => ele.deviceId == device.deviceId && ele.ipAddr == device.address);
let deviceListIndex = that.deviceList.findIndex((ele) => ele.getDeviceId() == device.deviceId);
let deviceKey = device.address + "-" + device.deviceId;
delete that.networkTree[deviceKey];
that.renderList.splice(renderListIndex, 1);
that.deviceList.splice(deviceListIndex, 1);
that.countDevices();
resolve(true);
} catch (e) {
reject(e);
}
});
}
forceUpdateDevices(deviceArray) {
let that = this;
try {
deviceArray.forEach(async function (deviceId) {
let device = that.deviceList.find((ele) => ele.getDeviceId() === deviceId);
if (device) {
await that.buildJsonObject(device);
}
});
} catch (e) {
that.logOut("forceUpdateDevices error: ", e);
}
}
async updatePointsForDevice(deviceObject) {
try {
let device = this.deviceList.find((ele) => ele.getDeviceId() === deviceObject.deviceId);
if (!device) {
throw new Error(`Device with ID ${deviceObject.deviceId} not found`);
}
await this.updateDeviceName(device);
if (!device.getIsProtocolServicesSet()) {
try {
const result = await this.getProtocolSupported(device);
const decodedValues = decodeBitArray(8, result.values[0].originalBitString.value);
device.setProtocolServicesSupported(decodedValues);
} catch (error) {
this.logOut("getProtocolSupported error: ", error);
}
}
try {
await this.getDevicePointList(device);
await this.buildJsonObject(device);
} catch (e) {
this.logOut(`Update points list error 2: ${this.getDeviceAddress(device)}`, e);
device.setManualDiscoveryMode(true);
try {
await this.getDevicePointListWithoutObjectList(device);
await this.buildJsonObject(device);
} catch (e) {
await this.buildJsonObject(device);
this.logOut(`Update points list error 4: ${this.getDeviceAddress(device)}`, e);
}
}
return true;
} catch (e) {
this.logOut(`Error in updatePointsForDevice: ${e.message}`, e);
throw e; // Re-throw the error to be handled by the caller
}
}
applyDisplayNames(pointsToRead) {
let that = this;
return new Promise((resolve, reject) => {
try {
for (let key in pointsToRead) {
let deviceModel = that.findDeviceByKey(key);
let device = pointsToRead[key];
for (let pointName in device) {
let pointObject = device[pointName];
if (pointName == "deviceName") {
deviceModel.setDisplayName(pointObject);
}
if (that.networkTree[key][pointName]) {
that.networkTree[key][pointName] = pointObject;
}
}
}
resolve(true);
} catch (e) {
that.logOut("applyDisplayNames error: ", e);
reject(e);
}
});
}
setDeviceDisplayName(deviceObject, displayName) {
let that = this;
return new Promise((resolve, reject) => {
try {
let address = "";
if (typeof deviceObject.address == "string") {
address = deviceObject.address;
} else if (typeof deviceObject.address == "object") {
address = deviceObject.address.address;
}
let device = that.deviceList.find(
(ele) => that.getDeviceAddress(ele) == address && ele.getDeviceId() == deviceObject.deviceId
);
device.setDisplayName(displayName);
that.buildTreeException = true;
resolve(true);
} catch (e) {
that.logOut("setDeviceDisplayName error: ", e);
reject(e);
}
});
}
setPointDisplayName(deviceKey, pointName, pointDisplayName) {
let that = this;
return new Promise((resolve, reject) => {
try {
if (that.networkTree[deviceKey][pointName]) {
that.networkTree[deviceKey][pointName].displayName = pointDisplayName;
}
that.buildTreeException = true;
resolve(true);
} catch (e) {
that.logOut("setPointDisplayName error: ", e);
reject(e);
}
});
}
importReadList(payload) {
let that = this;
return new Promise((resolve, reject) => {
try {
that.buildTreeException = true;
for (let key in payload) {
let device = payload[key];
for (let pointName in device) {
let pointObject = device[pointName];
if (that.networkTree[key][pointName]) {
that.networkTree[key][pointName] = pointObject;
}
}
}
resolve(true);
} catch (e) {
that.logOut("importReadList error: ", e);
reject(e);
}
});
}
async queryDevices() {
let that = this;
try {
that.pollInProgress = true;
let index = 0;
await query(index);
async function query(index) {
if (index < that.deviceList.length) {
let device = that.deviceList[index];
if (typeof device == "object" && (device.getIsDumbMstpRouter() == false || device.getIsDumbMstpRouter() == undefined)) {
if (device.getIsProtocolServicesSet() == false) {
try {
let result = await that.getProtocolSupported(device);
let decodedValues = decodeBitArray(8, result.values[0].originalBitString.value);
device.setProtocolServicesSupported(decodedValues);
} catch (error) {
that.logOut("getProtocolSupported error: ", error);
index++;
await query(index);
}
}
try {
await that.updateDeviceName(device);
if (device.getSegmentation() !== 3) {
try {
await that.getDevicePointList(device);
index++;
await query(index);
} catch (e) {
that.logOut(`getDevicePointList error: ${device.getAddress()}`, e);
index++;
await query(index);
}
} else if (device.getSegmentation() == 3) {
try {
await that.getDevicePointListWithoutObjectList(device);
index++;
await query(index);
} catch (e) {
that.logOut(`getDevicePointList error: ${device.getAddress()}`, e);
index++;
await query(index);
}
}
} catch (e) {
that.logOut("Error while querying devices: ", e);
index++;
await query(index);
}
} else {
index++;
await query(index);
}
} else if (index == that.deviceList.length) {
that.pollInProgress = false;
}
}
} catch (e) {
that.logOut("Error while querying devices: ", e);
}
}
async updateDeviceName(device) {
try {
const deviceObject = await this._getDeviceName(device);
if (typeof deviceObject?.name === "string") {
device.setDeviceName(deviceObject.name + " " + device.getDeviceId());
device.setPointsList(deviceObject.devicePointEntry);
}
} catch (e) {
this.logOut("updateDeviceName error: ", e);
}
}
reinitializeClient(config) {
let that = this;
that.config = config;
that.roundDecimal = config.roundDecimal;
that.apduSize = config.apduSize;
that.maxSegments = config.maxSegments;
that.discover_polling_schedule = config.discover_polling_schedule;
that.deviceId = config.deviceId;
that.broadCastAddr = config.broadCastAddr;
that.device_read_schedule = config.device_read_schedule;
that.enable_device_discovery = config.enable_device_discovery;
if (that.scheduler !== null) {
that.scheduler.stop();
}
try {
that.client._settings.apduTimeout = config.apduTimeout;
that.client._settings.interface = config.localIpAdrress;
that.client._settings.port = config.port;
that.client._settings.broadcastAddress = config.broadCastAddr;
that.client._transport.interface = config.localIpAdrress;
that.client._transport.port = config.port;
that.client._transport.broadcastAddress = config.broadCastAddr;
const task = new Task("simple task", () => {
that.globalWhoIs();
});
const job = new SimpleIntervalJob({ seconds: parseInt(config.discover_polling_schedule) }, task);
that.scheduler.addSimpleIntervalJob(job);
// //query device task
const queryDevices = new Task("simple task", () => {
if (!that.cacheLoaded) return;
if (!that.pollInProgress && that.enable_device_discovery) {
that.queryDevices();
}
if (!that.buildJsonInProgress && that.enable_device_discovery) {
that.buildJsonTree();
}
});
const queryJob = new SimpleIntervalJob({ seconds: parseInt(config.device_read_schedule) }, queryDevices);
that.scheduler.addSimpleIntervalJob(queryJob);
//buildNetworkTreeData task
const buildNetworkTree = new Task("simple task", () => {
that.doTreeBuilder();
that.countDevices();
});
const buildNetworkTreeJob = new SimpleIntervalJob({ seconds: 10 }, buildNetworkTree);
that.scheduler.addSimpleIntervalJob(buildNetworkTreeJob);
} catch (e) {
that.logOut("Error reinitializing bacnet client: ", e);
}
}
getValidPointProperties(point, requestedProps) {
let that = this;
let availableProps = point.propertyList;
let newProps = [];
try {
requestedProps.forEach(function (prop) {
let foundInAvailable = availableProps.find((ele) => ele === prop.id);
if (foundInAvailable) newProps.push(prop);
});
//add object name for use in formatting
newProps.push({ id: baEnum.PropertyIdentifier.OBJECT_NAME });
} catch (e) {
that.logOut("Issue finding valid object properties, see error: ", e);
}
return newProps;
}
findDeviceByKey(key) {
let that = this;
return that.deviceList.find((ele) => `${that.getDeviceAddress(ele)}-${ele.getDeviceId()}` === key);
}
getObjectId(pointName, pointConfig, that) {
// Retrieve the object type based on the point configuration
const bacObjType = that.getObjectType(pointConfig.meta.objectId.type);
// Construct the object ID string
return `${pointName}_${bacObjType}_${pointConfig.meta.objectId.instance}`;
}
createDeviceKey(device) {
// Create a device key by combining the address and device ID
const address = device.getAddress();
const deviceId = device.getDeviceId();
if (typeof address === "object") {
return `${address.address}-${deviceId}`;
} else {
return `${address}-${deviceId}`;
}
}
async doRead(readConfig, outputType, objectPropertyType, readNodeName) {
const that = this;
const roundDecimal = readConfig.precision;
const devicesToRead = Object.keys(readConfig.pointsToRead);
let completedDevices = 0;
try {
// Create array of device processing promises
const devicePromises = devicesToRead.map(async (key, deviceIndex) => {
const device = that.findDeviceByKey(key);
if (!device) return null;
const deviceName = that.computeDeviceName(device);
const deviceKey = that.createDeviceKey(device);
const deviceObject = that.networkTree[deviceKey];
const maxObjectCount = that.estimateMaxObjectSize(device.getMaxApdu());
const bacnetResults = {};
bacnetResults[deviceName] = {};
// Process points for the current device
const pointsToRead = readConfig.pointsToRead[key];
const pointNames = Object.keys(pointsToRead);
let totalPoints = pointNames.length - 1;
let requestArray = [];
// Process each point for the device in batches
for (let i = 0; i < pointNames.length; i++) {
const pointName = pointNames[i];
if (pointName === "deviceName") {
continue;
}
const pointConfig = pointsToRead[pointName];
const objectId = that.getObjectId(pointName, pointConfig, that);
const point = deviceObject[objectId];
if (point) {
point.displayName = pointConfig.displayName;
// Prepare request array for batch processing
requestArray.push({
objectId: { type: point.meta.objectId.type, instance: point.meta.objectId.instance },
properties: [{ id: baEnum.PropertyIdentifier.PRESENT_VALUE }],
pointRef: point,
pointName: pointName,
});
}
// Process the batch when the request array is full or the last point is reached
if (requestArray.length === maxObjectCount || i === pointNames.length - 1) {
if (device.getProtocolServiceSupport("ReadPropertyMultiple") == true) {
await that.processBatch(device, requestArray, deviceName, bacnetResults, that, roundDecimal);
} else {
await that.processIndividualPoints(device, requestArray, deviceName, bacnetResults, that, roundDecimal);
}
requestArray = [];
}
}
// Return results for this device
return {
deviceName,
results: bacnetResults,
deviceIndex: deviceIndex + 1,
totalDevices: devicesToRead.length,
};
});
// Process all devices in parallel and emit results as they complete
const results = await Promise.allSettled(devicePromises);
results.forEach((result, index) => {
if (result.status === "fulfilled" && result.value) {
completedDevices++;
const { deviceName, results: bacnetResults, deviceIndex, totalDevices } = result.value;
// Emit the `values` event for this device immediately
that.emit("values", bacnetResults, outputType, objectPropertyType, readNodeName, completedDevices, totalDevices);
} else {
// Handle failed device (offline/error)
completedDevices++;
that.logOut(`Device ${devicesToRead[index]} failed:`, result.reason);
}
});
} catch (error) {
that.logOut("doRead error: ", error);
}
}
async processBatch(device, requestArray, deviceName, bacnetResults, that, roundDecimal) {
try {
const results = await that.updateManyPoints(device, requestArray);
if (results.error) {
throw results.error;
}
let deviceMetaInfo = {
address: device.getAddress(),
isMstp: device.getIsMstpDevice(),
deviceId: device.getDeviceId(),
vendorId: device.getVendorId(),
deviceName: deviceName,
};
// Process the results of the batch
results.value.values.forEach((pointResult, index) => {
const cacheRef = requestArray[index];
const pointRef = cacheRef.pointRef;
const pointNameRef = cacheRef.pointName;
if (pointResult.values[0].value.length > 0) {
const val = pointResult.values[0].value[0].value;
if (isNumber(val)) {
pointRef.presentValue = roundDecimalPlaces(val, roundDecimal);
pointRef.error = "none";
pointRef.status = "online";
if (pointRef.meta.objectId.type == 19 || pointRef.meta.objectId.type == 13 || pointRef.meta.objectId.type == 14) {
if (pointRef.stateTextArray && typeof pointRef.stateTextArray[0].value !== "object") {
if (val != 0) {
pointRef.presentValue = pointRef.stateTextArray[val - 1].value;
} else {
pointRef.presentValue = pointRef.stateTextArray[val].value;
}
}
}
} else {
if (typeof val !== "object") {
pointRef.presentValue = val;
pointRef.error = "none";
pointRef.status = "online";
} else if (val.errorClass && val.errorClass) {
pointRef.error = getBacnetErrorString(val.errorClass, val.errorClass);
pointRef.status = "offline";
} else {
pointRef.error = "none";
pointRef.status = "online";
}
}
}
pointRef.meta["device"] = deviceMetaInfo;
pointRef.timestamp = Date.now();
// Store the point data in results
bacnetResults[deviceName][pointNameRef] = pointRef;
});
} catch (err) {
that.logOut("Error processing batch:", err);
await that.processIndividualPoints(device, requestArray, deviceName, bacnetResults, that, roundDecimal);
}
}
async processIndividualPoints(device, requestArray, deviceName, bacnetResults, that, roundDecimal) {
let deviceMetaInfo = {
address: device.getAddress(),
isMstp: device.getIsMstpDevice(),
deviceId: device.getDeviceId(),
vendorId: device.getVendorId(),
deviceName: deviceName,
};
for (const request of requestArray) {
const { objectId, pointRef, pointName } = request;
try {
const result = await that.updatePoint(device, pointRef);
if (result.objectId.type == objectId.type && result.objectId.instance == objectId.instance) {
const val = result.values[0].value;
if (isNumber(val)) {
pointRef.presentValue = roundDecimalPlaces(val, roundDecimal);
pointRef.error = "none";
pointRef.status = "online";
if (pointRef.meta.objectId.type == 19 || pointRef.meta.objectId.type == 13 || pointRef.meta.objectId.type == 14) {
if (pointRef.stateTextArray && typeof pointRef.stateTextArray[0].value !== "object") {
if (val != 0) {
pointRef.presentValue = pointRef.stateTextArray[val - 1].value;
} else {
pointRef.presentValue = pointRef.stateTextArray[val].value;
}