Skip to content

Commit

Permalink
RTU: Check CRC before signalling an exception response.
Browse files Browse the repository at this point in the history
The first five response ADU bytes received are checked for a valid
function code, assuming an error if it is unknown.  The received ADU
part is then treated as an exception frame.  But even those must pass
the CRC validation, otherwise the supposed "wrong" function code
cannot even be trusted at all.

This change adds the CRC check for the first five bytes, falling
through to further processing when it fails.  The overall CRC and
function code is checked later in parse_response_adu(), so an invalid
code will be detected again at that point.

This is mainly relevant if the responses are received partially from
the serial input buffer, which will cause many CRC and parsing
failures.  In those cases, the reported exception will likely be a
CRCError or ValueError for the whole ADU, instead of an invalid
function code based on only the first 5 bytes.
  • Loading branch information
acolomb committed Mar 10, 2021
1 parent 4a818be commit 964d09f
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion umodbus/client/serial/rtu.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import struct

from umodbus.client.serial.redundancy_check import get_crc, validate_crc
from umodbus.client.serial.redundancy_check import CRCError
from umodbus.functions import (create_function_from_response_pdu,
expected_response_pdu_size_from_request_pdu,
pdu_to_function_code_or_raise_error, ReadCoils,
Expand Down Expand Up @@ -199,7 +200,13 @@ def raise_for_exception_adu(resp_adu):
:raises ModbusError: When a response contains an error code.
"""
resp_pdu = resp_adu[1:-2]
pdu_to_function_code_or_raise_error(resp_pdu)
try:
validate_crc(resp_adu)
pdu_to_function_code_or_raise_error(resp_pdu)
except CRCError:
# The response cannot be trusted at all, so ignore any
# possibly invalid function code.
pass


def send_message(adu, serial_port):
Expand Down

0 comments on commit 964d09f

Please sign in to comment.