|
8 | 8 | import os
|
9 | 9 | import sys
|
10 | 10 | import warnings
|
11 |
| -from typing import Callable, Dict, Optional, Union, cast |
| 11 | +from typing import Callable, Dict, Optional, Union, cast, AsyncContextManager |
12 | 12 | from uuid import UUID
|
13 | 13 |
|
14 | 14 | if sys.version_info < (3, 11):
|
@@ -100,9 +100,29 @@ def __init__(self, address_or_ble_device: Union[BLEDevice, str], **kwargs):
|
100 | 100 | # used to override mtu_size property
|
101 | 101 | self._mtu_size: Optional[int] = None
|
102 | 102 |
|
| 103 | + # pairing agent used in manual pairing process, together with pairing_callbacks |
| 104 | + self._pairing_agent: Optional[AsyncContextManager] = None |
| 105 | + |
103 | 106 | def close(self):
|
104 | 107 | self._bus.disconnect()
|
105 | 108 |
|
| 109 | + async def __aenter__(self) -> "BaseBleakClient": |
| 110 | + if self._pairing_callbacks: |
| 111 | + if not self._bus.connected: |
| 112 | + await self._bus.connect() |
| 113 | + |
| 114 | + self._pairing_agent = bluez_agent(self._bus, self._pairing_callbacks) |
| 115 | + await self._pairing_agent.__aenter__() |
| 116 | + |
| 117 | + return await super().__aenter__() |
| 118 | + |
| 119 | + async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 120 | + if self._pairing_agent: |
| 121 | + await self._pairing_agent.__aexit__(exc_type, exc_val, exc_tb) |
| 122 | + self._pairing_agent = None |
| 123 | + |
| 124 | + return await super().__aexit__(exc_type, exc_val, exc_tb) |
| 125 | + |
106 | 126 | # Connectivity methods
|
107 | 127 |
|
108 | 128 | async def connect(self, dangerous_use_bleak_cache: bool = False, **kwargs) -> bool:
|
@@ -354,11 +374,14 @@ async def pair(
|
354 | 374 | """
|
355 | 375 | Pair with the peripheral.
|
356 | 376 | """
|
357 |
| - if callbacks and self._pairing_callbacks: |
| 377 | + # Check _pairing_agent instead of _pairing_callbacks, because even if _pairing_callbacks |
| 378 | + # were provided, this class might not be used as a context manager and therefore pairing |
| 379 | + # agent was not yet registered. |
| 380 | + if callbacks and self._pairing_agent: |
358 | 381 | warnings.warn(
|
359 | 382 | "Ignoring callbacks parameters because pairing_callbacks were provided"
|
360 | 383 | )
|
361 |
| - callbacks = self._pairing_callbacks |
| 384 | + callbacks = None |
362 | 385 |
|
363 | 386 | # See if it is already paired.
|
364 | 387 | reply = await self._bus.call(
|
|
0 commit comments