modbus.parse_rtu

modbus.parse_rtu

modbus.parse_rtu

Function

Parse Modbus RTU response frames, check CRC and extract common response fields.

Syntax

Parameters

ParametersTypeRequiredDefault valueDescription
dataBytes/Array/StringYesNoneRTU response frame.

Return value

TypeDescription
ObjectReturns the RTU response parsing object. See "Return Object Fields" below for fields.

Return object fields

FieldTypeMust existDescription
protocolStringYesProtocol type, fixed to rtu.
unit_idIntYesRTU slave address.
crcIntYesThe CRC16 value carried at the end of the response frame, parsed with the low byte first.
crc_expectedIntYesThe CRC16 value recalculated based on the response payload.
valid_crcBoolYesWhether crc is equal to crc_expected. Parsing of the PDU continues even if the CRC does not match.
function_codeIntYesResponse function code. The exception response will have the highest bit, for example 0x83.
exceptionBoolYesWhether it is a Modbus exception response.
exception_codeInt/EmptyNoThe exception code of the exception response; only written when exception is true, and empty when the exception code is missing in the response.
dataBytesYesThe original data in the PDU after removing the function code. The exception response contains exception code bytes.
byte_countIntNoNumber of data bytes in the read coil, read discrete input, read holding register, read input register response. Other responses do not write this field.
coilsArrayNoRead coils or read a parsed Boolean array of discrete input responses. Other responses do not write this field.
registersArrayNoReading a holding register or reading an input register responds to a parsed 16-bit unsigned register integer array. Other responses do not write this field.
addressIntNoWrite single coil, write single register, write multiple coils, write multiple registers Confirm the starting address in the response. Other responses do not write this field.
valueIntNoThe quantity or value to write in the confirmation response. Function code 5/6 represents the written value, and function code 15/16 represents the written quantity.

Code Example

Notes

  • The data will not be discarded when the CRC does not match, valid_crc returns false, and the script can decide whether to discard it.
  • Exception responses will return exception: true and exception_code.