2022-07-08 23:55:31 +00:00
|
|
|
"""bluetooth usage utility to handle multiple instances."""
|
2022-07-30 00:53:33 +00:00
|
|
|
|
2022-07-08 23:55:31 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
import bleak
|
2022-09-27 18:06:10 +00:00
|
|
|
from bleak.backends.service import BleakGATTServiceCollection
|
|
|
|
import bleak_retry_connector
|
2022-07-08 23:55:31 +00:00
|
|
|
|
2022-08-17 21:42:12 +00:00
|
|
|
from .models import HaBleakClientWrapper, HaBleakScannerWrapper
|
2022-07-08 23:55:31 +00:00
|
|
|
|
2022-07-22 18:19:53 +00:00
|
|
|
ORIGINAL_BLEAK_SCANNER = bleak.BleakScanner
|
2022-08-17 21:42:12 +00:00
|
|
|
ORIGINAL_BLEAK_CLIENT = bleak.BleakClient
|
2022-09-27 18:06:10 +00:00
|
|
|
ORIGINAL_BLEAK_RETRY_CONNECTOR_CLIENT = (
|
|
|
|
bleak_retry_connector.BleakClientWithServiceCache
|
|
|
|
)
|
2022-07-08 23:55:31 +00:00
|
|
|
|
2022-07-22 18:19:53 +00:00
|
|
|
|
|
|
|
def install_multiple_bleak_catcher() -> None:
|
2022-07-08 23:55:31 +00:00
|
|
|
"""Wrap the bleak classes to return the shared instance if multiple instances are detected."""
|
2022-07-30 00:53:33 +00:00
|
|
|
bleak.BleakScanner = HaBleakScannerWrapper # type: ignore[misc, assignment]
|
2022-09-26 13:12:08 +00:00
|
|
|
bleak.BleakClient = HaBleakClientWrapper # type: ignore[misc]
|
2022-09-27 18:06:10 +00:00
|
|
|
bleak_retry_connector.BleakClientWithServiceCache = HaBleakClientWithServiceCache # type: ignore[misc,assignment]
|
2022-07-22 18:19:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
def uninstall_multiple_bleak_catcher() -> None:
|
|
|
|
"""Unwrap the bleak classes."""
|
2022-07-30 00:53:33 +00:00
|
|
|
bleak.BleakScanner = ORIGINAL_BLEAK_SCANNER # type: ignore[misc]
|
2022-08-17 21:42:12 +00:00
|
|
|
bleak.BleakClient = ORIGINAL_BLEAK_CLIENT # type: ignore[misc]
|
2022-09-27 18:06:10 +00:00
|
|
|
bleak_retry_connector.BleakClientWithServiceCache = ORIGINAL_BLEAK_RETRY_CONNECTOR_CLIENT # type: ignore[misc]
|
|
|
|
|
|
|
|
|
|
|
|
class HaBleakClientWithServiceCache(HaBleakClientWrapper):
|
|
|
|
"""A BleakClient that implements service caching."""
|
|
|
|
|
|
|
|
def set_cached_services(self, services: BleakGATTServiceCollection | None) -> None:
|
|
|
|
"""Set the cached services.
|
|
|
|
|
|
|
|
No longer used since bleak 0.17+ has service caching built-in.
|
|
|
|
|
|
|
|
This was only kept for backwards compatibility.
|
|
|
|
"""
|