Skip to content

Commit 1a0df03

Browse files
committed
Fix some Modbus errors. Add modbus debuging.
1 parent 0bdb038 commit 1a0df03

File tree

1 file changed

+38
-11
lines changed

1 file changed

+38
-11
lines changed

custom_components/weishaupt_modbus/modbusobject.py

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import warnings
99

10-
from pymodbus import ModbusException
10+
from pymodbus import ModbusException, ExceptionResponse
1111
from pymodbus.client import AsyncModbusTcpClient
1212

1313
from homeassistant.config_entries import ConfigEntry
@@ -91,27 +91,54 @@ def __init__(self, modbus_api: ModbusAPI, modbus_item: ModbusItem) -> None:
9191
"""
9292
self._modbus_item = modbus_item
9393
self._modbus_client = modbus_api.get_device()
94+
# await self._modbus_client.connect()
9495

9596
@property
9697
async def value(self):
9798
"""Returns the value from the modbus register."""
9899
if self._modbus_client is None:
99100
return None
101+
if not self._modbus_client.connected:
102+
await self._modbus_client.connect()
103+
100104
val = None
101105
match self._modbus_item.type:
102106
case TYPES.SENSOR | TYPES.SENSOR_CALC:
103107
# Sensor entities are read-only
104-
mbr = await self._modbus_client.read_input_registers(
105-
self._modbus_item.address, slave=1
106-
)
107-
if len(mbr.registers) > 0:
108-
val = mbr.registers[0]
108+
try:
109+
mbr = await self._modbus_client.read_input_registers(
110+
self._modbus_item.address, slave=1
111+
)
112+
if len(mbr.registers) > 0:
113+
val = mbr.registers[0]
114+
except ModbusException as exc:
115+
print(f"Received ModbusException({exc}) from library")
116+
return None
117+
if mbr.isError():
118+
print(f"Received Modbus library error({mbr})")
119+
return None
120+
if isinstance(mbr, ExceptionResponse):
121+
print(f"Received Modbus library exception ({mbr})")
122+
return None
123+
# THIS IS NOT A PYTHON EXCEPTION, but a valid modbus message
124+
109125
case TYPES.SELECT | TYPES.NUMBER | TYPES.NUMBER_RO:
110-
mbr = await self._modbus_client.read_holding_registers(
111-
self._modbus_item.address, slave=1
112-
)
113-
if len(mbr.registers) > 0:
114-
val = mbr.registers[0]
126+
try:
127+
mbr = await self._modbus_client.read_holding_registers(
128+
self._modbus_item.address, slave=1
129+
)
130+
if len(mbr.registers) > 0:
131+
val = mbr.registers[0]
132+
except ModbusException as exc:
133+
print(f"Received ModbusException({exc}) from library")
134+
return None
135+
if mbr.isError():
136+
print(f"Received Modbus library error({mbr})")
137+
return None
138+
if isinstance(mbr, ExceptionResponse):
139+
print(f"Received Modbus library exception ({mbr})")
140+
return None
141+
# THIS IS NOT A PYTHON EXCEPTION, but a valid modbus message
115142
case _:
116143
val = None
117144
return val

0 commit comments

Comments
 (0)