Skip to content

Commit

Permalink
Implement bluetooth service caching
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco committed Aug 12, 2022
1 parent dfce1a7 commit e0815a9
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 14 deletions.
5 changes: 3 additions & 2 deletions aiohomekit/controller/ble/bleak.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

import uuid

from bleak import BleakClient, BleakError
from bleak import BleakError
from bleak.backends.characteristic import BleakGATTCharacteristic
from bleak.backends.device import BLEDevice
from bleak_retry_connector import BleakClientWithServiceCache

from .const import HAP_MIN_REQUIRED_MTU

Expand All @@ -13,7 +14,7 @@
CHAR_DESCRIPTOR_UUID = uuid.UUID(CHAR_DESCRIPTOR_ID)


class AIOHomeKitBleakClient(BleakClient):
class AIOHomeKitBleakClient(BleakClientWithServiceCache):
"""Wrapper for bleak.BleakClient that auto discovers the max mtu."""

def __init__(self, address_or_ble_device: BLEDevice | str) -> None:
Expand Down
3 changes: 3 additions & 0 deletions aiohomekit/controller/ble/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from collections.abc import Callable

from bleak.backends.device import BLEDevice
from bleak.backends.service import BleakGATTServiceCollection
from bleak_retry_connector import (
BleakAbortedError,
BleakConnectionError,
Expand All @@ -39,6 +40,7 @@ async def establish_connection(
name: str,
disconnected_callback: Callable[[AIOHomeKitBleakClient], None],
max_attempts: int = MAX_CONNECT_ATTEMPTS,
cached_services: BleakGATTServiceCollection | None = None,
) -> AIOHomeKitBleakClient:
"""Establish a connection to the accessory."""
try:
Expand All @@ -48,6 +50,7 @@ async def establish_connection(
name,
disconnected_callback,
max_attempts=max_attempts,
cached_services=cached_services,
)
except (BleakAbortedError, BleakConnectionError) as ex:
raise AccessoryDisconnectedError(ex) from ex
Expand Down
13 changes: 11 additions & 2 deletions aiohomekit/controller/ble/pairing.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
from typing import TYPE_CHECKING, Any, TypeVar, cast

from bleak.backends.device import BLEDevice
from bleak.backends.service import BleakGATTServiceCollection
from bleak.exc import BleakError
from bleak_retry_connector import ble_device_has_changed

from aiohomekit.exceptions import (
AccessoryDisconnectedError,
Expand Down Expand Up @@ -123,6 +125,8 @@ def __init__(
self.id = pairing_data["AccessoryPairingID"]
self.device = device
self.client = client
self._cached_services: BleakGATTServiceCollection | None = None

self.pairing_data = pairing_data
self.description = description
self.controller = controller
Expand Down Expand Up @@ -200,7 +204,8 @@ def transport(self) -> Transport:

def _async_ble_device_update(self, device: BLEDevice) -> None:
"""Update the BLE device."""
if self.device and device.address != self.device.address:
if self.device and ble_device_has_changed(self.device, device):
self._cached_services = None
logger.debug(
"BLE address changed from %s to %s; closing connection",
self.device.address,
Expand Down Expand Up @@ -322,7 +327,9 @@ async def _ensure_connected(self):
self.device,
self.name,
self._async_disconnected,
cached_services=self._cached_services,
)
self._cached_services = self.client.services
logger.debug(
"%s: Connected, processing subscriptions: %s",
self.name,
Expand Down Expand Up @@ -429,7 +436,9 @@ async def _async_fetch_gatt_database(self) -> Accessories:
logger.debug("%s: Fetching GATT database", self.name)
accessory = Accessory()
accessory.aid = 1
for service in self.client.services:
# Never use the cache when fetching the GATT database
services = await self.client.get_services()
for service in services:
s = accessory.add_service(normalize_uuid(service.uuid))

for char in service.characteristics:
Expand Down
19 changes: 10 additions & 9 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ commentjson = "^0.9.0"
aiocoap = ">=0.4.1"
bleak = ">=0.14.2"
chacha20poly1305-reuseable = ">=0.0.4"
bleak-retry-connector = ">=1.5.0"
bleak-retry-connector = ">=1.7.0"
orjson = ">=3.7.8"

[tool.poetry.dev-dependencies]
Expand Down

0 comments on commit e0815a9

Please sign in to comment.