Skip to content

Commit

Permalink
Merge pull request #14 from dala318/error_interval
Browse files Browse the repository at this point in the history
Rework error_interval
  • Loading branch information
dala318 authored May 30, 2022
2 parents 33a501c + 72905dd commit e57e234
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 22 deletions.
27 changes: 11 additions & 16 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@
_LOGGER = logging.getLogger(__name__)

UPDATE_TOPIC = f"{DOMAIN}_update"
SCAN_INTERVAL = timedelta(seconds=10)
ERROR_INTERVAL = timedelta(seconds=300)
MAX_FAILS = 10
ERROR_ITERVAL_MAPPING = [10, 60, 300, 600, 3000, 6000]
NOTIFICATION_ID = "ph803w_device_notification"
NOTIFICATION_TITLE = "PH-803W Device status"

Expand Down Expand Up @@ -80,6 +78,7 @@ def __init__(self, hass, device_client: device.Device) -> None:
self.hass = hass
self.device_client = device_client
self.device_client.register_callback(self.dispatcher_new_data)
self.device_client.register_callback(self.reset_fail_counter)
self.host = self.device_client.host
self._shutdown = False
self._fails = 0
Expand Down Expand Up @@ -113,30 +112,26 @@ def shutdown(event):
_LOGGER.debug("Graceful shutdown")
return

if self._fails > MAX_FAILS:
_LOGGER.error("Failed to reconnect. Thread stopped")
persistent_notification.create(
self.hass,
"Error:<br/>Connection to PH-803W device failed "
"the maximum number of times. Thread has stopped",
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
return

try:
self.device_client.run(once=False)
except device.DeviceError:
except (device.DeviceError, ConnectionError):
_LOGGER.exception("Failed to read data, attempting to recover")
self.device_client.close()
self._fails += 1
sleep_time = self._fails * ERROR_INTERVAL.total_seconds()
error_mapping = self._fails
if error_mapping >= len(ERROR_ITERVAL_MAPPING):
error_mapping = len(ERROR_ITERVAL_MAPPING) - 1
sleep_time = ERROR_ITERVAL_MAPPING[error_mapping]
_LOGGER.debug(
"Sleeping for fail #%s, in %s seconds", self._fails, sleep_time
)
self.device_client.reset_socket()
time.sleep(sleep_time)

@callback
def reset_fail_counter(self):
self._fails = 0

@callback
def dispatcher_new_data(self):
"""Noyifying HASS that new data is ready to read."""
Expand Down
9 changes: 3 additions & 6 deletions lib/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,12 @@ async def run_async(self, once: bool = True) -> bool:

def run(self, once: bool = True) -> bool:
self._loop = True
if self._socket.fileno() == -1:
self.reset_socket()
self._connect()
if once:
if self._socket.fileno() == -1:
self.reset_socket()
self._connect()
return self._run(once)
else:
if self._socket.fileno() == -1:
self.reset_socket()
self._connect()
self._run(once)
return not self._loop

Expand Down

0 comments on commit e57e234

Please sign in to comment.