forked from yaacov/node-modbus-serial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync_server.js
executable file
·72 lines (69 loc) · 2.26 KB
/
async_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
/* eslint-disable no-console, no-unused-vars, spaced-comment */
// create an empty modbus client
//var ModbusRTU = require("modbus-serial");
var ModbusRTU = require("../index");
var vector = {
getInputRegister: function(addr, unitID) {
// Synchronous handling
return addr;
},
getHoldingRegister: function(addr, unitID, callback) {
// Asynchronous handling (with callback)
setTimeout(function() {
// callback = function(err, value)
callback(null, addr + 8000);
}, 10);
},
getCoil: function(addr, unitID) {
// Asynchronous handling (with Promises, async/await supported)
return new Promise(function(resolve) {
setTimeout(function() {
resolve(addr % 2 === 0);
}, 10);
});
},
getDiscreteInput: function(addr, unitID) {
// Asynchronous handling (with Promises, async/await supported)
return new Promise(function(resolve) {
setTimeout(function() {
resolve(addr % 2 === 0);
}, 10);
});
},
setRegister: function(addr, value, unitID) {
// Asynchronous handling supported also here
console.log("set register", addr, value, unitID);
return;
},
setCoil: function(addr, value, unitID) {
// Asynchronous handling supported also here
console.log("set coil", addr, value, unitID);
return;
},
readDeviceIdentification: function(unitID) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve({
0x00: "MyVendorName",
0x01: "MyProductCode",
0x02: "MyMajorMinorRevision",
0x05: "MyModelName",
0x97: "MyExtendedObject1",
0xAB: "MyExtendedObject2"
});
}, 10);
});
}
};
// set the server to answer for modbus requests
console.log("ModbusTCP listening on modbus://0.0.0.0:8502");
var serverTCP = new ModbusRTU.ServerTCP(vector, {
host: "0.0.0.0",
port: 8502,
debug: true,
unitID: 1
});
serverTCP.on("socketError", function(err) {
// Handle socket error if needed, can be ignored
console.error(err);
});