@ncd-io/node-red-enterprise-sensors 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.gitattributes ADDED
@@ -0,0 +1,2 @@
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 io-Jacob
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # NCD-RED-Enterprise
2
+
3
+ To install navigate inside .node-red directory on a computer with Node-Red already installed. Then run command npm install ncd-red-enerprise-sensors. To update run command npm update ncd-red-enerprise-sensors.
4
+
5
+ Standard install commands:
6
+ * cd ~/.node-red
7
+ * npm install ncd-red-enterprise-sensors
8
+
9
+ Standard update commands:
10
+ * cd ~/.node-red
11
+ * npm update ncd-red-enterprise-sensors
12
+
13
+ This library handles communication to, and configuration of, the [NCD Wireless Sensor Line](https://ncd.io/wireless-enterprise-line/). It can be used in [conjunction with Node-RED](https://ncd.io/node-red-wireless-sensors/) to create and manage a Wireless Sensor Network using the Node-RED flow-based development tool on any platform. For specific examples of different sensor types using this package, check out the resources tab of the [appropriate product page](https://store.ncd.io/?fwp_main_facet=enterprise-solutions). If you cannot find an example, or need further assistance, check out the [Node-RED section of our forum](https://community.ncd.io/c/node-red).
package/index.js ADDED
@@ -0,0 +1,9 @@
1
+ process.on('unhandledRejection', (reason, p) => {
2
+ console.log({'Unhandled Rejection at': p, reason: reason});
3
+ // application specific logging, throwing an error, or other logic here
4
+ });
5
+
6
+ module.exports = {
7
+ Modem: require("./lib/DigiParser.js"),
8
+ Gateway: require("./lib/WirelessGateway.js")
9
+ }
@@ -0,0 +1,357 @@
1
+ const events = require("events");
2
+ module.exports = class DigiComm{
3
+ constructor(serial){
4
+ this.serial = serial;
5
+ this._emitter = new events.EventEmitter();
6
+ this.temp = [];
7
+ this._idCount = 0;
8
+ this._timoutLimit = 5000;
9
+ this.report_rssi = false;
10
+ var that = this;
11
+ function receive(d){
12
+ that.dataIn(d);
13
+ }
14
+ this.serial.on('data', receive);
15
+ this.serial.on('error', (err) => {
16
+ console.log(err);
17
+ });
18
+ this.on('close', () => {
19
+ that._emitter.removeListener('data', receive);
20
+ });
21
+ this.send = new outgoingFrame(this);
22
+ this.frame = new incomingFrame(this);
23
+ this.lastSent = [];
24
+ // this.modem_mac = this.send.at_command('SL');
25
+ }
26
+ close(){
27
+ this._emitter.emit('close');
28
+ }
29
+ getId(){
30
+ if(this._idCount == 255) this._idCount = 0;
31
+ return ++this._idCount;
32
+ }
33
+ dataIn(d){
34
+ if(!this.temp.length && d != 126) return;
35
+ // if(this.temp.length == 0) console.log('starting new buffer');
36
+ //Add incoming byte to buffer
37
+ this.temp.push(d);
38
+ //A valid packet can be no less than 6 bytes (delimiter, lengthMSB, lengthLSB, frameType, [...frame data], checksum);
39
+ if(this.temp.length >= 6){
40
+
41
+ //get the reported length and actual length of the frame
42
+ var length = msbLsb(this.temp[1], this.temp[2]);
43
+ var fLength = this.temp.length-4;
44
+
45
+ //If the frame length is less than the actual length, we are still waiting for data
46
+ if(length > fLength) return;
47
+
48
+ //If the lengths match, we have a full packet
49
+ if(length == fLength){
50
+
51
+ //If the checksum matches, parse the packet
52
+ if(this.checksum(this.temp.slice(3,-1)) == this.temp[this.temp.length-1]){
53
+ var frame = this.frame.parse(this.temp);
54
+ if(frame.mac) frame.mac = frame.mac.toLowerCase();
55
+ //If the frame has an ID, send it as the event name since it's a response
56
+ // console.log(frame);
57
+ var event = typeof frame.id != 'undefined' ? 'digi-response:'+frame.id : frame.type;
58
+ //Send out the incoming frame to anyone listening for specific event
59
+ // console.log('event: '+event);
60
+ // console.log(frame);
61
+ this._emitter.emit(event, frame);
62
+ // console.log('data frame: '+this.temp);
63
+ // console.log(frame);
64
+ //Send out the frame to everyone listening to a general call
65
+ this._emitter.emit('digi_frame', frame);
66
+ //If the checksum didn't match, emit an error
67
+ }else{
68
+ console.log('checksum error');
69
+ this._emitter.emit('checksum_error', this.temp);
70
+ //console.log({'checksum error': this.temp});
71
+ }
72
+
73
+ //If the buffer is longer than it should be, send an overflow error
74
+ }else{
75
+ this._emitter.emit('overflow_error', this.temp);
76
+ console.log({'overflow error': this.temp});
77
+ }
78
+ //If we are here the buffer should be reset one way or another
79
+ // console.log({
80
+ // incoming_raw: this.temp
81
+ // });
82
+ //console.log(this.temp);
83
+ this.temp = [];
84
+ }
85
+ }
86
+
87
+ checksum(data){
88
+ return (255 - (data.reduce((t, n) => t+n) & 255));
89
+ }
90
+
91
+ _send(frame, expected){
92
+ // console.log('frame in _send function: '+frame);
93
+ // console.log('frame length is: '+frame.length);
94
+ var that = this;
95
+ if(!expected) expected = 1;
96
+ var awaiting = expected;
97
+ return new Promise((fulfill, reject) => {
98
+ var packet = [126, (frame.length >> 8), (frame.length & 255)];
99
+ packet.push(...frame);
100
+ packet.push(this.checksum(frame));
101
+ var event = 'digi-response:'+frame[1];
102
+ var response = [];
103
+ var tOut = setTimeout(() => {
104
+ that._emitter.removeAllListeners(event);
105
+ reject({error: 'Request timed out without response', original: frame});
106
+ }, that._timoutLimit);
107
+ that.on(event, (frame) => {
108
+ clearTimeout(tOut);
109
+ awaiting -= 1;
110
+ if(awaiting == 0) that._emitter.removeAllListeners(event);
111
+ if(expected == 1) fulfill(frame);
112
+ else{
113
+ response.push(frame);
114
+ fulfill(response);
115
+ }
116
+ });
117
+ // These console.log entries are to display timing and raw packets
118
+ // console.log('-------------------------------');
119
+ // console.log('#otf: /lib/DigiParser.js');
120
+ // console.log('send Frame', packet);
121
+ // console.log('epoch', new Date().getTime());
122
+ that.serial.write(packet, (err) => {
123
+ that.lastSent = packet;
124
+ if(err){
125
+ console.log(err);
126
+ }
127
+ });
128
+ });
129
+
130
+
131
+ //send data!
132
+ }
133
+ on(a,b){ this._emitter.on(a,b); }
134
+ };
135
+ class outgoingFrame{
136
+ constructor(master){
137
+ this.master = master;
138
+ }
139
+ at_command(command, param, queue, expected){
140
+ var frame = [queue ? 9 : 8, this.master.getId()];
141
+ if(!expected) expected = 1;
142
+ for(var i=0;i<command.length;i++) frame.push(command.charCodeAt(i));
143
+ if(typeof param == 'undefined') return this.master._send(frame, expected);
144
+ if(param.constructor != Array) param = [param];
145
+ frame.push(...param);
146
+ return this.master._send(frame, expected);
147
+ }
148
+ remote_at_command(mac, command, param, apply){
149
+ var frame = [23, this.master.getId()];
150
+ frame.push(...mac);
151
+ frame.push(255, 254);
152
+ frame.push(apply ? 2 : 0);
153
+ for(var i=0;i<command.length;i++) frame.push(command.charCodeAt(i));
154
+ if(typeof param == 'undefined') return this.master._send(frame);
155
+ if(param.constructor != Array) param = [param];
156
+ frame.push(...param);
157
+ return this.master._send(frame);
158
+ }
159
+ //For broadcast, set mac to [0,0,0,0,0,0,255,255]
160
+ transmit_request(mac, data, opts){
161
+ var config = this.transmissionOptions(opts);
162
+ var frame = [16, this.master.getId()];
163
+ frame = frame.concat(mac);
164
+ var conf = [255, 254, (config >> 8), (config & 255)];
165
+ frame = frame.concat(conf);
166
+ // if(data.constructor != Array) data = [data];
167
+ frame = frame.concat(data);
168
+ frame.length = 2+mac.length+conf.length+data.length;
169
+ return this.master._send(frame);
170
+ }
171
+ explicit_addressing_command(mac, source, destination, cluster, profile, data, opts){
172
+ var config = this.transmissionOptions(opts);
173
+ var frame = [17, this.master.getId()];
174
+ frame.push(...mac);
175
+ frame.push([255, 254, source, destination, cluster[0], cluster[1], profile[0], profile[1], (config >> 8), (config & 255)]);
176
+ if(data.constructor != Array) data = [data];
177
+ frame.push(...data);
178
+ return this.master._send(frame);
179
+ }
180
+ transmissionOptions(opts){
181
+ var config = Object.assign({
182
+ //Number of allowed hops, 0 = maximum
183
+ rad: 0,
184
+ //1 = Disable ACK
185
+ ack: 0,
186
+ //1 = Disable route discovery
187
+ rd: 0,
188
+ //Enable NACK messages
189
+ nack: 0,
190
+ //Enable Trace Route
191
+ trace: 0,
192
+ //Delivery method - 1 = point_multipoint, 2 = repeater_mode, 3 = digimesh
193
+ method: 3
194
+ }, opts);
195
+ return (config.rad << 8) | (config.ack | (config.rd << 1) | (config.nack << 2) | (config.trace << 3) | (config.method << 6));
196
+
197
+ }
198
+
199
+ }
200
+ class incomingFrame{
201
+ constructor(parent){
202
+ this.parent = parent;
203
+ this.frameType = {
204
+ "136": 'at_command_response',
205
+ "138": 'modem_status',
206
+ "139": 'transmit_status',
207
+ "141": 'route_information_packet',
208
+ "142": 'aggregate_addressing_update',
209
+ "144": 'receive_packet',
210
+ "145": 'explicit_rx_indicator',
211
+ "146": 'io_data_sample_indicator',
212
+ "149": 'node_identification_indicator',
213
+ "151": 'remote_command_response'
214
+ };
215
+ }
216
+ parse(data){
217
+ var type = typeof this.frameType[data[3]] == 'undefined' ? 'unknown' : this.frameType[data[3]];
218
+ if(typeof this[type] == 'function'){
219
+ var frame = this[type](data.slice(4, -1));
220
+ frame.type = type;
221
+ }
222
+ return frame;
223
+ }
224
+
225
+ //Parse frame methods
226
+ at_command_response(frame){
227
+ return {
228
+ id: frame[0],
229
+ command: String.fromCharCode(frame[1])+String.fromCharCode(frame[2]),
230
+ status: (['OK', 'ERROR', 'Invalid Command', 'Invalid Parameter', 'Tx Failure'])[frame[3] & 7],
231
+ data: frame.length > 4 ? frame.slice(4) : false,
232
+ hasError: (frame[3] > 0)
233
+ };
234
+ }
235
+ modem_status(frame){
236
+ return ({"0":{type: "Hardware reset"}, "1": {type: "Watchdog timer reset"}, "11": {type: "Network woke up"}, "12": {type: "Network went to sleep"}})[frame[0]];
237
+ }
238
+ transmit_status(frame){
239
+ return {
240
+ id: frame[0],
241
+ address: frame.slice(1, 3),
242
+ retries: frame[3],
243
+ delivery_status: this.deliveryStatus(frame[4]),
244
+ discovery_status: frame[5] == 0 ? "No discovery overhead" : "Route discovery",
245
+ hasError: (frame[5] != 0)
246
+ };
247
+ }
248
+ route_information_packet(frame){
249
+ return {
250
+ source_event: frame[0] == 17 ? "NACK" : "Trace route",
251
+ format: frame[1],
252
+ timestamp: frame.slice(2, 6).reduce(msbLsb),
253
+ ack_timouts: frame[6],
254
+ tx_blocked: frame[7],
255
+ destination_mac: toMac(frame.slice(9, 17)),
256
+ source_mac: toMac(frame.slice(17, 25)),
257
+ responder_mac: toMac(frame.slice(25, 33)),
258
+ receiver_mac: toMac(frame.slice(33, 41)),
259
+ };
260
+ }
261
+ aggregate_addressing_update(frame){
262
+ return {
263
+ format: frame[0],
264
+ new_address: toMac(frame.slice(1, 9)),
265
+ old_address: toMac(frame.slice(9, 17))
266
+ };
267
+ }
268
+ receive_packet(frame){
269
+ var ret = {
270
+ mac: toMac(frame.slice(0, 8)),
271
+ receive_options: this.receiveOptions(frame[10]),
272
+ data: frame.slice(11)
273
+ };
274
+ if(this.parent.report_rssi) ret.rssi = this.parent.send.at_command('DB');
275
+ return ret;
276
+ }
277
+ explicit_rx_indicator(frame){
278
+ return {
279
+ source_mac: toMac(frame.slice(0, 8)),
280
+ source_endpoint: frame[10],
281
+ destination_endpoint: frame[11],
282
+ cluster_id: frame.slice(12, 14),
283
+ profile_id: frame.slice(14, 16),
284
+ receive_options: this.receiveOptions(frame[16]),
285
+ data: frame.slice(17)
286
+ };
287
+ }
288
+ io_data_sample_indicator(frame){
289
+ return {
290
+ source_mac: toMac(frame.slice(0, 8)),
291
+ source_addr: frame.slice(8, 10).reduce(msbLsb),
292
+ receive_options: this.receiveOptions(frame[10] & 3),
293
+ sample_count: frame[11],
294
+ digital_pins: frame.slice(12, 14).reduce(msbLsb),
295
+ analog_pins: frame[14],
296
+ digital_samples: frame.slice(15, 17).reduce(msbLsb),
297
+ analog_samples: chunk(frame.slice(17), 2).map((i) => msbLsb(i[0], i[1]))
298
+ };
299
+ }
300
+ node_identification_indicator(frame){
301
+ var packet = {
302
+ source_mac: toMac(frame.slice(0, 8)),
303
+ receive_options: this.receiveOptions(frame[10]),
304
+ remote_mac: toMac(frame.slice(13, 21)),
305
+ node_id: frame.slice(21, 23),
306
+ device_type: frame[25] ? (frame[25] == 1 ? "Normal Mode" : "End Device") : "Coordinator",
307
+ source_event: frame[26],
308
+ digi_profile: frame.slice(27, 29),
309
+ digi_manufacturer: frame.slice(29, 31)
310
+ };
311
+ if(frame.length > 33) packet.digi_dd = frame.slice(31, 35);
312
+ if(frame.length > 34) packet.rssi = frame[35];
313
+ return packet;
314
+ }
315
+ remote_command_response(frame){
316
+ return {
317
+ id: frame[0],
318
+ remote_mac: toMac(frame.slice(1, 9)),
319
+ command: String.fromCharCode(frame[11])+String.fromCharCode(frame[12]),
320
+ status: (['OK', 'ERROR', 'Invalid Command', 'Invalid Parameter', 'Tx Failure'])[frame[13] & 7],
321
+ data: frame.slice(14)
322
+ };
323
+ }
324
+ deliveryStatus(status){
325
+ return ({
326
+ "0": "Success",
327
+ "1": "MAC ACK failure",
328
+ "2": "Collision avoidance failure",
329
+ "33": "Network ACK failure",
330
+ "37": "Route not found",
331
+ "49": "Internal resource error",
332
+ "50": "Internal error",
333
+ "116": "Payload too large",
334
+ "117": "Indirect message requested"
335
+ })[status];
336
+ }
337
+ receiveOptions(byte){
338
+ return {
339
+ ack: (byte & 1 == 1),
340
+ broadcast: (byte & 2 == 2),
341
+ type: (byte & 192 == 192) ? "DigiMesh" : ((byte & 128 == 128) ? "Repeater Mode" : ((byte & 64 == 64) ? "Point-Multipoint" : ""))
342
+ };
343
+ }
344
+ }
345
+ function msbLsb(m,l){return (m<<8)+l;}
346
+ function toHex(n){return ("00" + n.toString(16)).substr(-2);}
347
+
348
+ function toMac(arr){
349
+ return arr.reduce((h,c,i) => {return (i==1?toHex(h):h)+':'+toHex(c);});
350
+ }
351
+ function chunk(a, l){
352
+ var arr = [];
353
+ for(i=0;i<a.length;i+=l){
354
+ arr.push(this.slice(i, i+l));
355
+ }
356
+ return arr;
357
+ }