pymodbus自定义请求中的单位参数

Unit parameter in pymodbus custom request

这是我第一次 post 来这里。 我潜伏了一段时间

所以,我在 pymodbus ModbusTcpClient 中遇到有关自定义消息的问题

我正在玩一台具有自定义寄存器和命令的旧 Modbus 设备。 我能够 read/write 线圈、寄存器等。 问题是此设备需要特殊命令才能进行某种重置。

我做了一些 wireshark 嗅探并制作了自定义消息,但我在定义单元参数时遇到了困难。

这里是代码片段:

class CustomModbusRequest(ModbusRequest):
    function_code = 8

    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)

def custom_8():
    client = ModbusTcpClient('192.168.0.222')
    connection = client.connect()
    request = CustomModbusRequest(170)
    result = client.execute(request)
    print(result)
    time.sleep(1)

在正常的读寄存器请求中有指定的单元参数,像这样:

    request = client.read_input_registers(513,4, unit=0x4)

在自定义请求中,我不知道如何指定。在 wireshark 中,我可以看到在自定义消息中,我正在向地址 0 发送请求,我需要使用地址 4。

求求你帮忙

您必须将 unit 传递给自定义消息,这应该可以解决问题。 request = CustomModbusRequest(170, unit=<unit_id>)。您还必须更新 CustomModbusRequest__init__ 以将额外的 kwargs 传递给 parent

class CustomModbusRequest(ModbusRequest):
    function_code = 8

    def __init__(self, address, **kwargs):
        ModbusRequest.__init__(self, **kwargs)
        self.address = address
        self.count = 1


...
...

request = CustomModbusRequest(170, unit=<unit_id>)
result = client.execute(request)