4

I am working on pymodbus. Trying to read the data from multiple units (multiple slaves) it gives me data but when the 1 of the slaves did not respond or is off the other slaves also shows the error after some time. please help. Thank you

from pymodbus.client.sync import ModbusSerialClient as ModbusClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.exceptions import ModbusIOException
from pymodbus.exceptions import ConnectionException

def length(x):
    client = ModbusClient(method='rtu', port='/dev/ttyUSB0', timeout=2, stopbits = 1, bytesize = 8,  parity='N', baudrate = 9600)
    client.connect()
    rr = client.read_holding_registers(address=1, count=4, unit=x);
    decoder = BinaryPayloadDecoder.fromRegisters(rr.registers, Endian.Big, wordorder=Endian.Big);
    a=str(decoder.decode_32bit_float());
    c = int (float(a))
    client.close()
    print("length",c)
    client = ModbusClient(method='rtu', port='/dev/ttyUSB0', timeout=2, stopbits = 1, bytesize = 8,  parity='N', baudrate = 9600)
    client.connect()
    rr = client.read_holding_registers(address=7, count=4, unit=x);
    decoder = BinaryPayloadDecoder.fromRegisters(rr.registers, Endian.Big, wordorder=Endian.Big);
    b=str(decoder.decode_32bit_float());
    d = int (float(b))
    client.close()
    print("speed",d)
    print(x)
    return c,d
Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
Eng
  • 41
  • 4

1 Answers1

0

I've improved your code with the .isError() method in pymodbus as the following:

from pymodbus.client.sync import ModbusSerialClient as ModbusClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder

def error_checker(instance):
    if not instance.isError():
        '''.isError() implemented in pymodbus 1.4.0 and above.'''
        decoder = BinaryPayloadDecoder.fromRegisters(
            instance.registers, byteorder=Endian.Big, wordorder=Endian.Big
        )
        return decoder.decode_32bit_float()
    else:
        # Error handling.
        return None

def length(x):
    client = ModbusClient(
        method='rtu',
        port='/dev/ttyUSB0',
        timeout=2, stopbits=1, bytesize=8, parity='N', baudrate=9600
    )
    try:
        client.connect()
        rr = client.read_holding_registers(address=1, count=4, unit=x)
        c = error_checker(rr)
        print("length: ", c)
        rr = client.read_holding_registers(address=7, count=4, unit=x)
        d = error_checker(rr)
        print("speed: ", d)
        return c, d
    except Exception as exc:
        print(exc)
    finally:
        client.close()
Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150