在 python 中使用 pymodbus 读取离散输入

Read discrete inputs with pymodbus in python

我正在使用 python 通过 modbus 从控制器收集数据。我阅读了很多解释如何显示从线圈、输入寄存器和保持寄存器收集的数据的文档,但是对于离散寄存器我什么也没看到。

我使用的代码是:

def connect_apm(self):
        try:
            # RTU
            self.client = ModbusClient(method='rtu', port='/dev/ttyUSB0',
                                       timeout=1, stopbits=1, bytesize=8, parity='N', baudrate=9600)
            # IP
            # self.client = ModbusClient('ip', port=)
            self.connection = self.client.connect()
            print('Conexión:', self.connection)
        except Exception as e:
            print('Error al conectar: ', e)

def registers(self):
        memo_binaries = {'Emergency stop': 0x0060}

        return {'self.memo_Binaries': memo_binaries}

def data_fails(self):
    try:
        if self.connection:
            for key, value in self.registers()['self.memo_Binaries'].items():
                rr = self.client.read_discrete_inputs(value, 2, unit=1) # address, count, slave address
                if not rr.isError():
                    val = rr.registers[0]
                    print('{}: {}'.format(key,val))
                else:
                    print('{}: error'.format(key))
                    time.sleep(0.3)
        
    except Exception as e:
        print('Error: ',e)

原代码分为两部分,一部分包含apm连接和寄存器,另一部分搜索输入。

这个案例的输出:

Error:  'ReadDiscreteInputsResponse' object has no attribute 'registers'

如错误消息所示,线圈读取操作的响应是一个 ReadDiscreteInputsResponse 对象,它没有名为 registers 的成员。这是有道理的,因为离散输入(或线圈s)是位大小的变量(或常量)。

您需要 rr.bits[0] 才能访问它们。还有其他与此相关的函数class。请参阅下面的 GitHub link。

资源:

https://pymodbus.readthedocs.io/en/latest/source/example/synchronous_client.html

https://github.com/riptideio/pymodbus/blob/faf557ac8615ce3310f76b190806dae76eba03aa/pymodbus/bit_read_message.py#L63