使用 pymodbus 转换 Modbus 响应

Converting Modbus response using pymodbus

我想用允许 Modbus TCP 通信的 smart meter 与 PC 通信,PC 将成为主机,我只需要读取保持寄存器并以浮点格式显示它们。我在 pymodbus 2.2.0 中使用 python 我的代码是:

from pymodbus.client.sync import ModbusTcpClient

client = ModbusTcpClient('169.254.00.10')

result = client.read_holding_registers(1845,1,unit=0x01)
print('**************************************************************')
print(result)
client.close()

我得到的是:

DEBUG:pymodbus.transaction:Current transaction state - IDLE
DEBUG:pymodbus.transaction:Running transaction 1
DEBUG:pymodbus.transaction:SEND: 0x0 0x1 0x0 0x0 0x0 0x6 0x1 0x3 0x7 0x35 0x0 0x1
DEBUG:pymodbus.client.sync:New Transaction state 'SENDING'
DEBUG:pymodbus.transaction:Changing transaction state from 'SENDING' to 'WAITING FOR REPLY'
DEBUG:pymodbus.transaction:Changing transaction state from 'WAITING FOR REPLY' to 'PROCESSING REPLY'
DEBUG:pymodbus.transaction:RECV: 0x0 0x1 0x0 0x0 0x0 0x5 0x1 0x3 0x2 0x6 0xc
DEBUG:pymodbus.framer.socket_framer:Processing: 0x0 0x1 0x0 0x0 0x0 0x5 0x1 0x3 0x2 0x6 0xc
DEBUG:pymodbus.factory:Factory Response[ReadHoldingRegistersResponse: 3]
DEBUG:pymodbus.transaction:Adding transaction 1
DEBUG:pymodbus.transaction:Getting transaction 1
DEBUG:pymodbus.transaction:Changing transaction state from 'PROCESSING REPLY' to 'TRANSACTION_COMPLETE'
**************************************************************
ReadRegisterResponse (1)

你知道怎么用pymodbus 2.2.0解决吗?

您必须从响应中提取寄存器,试试这个:

print(result.registers)

或者,如果您想要一个一个:

for reg in result:
    print(reg)

如果您不确定您的服务器是否 运行ning,它的 IP 或端口最好使用独立工具进行测试,如果您在 Windows 上,您可以使用QModMaster 以确保您的设置和映射。

请注意,只有一个 Modbus 寄存器不能得到浮点数,因为 Modbus 寄存器是 16 位整数。如果你想得到一个浮点数,你需要读取两个寄存器。

另一方面,如果您只想验证您的 client-side 代码,您可以 运行 this example 在您的计算机上与您的客户端代码同时进行。当然,您必须将脚本上的 IP 地址更改为 localhost,将端口更改为 5020,并将您正在读取的寄存器编号更改为较小的数字(或增加服务器数据存储的大小) .如果您使用 Windows,您可能需要在防火墙上禁用或创建规则。