Skip to content

Commit

Permalink
Recover modbus connection after connectivity issues
Browse files Browse the repository at this point in the history
  • Loading branch information
vortizhe committed Nov 12, 2023
1 parent ebb9d00 commit dfa9bbb
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions custom_components/ingeteam_modbus/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def __init__(
):
"""Initialize the Modbus hub."""
self._hass = hass
self._client = ModbusTcpClient(host=host, port=port)
self._client = ModbusTcpClient(host=host, port=port, timeout=max(3, (scan_interval - 1)))
self._lock = threading.Lock()
self._name = name
self._address = address
Expand Down Expand Up @@ -161,10 +161,14 @@ async def async_refresh_modbus_data(self, _now: Optional[int] = None) -> None:
if not self._sensors:
return

if not self._check_and_reconnect():
#if not connected, skip
return

try:
update_result = self.read_modbus_data()
except Exception as e:
_LOGGER.exception("Error reading modbus data")
_LOGGER.exception("Error reading modbus data", exc_info=True)
update_result = False

if update_result:
Expand All @@ -180,11 +184,26 @@ def close(self):
"""Disconnect client."""
with self._lock:
self._client.close()

def _check_and_reconnect(self):
if not self._client.connected:
_LOGGER.info("modbus client is not connected, trying to reconnect")
return self.connect()

return self._client.connected

def connect(self):
"""Connect client."""
result = False
with self._lock:
self._client.connect()
result = self._client.connect()
if result:
_LOGGER.info("successfully connected to %s:%s",
self._client.comm_params.host, self._client.comm_params.port)
else:
_LOGGER.warning("not able to connect to %s:%s",
self._client.comm_params.host, self._client.comm_params.port)
return result

@property
def has_meter(self):
Expand Down

0 comments on commit dfa9bbb

Please sign in to comment.