node-modbus-serial
node-modbus-serial copied to clipboard
Unable to connect TCP
Hi. I tried the code as it is mentioned in the example:
// create an empty modbus client const ModbusRTU = require("modbus-serial"); const client = new ModbusRTU();
// open connection to a tcp line client.connectTCP("127.0.0.1", { port: 8502 }); client.setID(1);
// read the values of 10 registers starting at address 0 // on device number 1. and log the values to the console. setInterval(function() { client.readHoldingRegisters(0, 10, function(err, data) { console.log(data.data); }); }, 1000);
But, I am unable to get a connection with TCP. When I try running the code, I get the following error:
node:internal/process/promises:288 triggerUncaughtException(err, true /* fromPromise */); ^
Error: connect ECONNREFUSED 127.0.0.1:8502 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1237:16) { errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '127.0.0.1', port: 8502 }
Node.js v18.5.0
I have tried doing this with different versions of nodejs but I am getting the same result everytime. Can you please help me? The code worked just once yesterday and I have been trying to make it work again since but have been unsuccessful. Please help.
I recommend you to wrap setIntercal in a function and call this after TCP connection is done.
ECONNREFUSED means the host is not reachable, I suggest you to check first with ModPoll, or any modbus tool.
async function modbusConnect() {
await client.connectTCP(hostAddress, hostPort)
.then(() => {
if (client.isOpen) {
console.log(`Polling Modbus → IP: ${hostAddress} /PORT ${hostPort.port}`);
pollModbusDevices(3000);
}
})
.catch(err => {
if (err.code == 'ETIMEDOUT' || err.errno == 'ECONNREFUSED') {
if (intervalId) {
clearInterval(intervalId);
}
modbusConnect();
}
console.log(err.message);
});
}
// Read registers values starting at address 0
// on all nodes (nodeIds), and show values to console
function pollModbusDevices(interval) {
intervalId = setInterval(function () {
for (let node of nodeIds) {
client.setID(node);
client.readHoldingRegisters(0, 100, function (err, data) {
if (data) {
// do whatever ...
}
if (err) {
console.log(err.message);
if (err.errno == 'ECONNREFUSED') {
client.close();
modbusConnect();
}
}
});
}
}, interval);
}