winder
winder

Reputation: 23

Read discrete inputs with pymodbus in python

I am collecting data from a controller via modbus with python. I read a lot of documentation that explains how to show the data collected from coils, input registers and holding registers, but for discrete registers I don`t see nothing about it.

The code I am using is:

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)

The original code was divided in two parts, one contains the apm connection and the registers, the other search the input.

The output of this case:

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

Upvotes: 2

Views: 4066

Answers (1)

Tagli
Tagli

Reputation: 2592

As the error message indicates, the response of a coil read operation is a ReadDiscreteInputsResponse object and it has no members named registers. This makes sense, because discrete inputs (or coils) are bit sized variables (or constants).

You need rr.bits[0] in order to access them. There are also other functions related with this class. See the GitHub link below.

Resources:

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

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

Upvotes: 1

Related Questions