ClassicDIY / ModbusTool

A modbus master and slave test tool with import and export functionality, supports TCP, UDP and RTU.
Apache License 2.0
673 stars 201 forks source link

Bug in modbusLib RTU Codec when message contains intermediate CRC #35

Open alexkthompson opened 9 months ago

alexkthompson commented 9 months ago

I found a weasily little bug in ModbusLib which can cause some data corruption, specifically ModbusLib.Protocols.ModbusRtuCodec.ClientDecode(), where, if by chance, the data of a register read happens to contain an intermediate CRC for the packet, the ClientDecode will return CommResponseAck early, which then causes the SerialPortClient.Query() to exit its reception loop early, and thereby missing the remains of the message. ie, I have logs which look like the following: TX: 01 04 00 00 00 1a 71 c1 RX: 01 04 34 bf 31 5d 78 41 9a ed 42 47 bf f8 97 41 d9

26 registers were requested, but, by chance, my noisy data happened to land such that "41 d9" is the CRC for "01 04 34 bf 31 5d 78 41 9a ed 42 47 bf f8 97" so it exited early, ignoring the last 20 registers and treating the 6th as the CRC

This appears to be because the Codec ClientDecode function does not take into account the bytecount in the 3rd byte of the read operations response, though I suspect it is possible to occur for writes as well, just far less likely.