-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathserver.js
484 lines (424 loc) · 13.7 KB
/
server.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
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
/**
* Copyright (c) 2015, Yaacov Zamir <kobi.zamir@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
var io;
var ModbusRTU = require("modbus-serial");
var version = require('./package.json').version;
var serialPort;
var modbusRTU;
var getCoils;
var getInputStatus;
var getInputRegisters;
var getHoldingRegisters;
var forceCoil;
var setRegisters;
var debug;
/**
* Write a Modbus "Read Coils" (FC=01) to serial port,
* and emit the replay to websocket
*
* @param {number} unit the slave unit address.
* @param {number} address the Data Address of the first coil.
* @param {number} length the total number of coils requested.
*/
var _getCoils = function(unit, address, length) {
modbusRTU.writeFC1(unit, address, length,
function(err, msg) {
if (err) {
console.log(err);
io.emit('data', {'err': err});
} else {
io.emit('data', {
'unit': unit,
'type': 1,
'address': address,
'data': msg.data,
'flag': 'get'
});
}
}
);
}
/**
* Write a Modbus "Read input status" (FC=02) to serial port,
* and emit the replay to websocket
*
* @param {number} unit the slave unit address.
* @param {number} address the Data Address of the first digital input.
* @param {number} length the total number of digital inputs requested.
*/
var _getInputStatus = function(unit, address, length) {
modbusRTU.writeFC2(unit, address, length,
function(err, msg) {
if (err) {
console.log(err);
io.emit('data', {'err': err});
} else {
io.emit('data', {
'unit': unit,
'type': 2,
'address': address,
'data': msg.data,
'flag': 'get'
});
}
}
);
}
/**
* Write a Modbus "Read Holding Registers" (FC=03) to serial port,
* and emit the replay to websocket
*
* @param {number} unit the slave unit address.
* @param {number} address the Data Address of the first register.
* @param {number} length the total number of registers requested.
*/
var _getHoldingRegisters = function(unit, address, length) {
modbusRTU.writeFC3(unit, address, length,
function(err, msg) {
if (err) {
console.log(err);
io.emit('data', {'err': err});
} else {
io.emit('data', {
'unit': unit,
'type': 3,
'address': address,
'data': msg.data,
'flag': 'get'
});
}
}
);
}
/**
* Write a Modbus "Read Input Registers" (FC=04) to serial port,
* and emit the replay to websocket
*
* @param {number} unit the slave unit address.
* @param {number} address the Data Address of the first register.
* @param {number} length the total number of registers requested.
*/
var _getInputRegisters = function(unit, address, length) {
modbusRTU.writeFC4(unit, address, length,
function(err, msg) {
if (err) {
console.log(err);
io.emit('data', {'err': err});
} else {
io.emit('data', {
'unit': unit,
'type': 4,
'address': address,
'data': msg.data,
'flag': 'get'
});
}
}
);
}
/**
* Write a Modbus "Force one coil" (FC=05) to serial port,
* and emit the replay to websocket
*
* @param {number} unit the slave unit address.
* @param {number} address the Data Address of the coil.
* @param {number} state the state to set into coil.
*/
var _forceCoil = function(unit, address, state) {
modbusRTU.writeFC5(unit, address, state,
function(err, msg) {
if (err) {
console.log(err);
io.emit('data', {'err': err});
} else {
io.emit('data', {
'unit': unit,
'type': 5,
'address': address,
'data': state,
'flag': 'set'
});
}
}
);
}
/**
* Write a Modbus "Preset Multiple Registers" (FC=16) to serial port,
* and emit the replay to websocket
*
* @param {number} unit the slave unit address.
* @param {number} address the Data Address of the first register.
* @param {array} values the array of values to write to registers.
*/
var _setRegisters = function(unit, address, values) {
modbusRTU.writeFC16(unit, address, values,
function(err, msg) {
if (err) {
console.log(err);
io.emit('data', {'err': err});
} else {
io.emit('data', {
'unit': unit,
'type': 3,
'address': address,
'data': values,
'flag': 'set'
});
}
}
);
}
/**
* Setup the socket.io events
*/
var setup = function() {
/* register socker io events
*/
io.on('connection', function(socket){
var intervalIDs = [];
//console.log('client connected');
socket.on('disconnect', function(){
// clear all periodically requests
intervalIDs.map(clearInterval);
//console.log('client disconnected');
});
socket.on('readCoils', function(data){
// check event validity
if (!data) return;
var unit = data.unit;
var address = data.address;
var length = data.length;
// check event validity
if (!unit || typeof address == 'undefined' || !length) return;
/* if client request an interval,
* set a time interval and emit data
* periodically.
*/
var interval = data.interval;
if (interval) {
var id = setInterval(function() {
getCoils(unit, address, length);
}, interval);
intervalIDs.push(id);
} else {
getCoils(unit, address, length);
}
});
socket.on('readDiscreteInputs', function(data){
// check event validity
if (!data) return;
var unit = data.unit;
var address = data.address;
var length = data.length;
// check event validity
if (!unit || typeof address == 'undefined' || !length) return;
/* if client request an interval,
* set a time interval and emit data
* periodically.
*/
var interval = data.interval;
if (interval) {
var id = setInterval(function() {
getInputStatus(unit, address, length);
}, interval);
intervalIDs.push(id);
} else {
getInputStatus(unit, address, length);
}
});
socket.on('readHoldingRegisters', function(data){
// check event validity
if (!data) return;
var unit = data.unit;
var address = data.address;
var length = data.length;
// check event validity
if (!unit || typeof address == 'undefined' || !length) return;
/* if client request an interval,
* set a time interval and emit data
* periodically.
*/
var interval = data.interval;
if (interval) {
var id = setInterval(function() {
getHoldingRegisters(unit, address, length);
}, interval);
intervalIDs.push(id);
} else {
getHoldingRegisters(unit, address, length);
}
});
socket.on('readInputRegisters', function(data){
// check event validity
if (!data) return;
var unit = data.unit;
var address = data.address;
var length = data.length;
// check event validity
if (!unit || typeof address == 'undefined' || !length) return;
/* if client request an interval,
* set a time interval and emit data
* periodically.
*/
var interval = data.interval;
if (interval) {
var id = setInterval(function() {
getInputRegisters(unit, address, length);
}, interval);
intervalIDs.push(id);
} else {
getInputRegisters(unit, address, length);
}
});
socket.on('writeCoil', function(data){
// check event validity
if (!data) return;
var unit = data.unit;
var address = data.address;
var state = data.state;
// check event validity
if (!unit ||
typeof address == 'undefined' ||
typeof state == 'undefined') return;
forceCoil(unit, address, state);
});
socket.on('writeRegisters', function(data){
// check event validity
if (!data) return;
var unit = data.unit;
var address = data.address;
var values = data.values;
// check event validity
if (!unit || typeof address == 'undefined' || !values) return;
setRegisters(unit, address, values);
});
});
};
/**
* stop the modbus-ws server
*/
var stop = function() {
serialPort.close();
process.exit();
}
/**
* Run a websocket only server
*
* @param {number} tcpPort the tcp port to listen on
* @param {function} callback the function to call when done
*/
var run_wsd = function(tcpPort, callback) {
// run ws server
io = require('socket.io')(tcpPort, {
allowEIO3: true // false by default
});
/* Setup WebSocket event listener
*/
setup();
}
/**
* Run server with web application
*
* @param {number} tcpPort the tcp port to listen on
* @param {function} callback the function to call when done
*/
var run_httpd = function(tcpPort, callback) {
// run express application
// with websockets
var app = require('./app');
var http = require('http').Server(app);
io = require('socket.io')(http, {
allowEIO3: true // false by default
});
/* Setup WebSocket event listener
*/
setup();
/* Setup http listener
*/
http.listen(tcpPort);
}
/**
* start the modbus-ws server
*/
var start = function(options, callback) {
/* set up some default options
*/
var title = "Modbus-WS server";
var tcpPort = options.tcpport || 3000;
var port = options.serial || false;
var baud = options.baudrate || 9600;
var ip = options.ip || false;
var noCache = options.nocache || false;
var noHttp = options.nohttp || false;
/* log server title and version
*/
console.log();
console.log('----------------------------------------------------');
console.log(title, version);
/* open a serial port and setup modbus master
*/
modbusRTU = new ModbusRTU();
if (ip) {
console.log(" Setup tcp/ip port:", ip);
// open connection to a tcp line
modbusRTU.connectTCP(ip, { port: 502 });
} else if (port) {
console.log(" Setup serial port:", port, baud);
modbusRTU.connectRTUBuffered(port, { baudRate: parseInt(baud) });
} else {
throw new Error("Test mode is no longer supported in modbus-serial");
}
/* set up express web application / only web socket server
*/
if (noHttp) {
// run only web sockets server
console.log(" Server is running, ws://127.0.0.1:" + tcpPort);
run_wsd(tcpPort);
} else {
// run express application
// with web sockets
console.log(" Server is running, http://127.0.0.1:" + tcpPort);
run_httpd(tcpPort);
}
/* set up caching
*/
if (noCache) {
console.log(" Setup modbus without caching.");
getCoils = _getCoils;
getInputStatus = _getInputStatus;
getHoldingRegisters = _getHoldingRegisters;
getInputRegisters = _getInputRegisters;
forceCoil = _forceCoil;
setRegisters = _setRegisters;
} else {
var cache = require("./cache");
console.log(" Setup modbus with caching.");
cache.run(io, modbusRTU, options);
getCoils = cache.getCoils;
getInputStatus = cache.getInputStatus;
getHoldingRegisters = cache.getHoldingRegisters;
getInputRegisters = cache.getInputRegisters;
forceCoil = cache.forceCoil;
setRegisters = cache.setRegisters;
}
console.log("----------------------------------------------------");
console.log();
// callback
if (callback) callback();
}
module.exports = {};
module.exports.stop = stop;
module.exports.start = start;