PyModbus读取保持寄存器时遇功能码128解码失败错误的求助
PyModbus读取保持寄存器时遇功能码128解码失败错误的求助
我现在遇到了一个PyModbus的问题,想请大家帮忙排查下。我尝试连接Modbus TCP服务器读取保持寄存器,已经确认其他软件用相同的IP、端口和寄存器地址都能正常读取数据,但我自己的代码每次运行都会报错。
每次触发的错误日志如下:
DEBUG:pymodbus.logging:Connection to Modbus server established. Socket ('xxx.xxx.x.xx', xxxxx)
DEBUG:pymodbus.logging:Processing: 0x0 0x1 0x0 0x0 0x0 0x3 0x1 0x80 0x5
DEBUG:pymodbus.logging:decode PDU failed for function code 128
WARNING:pymodbus.logging:Unable to decode frame Modbus Error: Unknown response 128
Modbus I/O Error: Modbus Error: [Input/Output] Unable to decode request
我换了好几台不同的Modbus设备、不同的IP地址测试,每次都是同样的错误,所以我很确定问题出在我的代码里。
以下是我编写的读取寄存器的代码:
def read_macbat(): num_regs = 8 client = ModbusTcpClient(host=MACBAT_HOST, port=MACBAT_PORT, timeout=TIMEOUT) for attempt in range(1, MAX_RETRIES + 1): try: if client.connect(): response = client.read_holding_registers(address=10042, count=num_regs) print(response) if not response.isError(): print(f"Attempt {attempt}: Successfully read registers.") print(f"Register Values: {response.registers}") client.close() return response.registers else: print(f"Attempt {attempt}: Error reading registers.") client.close() else: print(f"Attempt {attempt}: Failed to connect to Modbus counter.") if attempt < MAX_RETRIES: print(f"Retrying in {RETRY_DELAY} seconds...") time.sleep(RETRY_DELAY) except ModbusIOException as e: print(f"Modbus I/O Error: {e}") print("Max retries reached. Could not read registers.") return None
目前我手头的排查线索不多,但如果有任何排查思路或者代码修改建议,都欢迎大家提出来,非常感谢!
备注:内容来源于stack exchange,提问作者kemalkaancetindag
相关产品推荐
相关产品推荐

