首页 > 解决方案 > pymodbus 自定义请求中的单元参数

问题描述

这是我在这里的第一篇文章。我潜伏了一段时间。

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

我正在使用一种具有自定义寄存器和命令的旧 Modbus 设备。我能够读/写线圈、寄存器等。问题是这个设备需要特殊的命令来进行某种复位。

我做了一些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。

请帮忙。

标签: pymodbus

解决方案


您将不得不传递unit自定义消息,这应该可以解决问题。 request = CustomModbusRequest(170, unit=<unit_id>). 您还必须更新__init__ofCustomModbusRequest以将额外的 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)


推荐阅读