Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The pymodbus connection sometimes doesn't respond?

I'm use "pymodbus" lib to connect PLC devices. The device is used Modbus RTU over TCP that devices will return the temperature and humidity of the environment.

map address list

  • 0001: temperature
  • 0002: humidity

I performed once to get value and it can succeed. But I'm using while loop sometimes get error. I don't know why.

code:

from time import sleep
from pymodbus.client.sync import ModbusTcpClient
from pymodbus.framer.rtu_framer import ModbusRtuFramer

from pymodbus.register_read_message import ReadHoldingRegistersResponse

client = ModbusTcpClient(host='192.168.1.1', port=5000, framer=ModbusRtuFramer)    
client.connect()
while True:
    rr = client.read_holding_registers(0, 2, unit=1)

    if isinstance(rr, ReadHoldingRegistersResponse):
        temp = rr.registers
        print(temp)
    else:
        print('error')
    sleep(1)
client.close()

output:

> ...
> [189, 444]
> [189, 443]
> [189]
> error
> error
> ...

We can see that sometimes the result is obtained normally, sometimes the result is incomplete, and sometimes the result is not available.

What should I do to solve this problem, I want to monitor this device. Thank you.

like image 683
frank Avatar asked May 30 '26 05:05

frank


1 Answers

Yes, I see this all the time in my pymodbus code. I suspect there's something wrong with the implementation when doing succesive reads. What I do, is quite simply, to retry the failed read after a slight delay. And that usually gets it working again. Alternatively, try closing and re-connecting the client and re-attempt the reading. Also try increasing the sleep time. Let me know how it goes!

like image 69
Sergio Flores Avatar answered Jun 01 '26 19:06

Sergio Flores