modbus.parse_tcp

modbus.parse_tcp

modbus.parse_tcp

Function

Parse Modbus TCP response frames, verify MBAP length and extract common response fields.

Syntax

Parameters

ParametersTypeRequiredDefault valueDescription
dataBytes/Array/StringYesNoneTCP response frame.

Return value

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

Return object fields

FieldTypeMust existDescription
protocolStringYesProtocol type, fixed to tcp.
transaction_idIntYesMBAP transaction number.
protocol_idIntYesMBAP protocol number, standard Modbus TCP is usually 0.
lengthIntYesMBAP length field, representing the number of bytes of unit_id + pdu.
valid_lengthBoolYesWhether the input byte length is exactly the same as MBAP length. When the input is longer, the current frame is still parsed according to MBAP length.
unit_idIntYesMBAP unit ID.
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

  • valid_length indicates whether the input length is exactly consistent with MBAP length; when the input is longer, the current frame will still be parsed according to MBAP length.