我正在尝试使用 IP 地址从 Modbus 控制器获取数据。
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
client = ModbusClient("10.98.237.80", port=502, auto_open=True)
client.connect()
rr = client.read_holding_registers(60, 2, unit=1)
print (rr.registers)
这给出了以下异常
2023-04-03 14:57:18,678 MainThread DEBUG sync :216 Connection to Modbus server established. Socket ('10.80.144.99', 64492)
2023-04-03 14:57:18,680 MainThread DEBUG transaction :140 Current transaction state - IDLE
2023-04-03 14:57:18,681 MainThread DEBUG transaction :145 Running transaction 1
2023-04-03 14:57:18,682 MainThread DEBUG transaction :273 SEND: 0x0 0x1 0x0 0x0 0x0 0x6 0x1 0x3 0x0 0x3c 0x0 0x2
2023-04-03 14:57:18,683 MainThread DEBUG sync :76 New Transaction state 'SENDING'
2023-04-03 14:57:18,684 MainThread DEBUG transaction :287 Changing transaction state from 'SENDING' to 'WAITING FOR REPLY'
2023-04-03 14:57:20,082 MainThread DEBUG transaction :375 Changing transaction state from 'WAITING FOR REPLY' to 'PROCESSING REPLY'
2023-04-03 14:57:20,083 MainThread DEBUG transaction :297 RECV: 0x0 0x1 0x0 0x0 0x0 0x3 0x1 0x83 0xfc
2023-04-03 14:57:20,084 MainThread DEBUG socket_framer :147 Processing: 0x0 0x1 0x0 0x0 0x0 0x3 0x1 0x83 0xfc
2023-04-03 14:57:20,084 MainThread DEBUG factory :266 Factory Response[131]
2023-04-03 14:57:20,085 MainThread DEBUG transaction :454 Adding transaction 1
2023-04-03 14:57:20,085 MainThread DEBUG transaction :465 Getting transaction 1
2023-04-03 14:57:20,086 MainThread DEBUG transaction :224 Changing transaction state from 'PROCESSING REPLY' to 'TRANSACTION_COMPLETE'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-11-1ea661f8edc1> in <module>
6 rr = client.read_holding_registers(60, 2, unit=1)
7
----> 8 print (rr.registers)
AttributeError: 'ExceptionResponse' object has no attribute 'registers'
我对这个 Modbus 和 modbus 服务器/客户端完全陌生。 请帮忙。非常感谢任何帮助。
首先,如果您的 Modbus 服务器通过以太网连接,则无需指定单元 ID,因为它用于识别在 Modbus-RTU 或 Modbus+ 中通信的各个 PLC,而 Modbus TCP 使用 IP 地址,因此只需使用
rr = client.read_holding_registers(60, 2)
应该是够了
消息
2023-04-03 14:57:20,084 MainThread DEBUG factory :266 Factory Response[131]
表示从服务器读取保持寄存器时出错,这可以通过简单地将功能代码编号(在本例中为 3,用于读取保持寄存器)和 128 相加来推断。确保寄存器 59 (%MW59) 在 modbus 服务器中定义。 (请记住,第一个寄存器的地址为寄存器0。)