modbus.parse_tcp
modbus.parse_tcp
Function
Parse Modbus TCP response frames, verify MBAP length and extract common response fields.
Syntax
modbus.parse_tcp(data)
Parameters
| Parameters | Type | Required | Default value | Description |
|---|---|---|---|---|
| data | Bytes/Array/String | Yes | None | TCP response frame. |
Return value
| Type | Description |
|---|---|
| Object | Returns the TCP response parsing object. See "Return Object Fields" below for fields. |
Return object fields
| Field | Type | Must exist | Description |
|---|---|---|---|
| protocol | String | Yes | Protocol type, fixed to tcp. |
| transaction_id | Int | Yes | MBAP transaction number. |
| protocol_id | Int | Yes | MBAP protocol number, standard Modbus TCP is usually 0. |
| length | Int | Yes | MBAP length field, representing the number of bytes of unit_id + pdu. |
| valid_length | Bool | Yes | Whether 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_id | Int | Yes | MBAP unit ID. |
| function_code | Int | Yes | Response function code. The exception response will have the highest bit, for example 0x83. |
| exception | Bool | Yes | Whether it is a Modbus exception response. |
| exception_code | Int/Empty | No | The exception code of the exception response; only written when exception is true, and empty when the exception code is missing in the response. |
| data | Bytes | Yes | The original data in the PDU after removing the function code. The exception response contains exception code bytes. |
| byte_count | Int | No | Number of data bytes in the read coil, read discrete input, read holding register, read input register response. Other responses do not write this field. |
| coils | Array | No | Read coils or read a parsed Boolean array of discrete input responses. Other responses do not write this field. |
| registers | Array | No | Reading 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. |
| address | Int | No | Write 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. |
| value | Int | No | The 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
frame = bytes([0, 1, 0, 0, 0, 7, 1, 3, 4, 0, 10, 0, 20]) result = modbus.parse_tcp(frame) // Output: 20 print result.registers[1]
Notes
-
valid_lengthindicates 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.