pymodbus: polling multiple sensors

49 Views Asked by At

I am polling temperature and humidity sensors via a USB-RS485 converter. If there is only one sensor, everything works fine without using of sleep function. But if you need to poll two sensors, without sleeps an error occurs:

[SENS_0] 41.8%; 26.4°C [SENS_1] 41.8%; 26.3°C
Traceback (most recent call last):
  File "/home/zenbooster/work/sht20/./sens.py", line 23, in <module>
    sens.read()
  File "/home/zenbooster/work/sht20/dev.py", line 19, in read
    self.t = res.registers[0] / 10
AttributeError: 'ModbusIOException' object has no attribute 'registers'

Why does this happen, and is there a more elegant solution than using delays? Or at least a way to calculate these delays?

dev.py:

class csSensBase:
  def __init__(self, cli, id):
    self.cli = cli
    self.id = id

  def get_t(self):
    return self.t

  def get_h(self):
    return self.h

  def get_th(self):
    return (self.t, self.h)

class csSens_XY_MD01(csSensBase):
  def read(self):
    cli = self.cli
    res = cli.read_input_registers(1, 2, slave=self.id)
    self.t = res.registers[0] / 10
    self.h = res.registers[1] / 10
    return res

class csSens_CWT_THxxS(csSensBase):
  def read(self):
    cli = self.cli
    res = cli.read_input_registers(0, 2, slave=self.id)
    self.h = res.registers[0] / 10
    self.t = res.registers[1] / 10
    return res

sens.py:

#!/usr/bin/env python3
from pymodbus.client import ModbusSerialClient
import sys
from time import sleep
from dev import *

cli = ModbusSerialClient(port='/dev/ttyUSB0', baudrate=9600)

sens_list = [csSens_XY_MD01(cli, 2), csSens_CWT_THxxS(cli, 3)]

while(1):
  try:
    i = 0
    for sens in sens_list:
      sens.read()
      t, h = sens.get_th()
      print(f'[SENS_{i}] {h}%; {t}\u00B0C ', end='')
      sys.stdout.flush()
      i += 1
      sleep(0.15)

    print('')

  except KeyboardInterrupt:
    break

print('') # after ^C

print('end')
cli.close()
0

There are 0 best solutions below