modbus.parse_rtu
modbus.parse_rtu
Function
Parse Modbus RTU response frames, check CRC and extract common response fields.
Syntax
modbus.parse_rtu(data)
Parameters
| Parameters | Type | Required | Default value | Description |
|---|---|---|---|---|
| data | Bytes/Array/String | Yes | None | RTU response frame. |
Return value
| Type | Description |
|---|---|
| Object | Returns the RTU 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 rtu. |
| unit_id | Int | Yes | RTU slave address. |
| crc | Int | Yes | The CRC16 value carried at the end of the response frame, parsed with the low byte first. |
| crc_expected | Int | Yes | The CRC16 value recalculated based on the response payload. |
| valid_crc | Bool | Yes | Whether crc is equal to crc_expected. Parsing of the PDU continues even if the CRC does not match. |
| 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('010304000a0014da3e', 'hex') result = modbus.parse_rtu(frame) // Output: 10 print result.registers[0]
Notes
- The data will not be discarded when the CRC does not match,
valid_crcreturns false, and the script can decide whether to discard it. - Exception responses will return
exception: trueandexception_code.