-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcommon.js
More file actions
443 lines (393 loc) · 12 KB
/
Copy pathcommon.js
File metadata and controls
443 lines (393 loc) · 12 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
/*
MIT License Copyright 2021, 2025 - Bitpool Pty Ltd
*/
const { randomUUID } = require("crypto");
const os = require("os");
const path = require("path");
const baEnum = require("./resources/node-bacstack-ts/dist/index.js").enum;
const fs = require("fs");
const fs2 = require("fs").promises;
class BacnetConfig {
constructor(
device,
objects,
bacnet_polling_schedule,
apduTimeout,
localIpAdrress,
roundDecimal,
local_device_port,
apduSize,
maxSegments,
broadCastAddr
) {
this.device = {
deviceId: device.deviceId,
address: device.address,
};
this.polling = {
schedule: bacnet_polling_schedule,
};
this.objects = [
{
objectId: {
type: objects.object_type,
instance: objects.instance,
properties: objects.object_props,
},
},
];
this.apduTimeout = apduTimeout;
this.localIpAdrress = localIpAdrress;
this.roundDecimal = roundDecimal;
this.port = local_device_port;
this.apduSize = apduSize;
this.maxSegments = maxSegments;
this.broadCastAddr = broadCastAddr;
}
}
class BacnetClientConfig {
constructor(
apduTimeout,
localIpAdrress,
local_device_port,
apduSize,
maxSegments,
broadCastAddr,
discover_polling_schedule,
toRestartNodeRed,
deviceId,
manual_instance_range_enabled,
manual_instance_range_start,
manual_instance_range_end,
device_read_schedule,
retries,
cacheFileEnabled,
sanitise_device_schedule,
portRangeMatrix,
enable_device_discovery,
maxConcurrentRequests
) {
this.apduTimeout = apduTimeout;
this.localIpAdrress = localIpAdrress;
this.port = local_device_port;
this.apduSize = apduSize;
this.maxSegments = maxSegments;
this.broadCastAddr = broadCastAddr;
this.discover_polling_schedule = discover_polling_schedule;
this.toRestartNodeRed = toRestartNodeRed;
this.deviceId = deviceId;
this.manual_instance_range_enabled = manual_instance_range_enabled;
this.manual_instance_range_start = manual_instance_range_start;
this.manual_instance_range_end = manual_instance_range_end;
this.device_read_schedule = device_read_schedule;
this.retries = retries;
this.cacheFileEnabled = cacheFileEnabled;
this.sanitise_device_schedule = sanitise_device_schedule;
this.portRangeMatrix = this.generatePortRangeArray(portRangeMatrix);
this.enable_device_discovery = enable_device_discovery;
// Clamp maxConcurrentRequests between 1 and 250
// BACnet protocol limits invoke IDs to 256, so 250 is the safe maximum
let clampedMaxConcurrent = parseInt(maxConcurrentRequests) || 250;
if (clampedMaxConcurrent < 1) clampedMaxConcurrent = 1;
if (clampedMaxConcurrent > 250) clampedMaxConcurrent = 250;
this.maxConcurrentRequests = clampedMaxConcurrent;
}
generatePortRangeArray(rangeMatrix) {
let portArray = [];
for (let x = 0; x < rangeMatrix.length; x++) {
let rangeEntry = rangeMatrix[x];
let start = parseInt(rangeEntry.start);
let end = parseInt(rangeEntry.end);
for (let i = start; i <= end; i++) {
portArray.push(i);
}
}
return portArray;
}
}
class ReadCommandConfig {
constructor(pointsToRead, objectProperties, decimalPrecision) {
this.pointsToRead = pointsToRead;
this.objectProperties = objectProperties;
this.precision = decimalPrecision;
}
}
class WriteCommandConfig {
constructor(device, objects) {
this.device = {
deviceId: device.deviceId,
address: device.address,
};
this.objects = [
{
objectId: {
type: objects.object_type,
instance: objects.instance,
properties: objects.object_props,
},
},
];
}
}
const getUnit = function (id) {
for (var key in baEnum.EngineeringUnits) {
if (baEnum.EngineeringUnits[key] == id) {
if (baEnum.EngineeringUnits.hasOwnProperty(key)) {
let unitsArr = key.split("_");
let unit;
unitsArr.forEach((ele, index) => {
if (index == 0) {
unit = ele.toLowerCase();
} else {
unit += "-" + ele.toLowerCase();
}
});
return unit;
}
}
}
return "no-units";
};
const generateId = function () {
return randomUUID();
};
const getIpAddress = function () {
return new Promise(function (resolve, reject) {
const nets = os.networkInterfaces();
const results = Object.create(null); // Or just '{}', an empty object
for (const name of Object.keys(nets)) {
for (const net of nets[name]) {
// Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
let family = parseInt(net.family.toString().match(/[0-9]/));
if (family === 4 && !net.internal) {
if (!results[name]) {
results[name] = [];
}
results[name].push(net.address);
}
}
}
if (os.version().includes("Ubuntu") || os.version().includes("SMP")) {
let allInterfaceName = "All interfaces";
if (!results[allInterfaceName]) {
results[allInterfaceName] = [];
}
results[allInterfaceName].push("0.0.0.0");
} else if (os.version().includes("Windows")) {
//do nothing
}
resolve(results);
});
};
const roundDecimalPlaces = function (value, decimals) {
if (decimals) return Number(Math.round(value + "e" + decimals) + "e-" + decimals);
return value;
};
const getStoragePath = (fileName) => {
const storagePath = process.env.BACNET_STORAGE_PATH;
if (storagePath) {
if (!fs.existsSync(storagePath)) {
fs.mkdirSync(storagePath, { recursive: true });
}
return path.join(storagePath, fileName);
}
return fileName;
};
let storeQueue = [];
let isStoreProcessing = false;
async function queueConfigStore(data) {
storeQueue.push(data);
if (!isStoreProcessing) {
isStoreProcessing = true;
while (storeQueue.length > 0) {
const nextData = storeQueue.pop(); // Get most recent data
storeQueue.length = 0; // Clear any accumulated data
await Store_Config(nextData);
// Add small delay between attempts
await new Promise((resolve) => setTimeout(resolve, 100));
}
isStoreProcessing = false;
}
}
async function Store_Config(data) {
const mainFile = getStoragePath("edge-bacnet-datastore.cfg");
const tempFile = getStoragePath("edge-bacnet-datastore.cfg.tmp");
const backupFile = getStoragePath("edge-bacnet-datastore.cfg.bak");
try {
// First validate the JSON to ensure it's valid before writing
try {
JSON.parse(JSON.stringify(data));
} catch (jsonError) {
console.error("Invalid JSON data detected:", jsonError);
return false;
}
// Write to temporary file first
await fs2.writeFile(tempFile, JSON.stringify(data, null, 2), { encoding: "utf8" });
// Verify the temporary file is valid JSON
try {
const tempContent = await fs2.readFile(tempFile, "utf8");
JSON.parse(tempContent);
} catch (verifyError) {
console.error("Temporary file validation failed:", verifyError);
await fs2.unlink(tempFile).catch(() => { });
return false;
}
// Create backup of current file if it exists
try {
await fs2.access(mainFile);
await fs2.copyFile(mainFile, backupFile);
} catch (backupError) {
// If main file doesn't exist, no backup needed
}
// Atomic rename of temporary file to main file
await fs2.rename(tempFile, mainFile);
return true;
} catch (error) {
console.error("Store_Config error:", error);
// Cleanup temporary file if it exists
try {
await fs2.unlink(tempFile).catch(() => { });
} catch (cleanupError) { }
// If main file is corrupted and backup exists, restore from backup
try {
const backupExists = await fs2.access(backupFile).catch(() => false);
if (backupExists) {
await fs2.copyFile(backupFile, mainFile);
console.log("Restored from backup file");
}
} catch (restoreError) {
console.error("Failed to restore from backup:", restoreError);
}
return false;
}
}
async function Read_Config_Async() {
// todo rename function, not using sync
const mainFile = getStoragePath("edge-bacnet-datastore.cfg");
const backupFile = getStoragePath("edge-bacnet-datastore.cfg.bak");
const defaultData = "{}";
try {
// Try to read the main file
const data = await fs2.readFile(mainFile, { encoding: "utf8" });
// Validate JSON
try {
JSON.parse(data);
return data;
} catch (jsonError) {
console.error("Main file contains invalid JSON, attempting backup recovery");
// Try to read backup file
try {
const backupData = await fs2.readFile(backupFile, { encoding: "utf8" });
JSON.parse(backupData); // Validate backup JSON
// Restore from backup
await fs.copyFile(backupFile, mainFile);
console.log("Successfully restored from backup file");
return backupData;
} catch (backupError) {
console.error("Backup recovery failed, creating new file");
await Store_Config(defaultData);
return defaultData;
}
}
} catch (error) {
console.error("Error reading config:", error);
await Store_Config(defaultData);
return defaultData;
}
}
// STORE CONFIG FUNCTION - BACNET SERVER ==========================================
//
// ================================================================================
async function Store_Config_Server(data) {
try {
await fs.writeFile(getStoragePath("edge-bacnet-server-datastore.cfg"), data, (err) => {
if (err) {
//console.log("Store_Config_Server writeFile error: ", err);
}
});
} catch (err) { }
}
// READ CONFIG SYNC FUNCTION - BACNET SERVER ======================================
//
// ================================================================================
function Read_Config_Sync_Server() {
var data = "{}";
try {
data = fs.readFileSync(getStoragePath("edge-bacnet-server-datastore.cfg"), { encoding: "utf8", flag: "r" });
} catch (err) {
if (err.errno == -4058) {
data = "{}";
Store_Config_Server(data);
}
}
return data;
}
function isNumber(value) {
return value != null && typeof value === "number" && !isNaN(value);
}
function decodeBitArray(size, bits) {
let array = [];
for (let i = 0; i < bits.length; i++) {
let bit = bits[i];
let bitString = bit.toString(2);
if (bitString.length < size) {
const remainingLength = size - bitString.length;
const backFillString = "0".repeat(remainingLength);
array.push(backFillString + bitString);
} else if (bitString.length == size) {
array.push(bitString);
}
if (i == bits.length - 1) {
return array;
}
}
}
function getBacnetErrorString(classInt, codeInt) {
const classString = Object.keys(baEnum.ErrorClass).find((key) => baEnum.ErrorClass[key] === classInt);
const codeString = Object.keys(baEnum.ErrorCode).find((key) => baEnum.ErrorCode[key] === codeInt);
return `BacnetError - Class:${classString} - Code:${codeString}`;
}
function parseBacnetError(error) {
let err = error.message;
if (err.includes("Class") && err.includes("Code")) {
const match = err.match(/Class:(\d+) - Code:(\d+)/);
if (match) {
err = getBacnetErrorString(parseInt(match[1], 10), parseInt(match[2], 10));
}
} else if (err.includes("ERR_TIMEOUT")) {
err = "Request TIMEOUT";
}
return err;
}
function debounce(func, wait) {
let timeout;
return function (...args) {
const context = this;
// Clear the previous timeout
clearTimeout(timeout);
// Set a new timeout
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
}
module.exports = {
BacnetConfig,
BacnetClientConfig,
ReadCommandConfig,
WriteCommandConfig,
getUnit,
generateId,
getIpAddress,
roundDecimalPlaces,
queueConfigStore,
Store_Config,
Read_Config_Async,
Store_Config_Server,
Read_Config_Sync_Server,
isNumber,
decodeBitArray,
parseBacnetError,
getBacnetErrorString,
debounce,
};