Skip to content

Commit

Permalink
BleakClient: Support performing GATT service disocvery after pairing
Browse files Browse the repository at this point in the history
  • Loading branch information
bojanpotocnik committed Nov 22, 2022
1 parent 7f8c72e commit cfd09ba
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
7 changes: 6 additions & 1 deletion bleak/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,12 @@ async def pair(
BleakPairingFailedError:
if pairing failed (rejected, wrong pin, etc.)
"""
return await self._backend.pair(callbacks, **kwargs)
if await self._backend.pair(callbacks, **kwargs):
# If services were already discovered during connection procedure, this will return cached
# services anyway. If `skip_service_discovery=True` was used, this will perform the discovery.
await self._backend.get_services()
return True
return False

async def unpair(self) -> bool:
"""
Expand Down
13 changes: 11 additions & 2 deletions examples/pairing_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,19 @@ async def main(addr: str, unpair: bool) -> None:

print("pairing...")

async with BleakClient(device) as client, AgentCallbacks() as callbacks:
async with (
BleakClient(device) as client,
# If the peripheral device sends Slave Security Request immediately upon establishing connection,
# the central device shall respond with the pairing request - usually before starting/finishing
# service discovery, that is before connect() method normally returns. In such cases the pairing
# process usually fails with "Pairing not supported" error - as a workaround,
# BleakClient(device, skip_service_discovery=True) as client,
# can be used, which will execute service discovery only after pairing.
AgentCallbacks() as callbacks,
):
try:
await client.pair(callbacks)
print("pairing successful")
print(f"pairing successful, {len(client.services.services)} services")
except BleakPairingCancelledError:
print("paring was canceled")
except BleakPairingFailedError:
Expand Down

0 comments on commit cfd09ba

Please sign in to comment.