You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 10:18:01