Skip to content

Commit

Permalink
Merge pull request #177 from yaacov/add-async-server-example
Browse files Browse the repository at this point in the history
add a server example
  • Loading branch information
yaacov authored Feb 5, 2018
2 parents e6988bb + 3fac9ab commit 4524204
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 3 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ const getMetersValue = async (meters) => {
}

const getMeterValue = async (id) => {
try {
try {
// set ID of slave
await client.setID(id);
// read the 1 registers starting at address 0 (first register)
Expand All @@ -156,7 +156,7 @@ const getMeterValue = async (id) => {
} catch(e){
// if error return -1
return -1
}
}
}

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
Expand Down Expand Up @@ -217,7 +217,8 @@ var vector = {
getHoldingRegister: function(addr, unitID, callback) {
// Asynchronous handling (with callback)
setTimeout(function() {
callback(addr + 8000);
// callback = function(err, value)
callback(null, addr + 8000);
}, 10);
},
getCoil: function(addr, unitID) {
Expand Down
50 changes: 50 additions & 0 deletions examples/async_server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/* 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);
});
},
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;
}
};

// 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);
});
Empty file modified examples/logger.js
100644 → 100755
Empty file.
Empty file modified examples/write.js
100644 → 100755
Empty file.

0 comments on commit 4524204

Please sign in to comment.