node-modbus-serial
node-modbus-serial copied to clipboard
Help needed ECONNREFUSED
Hi everybody, so I am new to this topic and got stocked. I have the case that I have to control 8 devices with 8 different ip addresses.
So if I try to connect the 8 devices, I get the error e.g. if one is not reachable.
Error: connect ECONNREFUSED 192.168.0.9:502
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '192.168.0.9',
port: 502
}
I trigger the script from a ionic app via api calls . If the device on 192.168.0.9 is not available all other devices stop readHoldingRegisters. If I only trigger the one on ip 192.168.0.10, which is available, I get the data from readHoldingRegisters
on node server:
app.post('/api/sps/connect', function (req, res) {
let data = req.body.data[0];
let ipAddressSPS = data.ipAddressSPS;
let ovenPosition = data.ovenPosition;
client.connectTCP(ipAddressSPS, { port: 502 })
.then(function() {
client.setID(ovenPosition);
//client.setTimeout(1000);
})
.then(function() {
console.log("Connected");
console.log('ClientID: ' + client.getID());
readRegisters();
})
.catch(function(e) {
if(e.errno) {
if(networkErrors.includes(e.errno)) {
console.log("we have to reconnect");
}
}
console.log('Error');
console.log('ClientID: ' + client.getID());
console.log(e.message);
//client.close();
});
});
function readRegisters() {
setInterval(function () {
client.readHoldingRegisters(0, 24)
.then(function(d) {
console.log('-------------------------------');
console.log("Receive:", d.data);
console.log('ClientID: ' + client.getID());
console.log('-------------------------------');
})
.catch(function(e) {
console.log(e.message);
});
}, 1000);
}
How could I catch the error and only start the client if it is available?
Here seems to be a similar problem, but I did't understand the suggested implementation. https://github.com/yaacov/node-modbus-serial/issues/469
Any other suggestions? Any help appreciated! Thanks in advance!
did you try to create a new client for each new IP you get ? e.g. keep a dictionary of clients, ip as key, and client as value
the example you refer too, is handling connection errors, so if you get an error, it will close the connection and re-open it, this may also help
Hey @yaacov Thank you very much for the very quick reply! This saved my day. I was thinking too difficult. I did it like you suggested with a dictionary of clients.