-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcommon.js
332 lines (306 loc) · 8.78 KB
/
common.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
/*
MIT License Copyright 2021, 2024 - Bitpool Pty Ltd
*/
const { createLogger, format, transports } = require("winston");
const { randomUUID } = require("crypto");
const os = require("os");
const { exec } = require("child_process");
const baEnum = require("./resources/node-bacstack-ts/dist/index.js").enum;
const fs = require("fs");
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
) {
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);
}
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 doNodeRedRestart = function () {
return new Promise(function (resolve, reject) {
try {
exec("restart", (error, stdout, stderr) => {
if (error) {
console.log(`Node-Red restart error: ${error.message}`);
reject(error.message);
}
if (stderr) {
console.log(`Node-Red restart stderr: ${stderr}`);
reject(stderr);
}
resolve(stdout);
});
} catch (e) {
console.log(`Node-Red restart error: ${e}`);
reject(e);
}
});
};
// STORE CONFIG FUNCTION ==========================================================
//
// ================================================================================
async function Store_Config(data) {
try {
await fs.writeFile("edge-bacnet-datastore.cfg", data, { encoding: "utf8", flag: "w" }, (err) => {
if (err) {
console.log("Store_Config writeFile error: ", err);
}
});
} catch (e) {
//do nothing
}
}
// READ CONFIG SYNC FUNCTION ======================================================
//
// ================================================================================
function Read_Config_Sync() {
var data = "{}";
try {
data = fs.readFileSync("edge-bacnet-datastore.cfg", { encoding: "utf8", flag: "r" });
} catch (err) {
data = "{}";
Store_Config(data);
}
return data;
}
// STORE CONFIG FUNCTION - BACNET SERVER ==========================================
//
// ================================================================================
async function Store_Config_Server(data) {
try {
await fs.writeFile("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("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;
};
module.exports = {
BacnetConfig,
BacnetClientConfig,
ReadCommandConfig,
WriteCommandConfig,
getUnit,
generateId,
getIpAddress,
roundDecimalPlaces,
doNodeRedRestart,
Store_Config,
Read_Config_Sync,
Store_Config_Server,
Read_Config_Sync_Server,
isNumber,
decodeBitArray,
parseBacnetError,
getBacnetErrorString,
};