-
Notifications
You must be signed in to change notification settings - Fork 21
/
cul.js
338 lines (286 loc) · 9.53 KB
/
cul.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
/* jshint strict:true */
/* jslint node: true */
/* jslint esversion: 6 */
'use strict';
/**
* CUL/COC / culfw Node.js module
* https://github.com/hobbyquaker/cul
*
* Licensed under GPL v2
* Copyright (c) 2014-2018 hobbyquaker <[email protected]>
*
*/
const util = require('util');
const {EventEmitter} = require('events');
const protocol = {
em: require('./lib/em.js'),
fs20: require('./lib/fs20.js'),
hms: require('./lib/hms.js'),
moritz: require('./lib/moritz.js'),
uniroll: require('./lib/uniroll.js'),
ws: require('./lib/ws.js'),
fht: require('./lib/fht.js'),
esa: require('./lib/esa.js')
};
// http://culfw.de/commandref.html
const commands = {
F: 'FS20',
T: 'FHT',
E: 'EM',
W: 'WS',
H: 'HMS',
S: 'ESA',
R: 'Hoermann',
A: 'AskSin',
V: 'MORITZ',
Z: 'MORITZ',
o: 'Obis',
t: 'TX',
U: 'Uniroll',
K: 'WS'
};
const modes = {
slowrf: {
},
moritz: {
start: 'Zr',
stop: 'Zx'
},
asksin: {
start: 'Ar',
stop: 'Ax'
}
};
const Cul = function (options) {
const that = this;
options = options || {};
options.initCmd = 0x01;
options.mode = options.mode || 'SlowRF';
options.init = options.init || true;
options.parse = options.parse || true;
options.coc = options.coc || false;
options.scc = options.scc || false;
options.rssi = options.rssi || true;
options.debug = options.debug || false;
options.repeat = options.repeat || false;
options.connectionMode = options.connectionMode || 'serial';
options.networkTimeout = options.networkTimeout || true;
options.logger = options.logger || console.log;
if (options.coc) {
options.baudrate = options.baudrate || 38400;
options.serialport = options.serialport || '/dev/ttyACM0';
} else if (options.scc) {
options.baudrate = options.baudrate || 38400;
options.serialport = options.serialport || '/dev/ttyAMA0';
} else {
options.baudrate = options.baudrate || 9600;
options.serialport = options.serialport || '/dev/ttyAMA0';
}
if (options.rssi) {
// Set flag, binary or
options.initCmd |= 0x20;
}
if (options.repeat) {
// Set flag, binary or
options.initCmd |= 0x02;
}
options.initCmd = 'X' + ('0' + options.initCmd.toString(16)).slice(-2);
const modeCmd = modes[options.mode.toLowerCase()] ? modes[options.mode.toLowerCase()].start : undefined;
let stopCmd;
if (modes[options.mode.toLowerCase()] && modes[options.mode.toLowerCase()].stop) {
stopCmd = modes[options.mode.toLowerCase()].stop;
}
// Serial connection
if (options.connectionMode === 'serial') {
const SerialPort = require('serialport');
const {Readline} = SerialPort.parsers;
const parser = new Readline({
delimiter: '\r\n'
});
const spOptions = {
baudRate: options.baudrate
};
const serialPort = new SerialPort(options.serialport, spOptions);
serialPort.pipe(parser);
this.close = function (callback) {
if (!serialPort.isOpen) {
return;
}
if (options.init && stopCmd) {
that.write(stopCmd, () => {
serialPort.close(callback);
});
} else {
serialPort.close(callback);
}
};
serialPort.on('close', () => {
that.emit('close');
});
serialPort.on('open', () => {
if (options.init) {
setTimeout(() => { // Give CUL enough time to wakeup
that.write(options.initCmd, err => {
if (err) {
that.emit('error', err);
}
});
serialPort.drain(() => {
if (modeCmd) {
that.write(modeCmd, err => {
if (err) {
that.emit('error', err);
}
});
serialPort.drain(err => {
if (err) {
that.emit('error', err);
} else {
ready();
}
});
} else {
ready();
}
});
}, 1500);
} else {
ready();
}
function ready() {
parser.on('data', parse);
that.emit('ready');
}
});
serialPort.on('error', ex => {
that.emit('error', ex);
});
this.write = function (data, callback) {
if (options.debug) {
options.logger('->', data);
}
serialPort.write(data + '\r\n');
serialPort.drain(callback);
};
} else if (options.connectionMode === 'telnet') {
// Telnet connection
const net = require('net');
if (!options.host) {
throw new Error('no host defined!');
}
options.port = options.port || '2323';
const telnet = net.createConnection(Number.parseInt(options.port, 10), options.host);
if (options.networkTimeout) {
// WATCHDOG
this.telnetWatchdog = Date.now(); // Setup watchdog
this.telnetWatchdogSecondTry = false; // We try to times before the watchdog bites
setInterval(() => {
if (Date.now() - that.telnetWatchdog > 5000) { // Watchdog bites
if (that.telnetWatchdogSecondTry) { // Second time
// the answer to the command we have written has not arrived
// so we throw an error
that.emit('error', new Error('Connection Timeout!'));
} else { // First time
// if its the first time we are writing a
// simple command to the server and wait for an answer
that.telnetWatchdogSecondTry = true;
that.telnetWatchdog = Date.now();
that.write('V');
}
}
}, 2500);
this.patWatchdog = function () {
that.telnetWatchdog = Date.now(); // Save new time
that.telnetWatchdogSecondTry = false;
};
}
telnet.on('connect', () => {
options.logger('Connected');
if (options.init) {
that.write(options.initCmd);
if (modeCmd) {
that.write(modeCmd);
}
}
telnet.on('data', data => {
data.toString().split(/\r?\n/).forEach(parse);
that.patWatchdog(); // Pat Watchdog
});
that.emit('ready');
});
telnet.on('close', () => {
options.logger('Disconnected');
that.emit('close');
});
telnet.on('error', ex => {
that.emit('error', ex);
});
this.write = function (data, callback) {
if (options.debug) {
options.logger('->', data);
}
telnet.write(data + '\r\n');
if (callback) {
callback(false);
}
};
} else {
// If an unknown connection is defined
throw new Error('connection mode \'' + options.connectionMode + '\' is unknown!\nplease use \'serial\' or \'telnet\'');
}
this.cmd = function () {
let args = Array.prototype.slice.call(arguments);
let callback;
if (typeof args[args.length - 1] === 'function') {
callback = args.pop();
}
let c = args[0].toLowerCase();
args = args.slice(1);
if (commands[c.toUpperCase()]) {
c = commands[c.toUpperCase()].toLowerCase();
}
if (protocol[c] && typeof protocol[c].cmd === 'function') {
const message = protocol[c].cmd.apply(null, args);
if (message) {
that.write(message, callback);
return true;
}
if (typeof callback === 'function') {
callback('cmd ' + c + ' ' + JSON.stringify(args) + ' failed');
}
return false;
}
if (typeof callback === 'function') {
callback('cmd ' + c + ' not implemented');
}
return false;
};
function parse(data) {
if (!data) {
return;
}
data = data.toString();
let message;
let command;
let p;
let rssi;
if (options.parse) {
command = data[0];
message = {};
if (commands[command]) {
p = commands[command].toLowerCase();
if (protocol[p] && typeof protocol[p].parse === 'function') {
message = protocol[p].parse(data);
}
}
if (options.rssi) {
rssi = Number.parseInt(data.slice(-2), 16);
message.rssi = (rssi >= 128 ? (((rssi - 256) / 2) - 74) : ((rssi / 2) - 74));
}
}
that.emit('data', data, message);
}
return this;
};
util.inherits(Cul, EventEmitter);
module.exports = Cul;