Apollo3zehn / FluentModbus

Lightweight and fast client and server implementation of the Modbus protocol (TCP/RTU).
MIT License
205 stars 72 forks source link

Linux / IsConnected #127

Open Steve0212a opened 3 weeks ago

Steve0212a commented 3 weeks ago

I have code that is shared between Windows and Linux that uses the FluentModbus client (synchronous) to talk to Modbus devices. I am currently testing failures such as the Modbus device is turned off or disconnected from the network.

On Windows, the code works perfectly - meaning that the IsConnected flag goes to false after having previously been true from before I turned the device off.

However, on Linux, it establishes the connection and the IsConnected flag is true. I then turn the device off, but the the IsConnected flag never goes to false.

Any thoughts on how to fix or work around this?

Apollo3zehn commented 3 weeks ago

Are you using Modbus TCP oder Modbus RTU? In case of Modbus TCP it is just forwarding the status of the underlying TcpClient:

https://github.com/Apollo3zehn/FluentModbus/blob/1d5e16b1cbddeb0c369cffec36cd1ec6ca00da0e/src/FluentModbus/Client/ModbusTcpClient.cs#L41

So it depends on the implementation of TcpClient by Microsoft and this in turn I think is based on a Socket. I do not know why they behave different but maybe a Timeout property is configured differently on both operating systems or there is no Timeout at all.

This is all I know about what happens underneath, sorry I could not help more.

Apollo3zehn commented 3 weeks ago

You can pass your own TcpClient so you have full control over it:

https://github.com/Apollo3zehn/FluentModbus/blob/1d5e16b1cbddeb0c369cffec36cd1ec6ca00da0e/src/FluentModbus/Client/ModbusTcpClient.cs#L152

Steve0212a commented 3 weeks ago

I will try my own client and see what I get. In the mean time, I was just about to try a work around where I catch the exception (shown below) on reads and use that to know I have lost connection. When this happens on linux, I get this on any read:

System.InvalidOperationException HResult=0x80131509 Message=The TCP connection closed unexpectedly. Source=FluentModbus_Vertiv StackTrace: at FluentModbus.ModbusTcpClient.TransceiveFrame(Byte unitIdentifier, ModbusFunctionCode functionCode, Action1 extendFrame) in C:\ClientDev\Vertiv\iCOM-S\ExternalSrc\FluentModbus\src\FluentModbus\Client\ModbusTcpClient.cs:line 297 at FluentModbus.ModbusClient.ReadDiscreteInputs(Int32 unitIdentifier, Int32 startingAddress, Int32 quantity) in C:\ClientDev\Vertiv\iCOM-S\ExternalSrc\FluentModbus\src\FluentModbus\Client\ModbusClient.cs:line 265`