Skip to content

Commit 4921858

Browse files
authored
Implement service caching for faster reconnects (#69)
1 parent abd5008 commit 4921858

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

switchbot/devices/device.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,12 @@
1010
import async_timeout
1111
import bleak
1212
from bleak.backends.device import BLEDevice
13-
from bleak_retry_connector import BleakClient, establish_connection
13+
from bleak.backends.service import BleakGATTServiceCollection
14+
from bleak_retry_connector import (
15+
BleakClientWithServiceCache,
16+
ble_device_has_changed,
17+
establish_connection,
18+
)
1419

1520
from ..const import DEFAULT_RETRY_COUNT, DEFAULT_SCAN_TIMEOUT
1621
from ..discovery import GetSwitchbotDevices
@@ -61,6 +66,7 @@ def __init__(
6166
self._password_encoded = "%08x" % (
6267
binascii.crc32(password.encode("ascii")) & 0xFFFFFFFF
6368
)
69+
self._cached_services: BleakGATTServiceCollection | None = None
6470

6571
def _commandkey(self, key: str) -> str:
6672
"""Add password to key if set."""
@@ -98,12 +104,17 @@ def name(self) -> str:
98104

99105
async def _send_command_locked(self, key: str, command: bytes) -> bytes:
100106
"""Send command to device and read response."""
101-
client: BleakClient | None = None
107+
client: BleakClientWithServiceCache | None = None
102108
try:
103109
_LOGGER.debug("%s: Connnecting to switchbot", self.name)
104110
client = await establish_connection(
105-
BleakClient, self._device, self.name, max_attempts=1
111+
BleakClientWithServiceCache,
112+
self._device,
113+
self.name,
114+
max_attempts=1,
115+
cached_services=self._cached_services,
106116
)
117+
self._cached_services = client.services
107118
_LOGGER.debug(
108119
"%s: Connnected to switchbot: %s", self.name, client.is_connected
109120
)
@@ -158,6 +169,8 @@ def get_battery_percent(self) -> Any:
158169
def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
159170
"""Update device data from advertisement."""
160171
self._sb_adv_data = advertisement
172+
if self._device and ble_device_has_changed(self._device, advertisement.device):
173+
self._cached_services = None
161174
self._device = advertisement.device
162175

163176
async def get_device_data(

0 commit comments

Comments
 (0)