读取modbus寄存器



我有python脚本从电能表读取寄存器并将值保存到数据库。

脚本工作正常,直到今天,当我试图运行它,我得到了错误:

AttributeError: 'ModbusIOException' object has no attribute 'registers'

我可以正常ping设备…

这是我的代码(它的一半)-甚至简单的输出值都不再工作了

from pymodbus.client import ModbusTcpClient
IP = "192.168.X.X"
client = ModbusTcpClient(IP)
reg = client.read_holding_registers(23322, 2)
calc = round((reg.registers[0] * pow(2, 16) + reg.registers[1]) * 0.01 / 1000, 2)
print(calc)

有什么问题吗?

read_holding_registers的返回值,即代码中的reg变量,仅当请求导致有效响应时才包含ReadHoldingRegistersResponse的实例。在无效响应的情况下,它将包含ExceptionResponse的实例。所以正确的方式应该是这样的:

from pymodbus.client import ModbusTcpClient
from pymodbus.pdu import ExceptionResponse
from pymodbus.exceptions import ModbusIOException
IP = "192.168.X.X"
client = ModbusTcpClient(IP)
reg = client.read_holding_registers(23322, 2)
if reg is not None and not isinstance(reg, ExceptionResponse) and not isinstance(reg, ModbusIOException):
calc = round((reg.registers[0] * pow(2, 16) + reg.registers[1]) * 0.01 / 1000, 2)
print(calc)
else:
print('Modbus request failed')

我还建议您使用异常处理,因为有时pymodbus调用会引发异常,而不是静默失败并返回None值。

您的设备显然返回一个异常而不是值,请查看异常的类型(通过查看您的reg变量)以获得有关如何修复它的线索

最新更新