diff --git a/umodbus/client/serial/rtu.py b/umodbus/client/serial/rtu.py index 4c01580..4ffe485 100644 --- a/umodbus/client/serial/rtu.py +++ b/umodbus/client/serial/rtu.py @@ -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, @@ -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): diff --git a/umodbus/functions.py b/umodbus/functions.py index 4db3cec..f46b1a6 100644 --- a/umodbus/functions.py +++ b/umodbus/functions.py @@ -104,11 +104,10 @@ def pdu_to_function_code_or_raise_error(resp_pdu): - """ Parse response PDU and return of :class:`ModbusFunction` or - raise error. + """Parse response PDU and return function code or raise error. :param resp_pdu: PDU of response. - :return: Subclass of :class:`ModbusFunction` matching the response. + :return: Function code contained in the response. :raises ModbusError: When response contains error code. """ function_code = struct.unpack('>B', resp_pdu[0:1])[0]