我当前正在尝试实现具有自定义功能代码的modbus请求。该实现基于以下示例:custom_message.py
import struct
from pymodbus.pdu import ModbusRequest, ModbusResponse
from pymodbus.client.sync import ModbusTcpClient
client = ModbusTcpClient('192.168.0.55')
connection = client.connect()
class CustomModbusResponse(ModbusResponse):
# some fancy decoding should be done here..
pass
class CustomModbusRequest(ModbusRequest):
function_code = 55
def __init__(self, address):
ModbusRequest.__init__(self)
self.address = address
self.count = 1
def encode(self):
return struct.pack('>HH', self.address, self.count)
def decode(self, data):
self.address, self.count = struct.unpack('>HH', data)
def execute(self, context):
if not (1 <= self.count <= 0x7d0):
return self.doException(ModbusExceptions.IllegalValue)
if not context.validate(self.function_code, self.address, self.count):
return self.doException(ModbusExceptions.IllegalAddress)
values = context.getValues(self.function_code, self.address,
self.count)
return CustomModbusResponse(values)
request = CustomModbusRequest(0)
result = client.execute(request)
print(result)
请求按预期方式工作。我可以在网络层上看到正确的响应。但是我无法解析结果。 Pymodbus引发以下错误:
DEBUG:pymodbus.factory:Factory Response[55]
ERROR:pymodbus.factory:Unable to decode response Modbus Error: Unknown response 55
ERROR:pymodbus.transaction:Modbus Error: [Input/Output] Unable to decode request
该示例指出,在这种情况下,我将必须:
如果您实现了当前未实现的新方法,则您 必须在ClientDecoder工厂中注册请求和响应。
是否有一种优雅的方式来执行此操作而不修补库?