Apollo3zehn / FluentModbus

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

fix two modbus rtu problems #79

Closed LukasKarel closed 1 year ago

LukasKarel commented 1 year ago

When a ModbusRtuRequestHandler is Disposed it closes the SerialPort before the CancellationTokenSource of the base class is cancelled. Therefor the InBuffer of SerialPort should be cleared even if the serialport is already closed. Secondly on a timeout exception the UnitIdentifier should be reset otherwise an exception is thrown.

LukasKarel commented 1 year ago

Added a new commit, which adds a virtual stop method to the ModbusServer base class. This helps to add both servers in the same container and perform cleanup on them.

Apollo3zehn commented 1 year ago

Thank you! I will go through it next week as I need to finish another project right now.

Apollo3zehn commented 1 year ago

You wrote "Therefor the InBuffer of SerialPort should be cleared even if the serialport is already closed." but your PR does the opposite: Is clears the buffer only when the serial port is already closed. I am a little bit confused.

What happens if the serial port is already closed and we try to clear the buffer? Will it throw an exception?

Edit: I have tested it and it throws an exception. So I agree to this change (only discarding buffer when port is open).

Apollo3zehn commented 1 year ago

Where does the exception occur, if the UnitIdentifier is not reset? To be honest I think there is another bug in the ModbusRtuRequestHandler method InternalReceiveRequestAsync because the return value is never used. I think I need to change error handling in general in InternalReceiveRequestAsync (both for Modbus TCP and RTU) because when a TimeoutException occurs no frame should be processed at all. It should simply continue looping.

Apollo3zehn commented 1 year ago

I have removed the Line UnitIdentifier = 255 because I do not understand why it is required. However I will now work on a better error handling in that method so hopefully your issue are solved anyway.