Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework error_interval #14

Merged
merged 3 commits into from
May 30, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Reqork error_interval
  • Loading branch information
dala318 committed May 30, 2022
commit 5b4cb0489dab9efba13dcbc509e0936aa9c408d4
25 changes: 11 additions & 14 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
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 +80,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 +114,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 = timedelta(seconds=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