Cannot read register values using pymodbus

307 Views Asked by At

When I tried the following code, I can connect to the smart meter, but I'm not able to read the register content.

import traceback
from pymodbus.client.sync import ModbusTcpClient
client = ModbusTcpClient('192.168.2.1', port=502)
client.connect()

try:
    res = client.read_holding_registers(0x0063, 1, unit=1)
    print(res.registers)

except:
    traceback.print_exc()
    
client.close()

The gives an exception

  Traceback <Most recent call last>
    File "m2.py", Line 8 ,in <module>
    print<res.registers>
AttributeErro: 'ModbusIOException' objecthas noattribute 'registers'    

Please help me to fix this

2

There are 2 best solutions below

0
On

For those who have similar problem, client.read_******** can return error without raising an exception.
So always check with resp.isError() and handle it.

3
On

You might be missing the client.connect here

from pymodbus.client.sync import ModbusTcpClient
client = ModbusTcpClient(host='192.168.2.1', port=502)
client.connect() ### Added here

try:
   result = client.read_holding_registers(0x0063,1, unit=1)
   print (result.registers)

except Exception as e:
   print (e)

client.close()