|
25 | 25 | UPDATE_TOPIC = f"{DOMAIN}_update" |
26 | 26 | SCAN_INTERVAL = timedelta(seconds=10) |
27 | 27 | ERROR_INTERVAL = timedelta(seconds=300) |
28 | | -MAX_FAILS = 10 |
| 28 | +ERROR_ITERVAL_MAPPING = [10, 60, 300, 600, 3000, 6000] |
29 | 29 | NOTIFICATION_ID = "ph803w_device_notification" |
30 | 30 | NOTIFICATION_TITLE = "PH-803W Device status" |
31 | 31 |
|
@@ -80,6 +80,7 @@ def __init__(self, hass, device_client: device.Device) -> None: |
80 | 80 | self.hass = hass |
81 | 81 | self.device_client = device_client |
82 | 82 | self.device_client.register_callback(self.dispatcher_new_data) |
| 83 | + self.device_client.register_callback(self.reset_fail_counter) |
83 | 84 | self.host = self.device_client.host |
84 | 85 | self._shutdown = False |
85 | 86 | self._fails = 0 |
@@ -113,30 +114,26 @@ def shutdown(event): |
113 | 114 | _LOGGER.debug("Graceful shutdown") |
114 | 115 | return |
115 | 116 |
|
116 | | - if self._fails > MAX_FAILS: |
117 | | - _LOGGER.error("Failed to reconnect. Thread stopped") |
118 | | - persistent_notification.create( |
119 | | - self.hass, |
120 | | - "Error:<br/>Connection to PH-803W device failed " |
121 | | - "the maximum number of times. Thread has stopped", |
122 | | - title=NOTIFICATION_TITLE, |
123 | | - notification_id=NOTIFICATION_ID, |
124 | | - ) |
125 | | - return |
126 | | - |
127 | 117 | try: |
128 | 118 | self.device_client.run(once=False) |
129 | | - except device.DeviceError: |
| 119 | + except (device.DeviceError, ConnectionError): |
130 | 120 | _LOGGER.exception("Failed to read data, attempting to recover") |
131 | 121 | self.device_client.close() |
132 | 122 | self._fails += 1 |
133 | | - sleep_time = self._fails * ERROR_INTERVAL.total_seconds() |
| 123 | + error_mapping = self._fails |
| 124 | + if error_mapping >= len(ERROR_ITERVAL_MAPPING): |
| 125 | + error_mapping = len(ERROR_ITERVAL_MAPPING) - 1 |
| 126 | + sleep_time = timedelta(seconds=ERROR_ITERVAL_MAPPING[error_mapping]) |
134 | 127 | _LOGGER.debug( |
135 | 128 | "Sleeping for fail #%s, in %s seconds", self._fails, sleep_time |
136 | 129 | ) |
137 | 130 | self.device_client.reset_socket() |
138 | 131 | time.sleep(sleep_time) |
139 | 132 |
|
| 133 | + @callback |
| 134 | + def reset_fail_counter(self): |
| 135 | + self._fails = 0 |
| 136 | + |
140 | 137 | @callback |
141 | 138 | def dispatcher_new_data(self): |
142 | 139 | """Noyifying HASS that new data is ready to read.""" |
|
0 commit comments