diff --git a/airthings_ble/const.py b/airthings_ble/const.py index 313504e..166b14d 100644 --- a/airthings_ble/const.py +++ b/airthings_ble/const.py @@ -52,3 +52,5 @@ PERCENTAGE_MAX = 100 RADON_MAX = 16383 TEMPERATURE_MAX = 100 + +MAX_UPDATE_ATTEMPTS = 3 diff --git a/airthings_ble/parser.py b/airthings_ble/parser.py index fc79255..6140eb8 100644 --- a/airthings_ble/parser.py +++ b/airthings_ble/parser.py @@ -19,6 +19,7 @@ from bleak_retry_connector import BleakClientWithServiceCache, establish_connection from .const import ( + MAX_UPDATE_ATTEMPTS, BQ_TO_PCI_MULTIPLIER, CHAR_UUID_DATETIME, CHAR_UUID_DEVICE_NAME, @@ -636,6 +637,23 @@ def _handle_disconnect( disconnect_future.set_result(True) async def update_device(self, ble_device: BLEDevice) -> AirthingsDevice: + """Connects to the device through BLE and retrieves relevant data""" + for attempt in range(MAX_UPDATE_ATTEMPTS): + is_final_attempt = attempt == MAX_UPDATE_ATTEMPTS - 1 + try: + return await self._update_device(ble_device) + except DisconnectedError: + if is_final_attempt: + raise + self.logger.debug( + "Unexpectedly disconnected from %s", ble_device.address + ) + except BleakError as err: + if is_final_attempt: + raise + self.logger.debug("Bleak error: %s", err) + + async def _update_device(self, ble_device: BLEDevice) -> AirthingsDevice: """Connects to the device through BLE and retrieves relevant data""" device = AirthingsDevice() loop = asyncio.get_running_loop() @@ -663,8 +681,7 @@ async def update_device(self, ble_device: BLEDevice) -> AirthingsDevice: # Clear the char cache since a char is likely # missing from the cache await client.clear_cache() - except DisconnectedError: - self.logger.debug("Unexpectedly disconnected from %s", client.address) + raise finally: await client.disconnect()