forked from huangxin/ailai
20 lines
755 B
Python
20 lines
755 B
Python
def parse_coil_status_response(response_hex):
|
||
"""
|
||
解析 Modbus 功能码 0x01 的响应(读线圈状态)
|
||
:param response_hex: 十六进制字符串,如 '00000000000401010101'
|
||
:return: dict,表示每个 bit 的状态(True/False)
|
||
"""
|
||
if len(response_hex) < 18:
|
||
return {"error": "响应数据过短"}
|
||
|
||
data_part = response_hex[14:18] # 提取 0101 部分
|
||
status_byte = int(data_part[2:4], 16) # 取出 01 → 十进制 1
|
||
|
||
# 每个 bit 对应一个设备,bit0 是最低位
|
||
status = {f"device_{i}": (status_byte >> i) & 0x01 == 1 for i in range(8)}
|
||
return status
|
||
|
||
# 示例使用
|
||
response = "00000000000401010103"
|
||
status = parse_coil_status_response(response)
|
||
print("设备状态:", status) |