Cloud-Automation / node-modbus

Modbus TCP Client/Server implementation for Node.JS
471 stars 175 forks source link

how reconnect ? #23

Closed profelec closed 8 years ago

profelec commented 8 years ago

If I loose connection, is it possible to reconnect without the node script being stopped and restarted? I tried this without success:

// create a modbus client
var ErreurModbus = 0;
var client = modbus.createTCPClient(CONF_portAutomate, CONF_ipAutomate, function (err) {
    if (err) {
        ErreurModbus = 1;
        io.sockets.emit('displayErreurModbus', ErreurModbus); // tous
    }
});
/*Un client se connecte*/
io.sockets.on('connection', function (socket) {
    /* Clique sur le bouton Reset Server*/
    socket.on('setResetServer',function(){
        ErreurModbus = 0;
        client.reconnect();
        io.sockets.emit('displayErreurModbus', ErreurModbus); // tous
    })
});
stefanpoeter commented 8 years ago

Any error messages?

profelec commented 8 years ago

I have no error messages. I tested this with a virtual server, and the code works one time out of three. And I tested this with a Zelio automaton, and it never works.

stefanpoeter commented 8 years ago

I checked the code, the reconnect function just calls the connect method on the socket. Make sure the connection is closed when you reconnect the client. Listen to the error and close events on the client, what did they have to say? This way we get a bit more information on that matter.

client.reconnect = function () {
    socket.connect(port, host);
};
stefanpoeter commented 8 years ago

You might want to check the #2 v1.0.0 branch. The README describes how to handle reconnects there. It even has two examples for doing so.

profelec commented 8 years ago

Thanks! Your update is great, it works! :+1:

But, there is a error in the readme.md :

client.readHoldingRegister(0, 10).then(function (resp) {

        // resp will look like { fc: 3, byteCount: 20, register: [ values 0 - 10 ] }
        console.log(resp); 

    }).fail(console.log);

it misses an "S" to readHoldingRegister.