Skip to content

Commit

Permalink
Handle unexpected disconnects by retrying up to 2 times
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco committed May 1, 2024
1 parent 8f82650 commit e96e96c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
2 changes: 2 additions & 0 deletions airthings_ble/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,5 @@
PERCENTAGE_MAX = 100
RADON_MAX = 16383
TEMPERATURE_MAX = 100

MAX_UPDATE_ATTEMPTS = 3
21 changes: 19 additions & 2 deletions airthings_ble/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()

Expand Down

0 comments on commit e96e96c

Please sign in to comment.