grid-x / modbus

BSD 3-Clause "New" or "Revised" License
78 stars 26 forks source link

Modbus over TCP - Connection refused #75

Closed decadenza closed 1 year ago

decadenza commented 1 year ago

I have a Raspberry Pi running this amazing library. A reduced version of the connecting code is:

handler = mb.NewRTUOverTCPClientHandler(config.ModbusSlaveAddress)
err := handler.Connect()
if err != nil {
        log.Debug().Err(err).Msg("Could not connect Modbus handler.")
        return err
    }
client = mb.NewClient(handler)

A Modbus slave GPIO board is connected via Ethernet cable.

I want the system to reconnect if the cable is disconnected and connected back. After a certain number of R/W errors or timeouts, I call handler.Close() and the connection is re-initialised as above.

After reconnecting the cable, handler.Connect() does not produce errors, connection is thus established, but at the first R/W operation I get the following error:

dial tcp 192.168.2.80:10001: connect: connection refused

And the cycle repeats endlessly... Unless I restart my application.

Is there a way to re-connect automatically? What am I missing?

decadenza commented 1 year ago

The simple solutions was to create the handler only during initialisation:

handler = mb.NewRTUOverTCPClientHandler(config.ModbusSlaveAddress)

and only call Connect()and Close() on the same object.

Closing.