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

Handle unexpected disconnects by retrying up to 2 times #37

Merged
merged 1 commit into from
May 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
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
22 changes: 20 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,24 @@ 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)
raise RuntimeError("Should not reach this point")

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 +682,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