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