ble-bond 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ble_bond/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """ble-bond: bonded Bluetooth LE sessions for devices that pair in a button window.
2
+
3
+ For devices that accept a new bond only for a few seconds after a button press, and then answer
4
+ one request at a time with no request id, usually through a Home Assistant Bluetooth proxy.
5
+ The device library brings its framing (an :class:`Assembler`) and its :class:`LinkPolicy`;
6
+ ble-bond handles pairing, which adapter or proxy each attempt used, the BlueZ pairing agent, and
7
+ matching replies to requests.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from ble_bond.bluez import bluez_device_path, bluez_pairing_agent, remove_bluez_bond
13
+ from ble_bond.exceptions import (
14
+ ConnectionLost,
15
+ LinkError,
16
+ PairingRequired,
17
+ PairingUnsupported,
18
+ RequestTimeout,
19
+ )
20
+ from ble_bond.link import Accept, Assembler, BondedLink, LinkPolicy, SubscribeRetry
21
+
22
+ __version__ = "1.0.0"
23
+
24
+ __all__ = [
25
+ "Accept",
26
+ "Assembler",
27
+ "BondedLink",
28
+ "ConnectionLost",
29
+ "LinkError",
30
+ "LinkPolicy",
31
+ "PairingRequired",
32
+ "PairingUnsupported",
33
+ "RequestTimeout",
34
+ "SubscribeRetry",
35
+ "__version__",
36
+ "bluez_device_path",
37
+ "bluez_pairing_agent",
38
+ "remove_bluez_bond",
39
+ ]
ble_bond/bluez.py ADDED
@@ -0,0 +1,220 @@
1
+ """A temporary BlueZ pairing agent, so a local Linux adapter can bond with the device.
2
+
3
+ A device with no display or keypad bonds with Just Works pairing, and many ask for it
4
+ themselves with a security request as soon as the link is up. BlueZ hands such a request to the
5
+ default ``org.bluez.Agent1`` for confirmation, and with no agent registered (Home Assistant
6
+ registers none) it refuses, so bleak's ``Pair`` fails with
7
+ ``org.bluez.Error.AuthenticationFailed``. ``bluetoothctl`` registers an agent on startup, which
8
+ is why pairing from it works. While the device is being paired, this module registers a
9
+ ``NoInputNoOutput`` agent as the default, accepts requests for that device and rejects the rest.
10
+ It can also remove BlueZ's half of a bond the device no longer honours, so pairing runs again.
11
+
12
+ The agent and its one-at-a-time lock are adapted from alpha-hwr's
13
+ ``src/alpha_hwr/core/pairing_agent.py`` (MIT, Copyright (c) 2026 Emmanuel Levijarvi,
14
+ https://github.com/eman/alpha-hwr); its notice is in THIRD_PARTY_NOTICES.md.
15
+
16
+ This module does not use ``from __future__ import annotations``: dbus_fast's ``@method()``
17
+ reads the D-Bus signature from the annotations when the class is defined.
18
+ """
19
+
20
+ import asyncio
21
+ import contextlib
22
+ import logging
23
+ import sys
24
+ import weakref
25
+ from collections.abc import AsyncGenerator
26
+ from typing import TYPE_CHECKING, Any, Final
27
+
28
+ if TYPE_CHECKING:
29
+ from bleak.backends.device import BLEDevice
30
+ from dbus_fast.aio import MessageBus
31
+
32
+ if sys.platform == "linux":
33
+ from bleak.backends.bluezdbus.manager import BlueZManager
34
+ else: # bleak's BlueZ backend refuses to import elsewhere
35
+ BlueZManager = Any
36
+
37
+ _LOGGER = logging.getLogger(__name__)
38
+
39
+ AGENT_PATH: Final = "/org/ble_bond/agent"
40
+ """Prefix of the agent's object path; each device gets its own path below it."""
41
+ BLUEZ_SERVICE: Final = "org.bluez"
42
+ AGENT_MANAGER_INTERFACE: Final = "org.bluez.AgentManager1"
43
+ ADAPTER_INTERFACE: Final = "org.bluez.Adapter1"
44
+
45
+ _agent_locks: "weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock]" = (
46
+ weakref.WeakKeyDictionary()
47
+ )
48
+ """One agent at a time, as BlueZ has a single default agent for the whole system. One lock per
49
+ event loop: an ``asyncio.Lock`` binds to the loop it is first contended on."""
50
+
51
+
52
+ def _agent_lock() -> asyncio.Lock:
53
+ loop = asyncio.get_running_loop()
54
+ if (lock := _agent_locks.get(loop)) is None:
55
+ lock = _agent_locks[loop] = asyncio.Lock()
56
+ return lock
57
+
58
+
59
+ def bluez_device_path(device: "BLEDevice") -> str | None:
60
+ """Return the BlueZ object path of a device seen by a local adapter, else None."""
61
+ details = device.details
62
+ if isinstance(details, dict) and isinstance(path := details.get("path"), str):
63
+ return path
64
+ return None
65
+
66
+
67
+ async def _bluez_bus() -> "tuple[BlueZManager, MessageBus] | None":
68
+ """Return bleak's BlueZ manager and its system bus, or None where there is no BlueZ."""
69
+ try:
70
+ # Linux only; elsewhere the import fails and lands in the except below.
71
+ from bleak.backends.bluezdbus.manager import (
72
+ get_global_bluez_manager, # pyright: ignore[reportAttributeAccessIssue]
73
+ )
74
+
75
+ manager = await get_global_bluez_manager()
76
+ except Exception as err: # no BlueZ here
77
+ _LOGGER.debug("BlueZ unavailable: %s", err)
78
+ return None
79
+ # bleak's own system bus, which BlueZ ties agents to. It is private, so a bleak release
80
+ # that renames it turns pairing through a local adapter back into a plain Pair call.
81
+ bus: MessageBus | None = getattr(manager, "_bus", None)
82
+ if bus is None:
83
+ _LOGGER.debug("bleak's BlueZ manager has no system bus to register an agent on")
84
+ return None
85
+ return manager, bus
86
+
87
+
88
+ async def _call(
89
+ bus: "MessageBus", path: str, interface: str, member: str, signature: str, body: list[object]
90
+ ) -> None:
91
+ from dbus_fast import Message, MessageType
92
+ from dbus_fast.errors import DBusError
93
+
94
+ reply = await bus.call(
95
+ Message(
96
+ destination=BLUEZ_SERVICE,
97
+ path=path,
98
+ interface=interface,
99
+ member=member,
100
+ signature=signature,
101
+ body=body,
102
+ )
103
+ )
104
+ if reply.message_type == MessageType.ERROR:
105
+ raise DBusError(reply.error_name or "unknown", str(reply.body))
106
+
107
+
108
+ async def remove_bluez_bond(device: "BLEDevice") -> bool:
109
+ """Make BlueZ forget its bond with ``device``, so the next connection pairs afresh.
110
+
111
+ A device that has lost its half of a bond refuses the old keys, and while BlueZ still holds
112
+ them bleak only reconnects and never pairs, so pressing the button cannot help. Call this
113
+ only once the device has refused the old bond while its pairing window is open, then
114
+ connect again inside the window: removing it earlier strands an adapter whose bond still
115
+ worked if the user never presses the button. BlueZ drops the device object with the bond
116
+ and recreates it from the next advertisement. Returns True when a bond was removed; does
117
+ nothing for a device not seen by a local BlueZ adapter.
118
+ """
119
+ path = bluez_device_path(device)
120
+ if path is None or (bluez := await _bluez_bus()) is None:
121
+ return False
122
+ manager, bus = bluez
123
+ if not manager.is_paired(path):
124
+ return False
125
+ try:
126
+ await _call(bus, path.rsplit("/", 1)[0], ADAPTER_INTERFACE, "RemoveDevice", "o", [path])
127
+ except Exception as err: # pairing will report what is left
128
+ _LOGGER.debug("Could not remove the BlueZ bond for %s: %s", path, err)
129
+ return False
130
+ _LOGGER.debug("Removed the BlueZ bond for %s", path)
131
+ return True
132
+
133
+
134
+ def _agent_path(device_path: str) -> str:
135
+ """Return the agent's object path for one device: ``/org/ble_bond/agent/dev_AA_…``."""
136
+ return f"{AGENT_PATH}/{device_path.rsplit('/', 1)[-1]}"
137
+
138
+
139
+ @contextlib.asynccontextmanager
140
+ async def bluez_pairing_agent(device: "BLEDevice", *, enabled: bool = True) -> AsyncGenerator[None]:
141
+ """Hold a Just Works agent while ``device`` is connected and paired through BlueZ.
142
+
143
+ Does nothing when ``enabled`` is False (no new bond is expected, so pairing must not be
144
+ accepted), when the device was not seen by a local BlueZ adapter (an ESPHome proxy, or
145
+ another platform), when BlueZ already holds a bond, or when the agent cannot be
146
+ registered; pairing then goes ahead as it would have without one. While registered, the
147
+ agent is the system's default and refuses every other device, so only one is held at a
148
+ time.
149
+ """
150
+ path = bluez_device_path(device) if enabled else None
151
+ bluez = None if path is None else await _bluez_bus()
152
+ if path is None or bluez is None or bluez[0].is_paired(path):
153
+ yield
154
+ return
155
+ async with _agent_lock(), _registered_agent(bluez[1], path):
156
+ yield
157
+
158
+
159
+ @contextlib.asynccontextmanager
160
+ async def _registered_agent(bus: "MessageBus", path: str) -> AsyncGenerator[None]:
161
+ agent_path = _agent_path(path)
162
+ from dbus_fast.annotations import DBusObjectPath, DBusStr, DBusUInt32
163
+ from dbus_fast.errors import DBusError
164
+ from dbus_fast.service import ServiceInterface, method
165
+
166
+ def check(requested: str) -> None:
167
+ if requested != path:
168
+ raise DBusError("org.bluez.Error.Rejected", "not the device being paired")
169
+
170
+ class Agent(ServiceInterface):
171
+ """Accept Just Works pairing for the one device being paired."""
172
+
173
+ def __init__(self) -> None:
174
+ super().__init__("org.bluez.Agent1")
175
+
176
+ @method()
177
+ def Release(self) -> None: # noqa: N802 - D-Bus method name
178
+ """Unregistered by BlueZ."""
179
+
180
+ @method()
181
+ def Cancel(self) -> None: # noqa: N802
182
+ """Drop a cancelled request."""
183
+
184
+ @method()
185
+ def RequestConfirmation(self, device: DBusObjectPath, passkey: DBusUInt32) -> None: # noqa: N802, ARG002
186
+ """Confirm Just Works pairing."""
187
+ check(device)
188
+
189
+ @method()
190
+ def RequestAuthorization(self, device: DBusObjectPath) -> None: # noqa: N802
191
+ """Authorize pairing the remote side started."""
192
+ check(device)
193
+
194
+ @method()
195
+ def AuthorizeService(self, device: DBusObjectPath, uuid: DBusStr) -> None: # noqa: N802, ARG002
196
+ """Authorize a service on the paired device."""
197
+ check(device)
198
+
199
+ async def call(member: str, signature: str, body: list[object]) -> None:
200
+ await _call(bus, "/org/bluez", AGENT_MANAGER_INTERFACE, member, signature, body)
201
+
202
+ exported = registered = False
203
+ try:
204
+ bus.export(agent_path, Agent())
205
+ exported = True
206
+ await call("RegisterAgent", "os", [agent_path, "NoInputNoOutput"])
207
+ registered = True
208
+ await call("RequestDefaultAgent", "o", [agent_path])
209
+ except Exception as err: # try the pairing anyway
210
+ _LOGGER.debug("Could not register the BlueZ pairing agent: %s", err)
211
+ else:
212
+ _LOGGER.debug("BlueZ pairing agent registered for %s", path)
213
+ try:
214
+ yield
215
+ finally:
216
+ if registered:
217
+ with contextlib.suppress(Exception):
218
+ await call("UnregisterAgent", "o", [agent_path])
219
+ if exported:
220
+ bus.unexport(agent_path)
ble_bond/exceptions.py ADDED
@@ -0,0 +1,59 @@
1
+ """Exceptions raised by ble-bond.
2
+
3
+ Device libraries usually translate these into their own exceptions, so that their callers see
4
+ one hierarchy; each keeps ``error_code`` and the original as ``__cause__``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+
10
+ class LinkError(Exception):
11
+ """Connecting to or talking to the device failed at the Bluetooth level.
12
+
13
+ ``error_code`` holds the adapter's numeric reason when it reported one.
14
+ """
15
+
16
+ def __init__(self, message: str, error_code: int | None = None) -> None:
17
+ super().__init__(message)
18
+ self.error_code = error_code
19
+
20
+
21
+ class PairingRequired(LinkError):
22
+ """The link could not be encrypted: the device wants a bond the adapter does not hold.
23
+
24
+ Two cases of very different strength:
25
+
26
+ * ``refused`` is True: the device turned pairing down outright (ESP-IDF SMP reason 82
27
+ through an ESPHome proxy, BlueZ ``AuthenticationFailed`` on a local adapter). The adapter
28
+ holds no bond the device accepts, and the device is not in its pairing window.
29
+ * ``refused`` is False: the link came up but stayed unencrypted ("insufficient
30
+ authentication"), and the policy counts that as weak evidence. It can be a lost bond, but
31
+ also a proxy whose bond store is stuck, or an attempt through an adapter that never held
32
+ the bond. On its own it is no reason to pair again.
33
+
34
+ Only an attempt through the adapter that holds the bond says anything about the bond; see
35
+ :attr:`~ble_bond.link.BondedLink.last_source`.
36
+ """
37
+
38
+ def __init__(
39
+ self, message: str, error_code: int | None = None, *, refused: bool = True
40
+ ) -> None:
41
+ super().__init__(message, error_code)
42
+ self.refused = refused
43
+
44
+
45
+ class PairingUnsupported(LinkError):
46
+ """The Bluetooth path cannot pair at all.
47
+
48
+ Raised when an ESPHome proxy's firmware has no pairing support (bleak-esphome's "Pairing is
49
+ not available in this version ESPHome", or reason 129), unless the policy allows one more
50
+ try without pairing. Pressing the device's button cannot help.
51
+ """
52
+
53
+
54
+ class ConnectionLost(LinkError):
55
+ """The link was not up, or dropped while a request was in flight."""
56
+
57
+
58
+ class RequestTimeout(LinkError, TimeoutError):
59
+ """No accepted reply arrived within the request timeout."""
ble_bond/link.py ADDED
@@ -0,0 +1,624 @@
1
+ """A bonded Bluetooth LE link to a device that answers one request at a time.
2
+
3
+ The link takes a ``BLEDevice`` from the caller and never scans. On every connection it pairs
4
+ (on an ESPHome proxy this is "start encryption": a re-encrypt when the proxy already holds a
5
+ bond, SMP pairing otherwise), subscribes to the reply characteristic, lets the link settle, and
6
+ then runs one request at a time: write the frame, wait for a reply the caller accepts.
7
+
8
+ Pairing on every connection is what makes the same code work on a local adapter and on an
9
+ ESPHome proxy. A local BlueZ adapter applies a stored bond by itself; a proxy does not, and
10
+ only an explicit pair call re-arms encryption from its stored key. Devices of this kind accept a
11
+ new bond only for a few seconds after a button press; outside that window ESP-IDF reports
12
+ reason 82 and BlueZ ``AuthenticationFailed``, both of which become
13
+ :class:`~ble_bond.exceptions.PairingRequired`.
14
+
15
+ Replies carry no request id, so three rules follow:
16
+
17
+ * one request is in flight at a time;
18
+ * a frame the caller's ``accept`` check does not recognise is logged as unsolicited and the
19
+ wait goes on, so a stray frame cannot shift every later reply by one;
20
+ * a request that does not complete (timeout, cancellation, write error, lost link) closes the
21
+ link, so its late reply cannot be taken for the next request's answer.
22
+
23
+ What differs between devices (pauses, retries, how weak evidence about the bond is reported,
24
+ write size) is a :class:`LinkPolicy`; framing is the caller's :class:`Assembler`.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import asyncio
30
+ import contextlib
31
+ import functools
32
+ import logging
33
+ import re
34
+ from collections import deque
35
+ from collections.abc import Callable
36
+ from contextvars import ContextVar
37
+ from dataclasses import dataclass
38
+ from enum import StrEnum
39
+ from typing import TYPE_CHECKING, Any, Final, Protocol, Self
40
+
41
+ import bleak_retry_connector
42
+ from bleak import BleakClient
43
+ from bleak.exc import BleakCharacteristicNotFoundError, BleakError
44
+ from bleak_retry_connector import establish_connection
45
+
46
+ from ble_bond.bluez import bluez_device_path, bluez_pairing_agent
47
+ from ble_bond.exceptions import (
48
+ ConnectionLost,
49
+ LinkError,
50
+ PairingRequired,
51
+ PairingUnsupported,
52
+ RequestTimeout,
53
+ )
54
+
55
+ if TYPE_CHECKING:
56
+ from types import TracebackType
57
+
58
+ from bleak.backends.characteristic import BleakGATTCharacteristic
59
+ from bleak.backends.device import BLEDevice
60
+
61
+ _LOGGER = logging.getLogger(__name__)
62
+
63
+ type Accept = Callable[[bytes], bool]
64
+ """Says whether a complete frame is the reply the pending request waits for."""
65
+
66
+ DEFAULT_WRITE_CHUNK: Final = 20
67
+ """Bytes one write carries when the negotiated MTU is not used or not known (ATT 23, less 3)."""
68
+ ATT_OVERHEAD: Final = 3
69
+ MAX_PIECES_REPORTED: Final = 8
70
+ """Notification pieces of an unfinished reply quoted in a RequestTimeout."""
71
+ MAX_PIECES_KEPT: Final = 64
72
+ """Notification pieces kept for that report; older ones are dropped."""
73
+ RETRY_DELAY: Final = 0.25
74
+ """Seconds between connection attempts."""
75
+
76
+ PAIRING_REFUSED_CODES: Final = frozenset({82})
77
+ """ESP-IDF SMP reasons that mean "no bond and the pairing window is closed".
78
+
79
+ Others seen in the same message (timeouts, busy, internal errors) are transient."""
80
+ PAIRING_UNSUPPORTED_CODES: Final = frozenset({129})
81
+ """Reasons from proxies that cannot pair at all."""
82
+ INSUFFICIENT_AUTHENTICATION_CODE: Final = 5
83
+ """The ATT error behind a subscription refused for want of encryption."""
84
+
85
+ _PAIRING_FAILED = re.compile(r"Pairing failed due to error: (-?\d+)")
86
+ """bleak-esphome's report of a failed pairing; it survives bleak-retry-connector's wrapping."""
87
+ _PAIRING_UNAVAILABLE: Final = "Pairing is not available"
88
+ """bleak-esphome's NotImplementedError when the proxy's ESPHome has no pairing support."""
89
+ _INSUFFICIENT_AUTHENTICATION = re.compile(r"insufficient (authentication|encryption)", re.I)
90
+ BLUEZ_AUTHENTICATION_FAILED: Final = "org.bluez.Error.AuthenticationFailed"
91
+ """BlueZ's report of a refused pairing; with the pairing agent up it means a missed window."""
92
+ _LINK_ERRORS: Final = (BleakError, EOFError, BrokenPipeError, AttributeError, NotImplementedError)
93
+ """What bleak backends raise for link trouble; bleak-retry-connector retries most of these.
94
+
95
+ The ``except`` clauses that use it wrap only bleak calls, so an ``AttributeError`` here comes
96
+ from a backend whose link went away under it, and a ``NotImplementedError`` from a proxy that
97
+ cannot pair (or CoreBluetooth, which pairs by itself).
98
+ """
99
+
100
+
101
+ class SubscribeRetry(StrEnum):
102
+ """When a failed subscription is tried once more on the same link."""
103
+
104
+ ANY_LINK_ERROR = "any_link_error"
105
+ """After any link error (encryption may still be settling)."""
106
+ INSUFFICIENT_AUTHENTICATION = "insufficient_authentication"
107
+ """Only after "insufficient authentication": the link is up but not yet encrypted."""
108
+ NEVER = "never"
109
+
110
+
111
+ @dataclass(frozen=True, slots=True, kw_only=True)
112
+ class LinkPolicy:
113
+ """How one kind of device wants its link handled. The defaults suit most devices.
114
+
115
+ Each value is a measurement or a choice made for a device, so a device library states them
116
+ in one place, with where they come from.
117
+ """
118
+
119
+ settle_after_pair: float = 0.0
120
+ """Seconds between the encrypted connect and subscribing.
121
+
122
+ A pair call can return before link-layer encryption is up; a subscription landing in that
123
+ gap is refused as "insufficient authentication"."""
124
+ settle_after_subscribe: float = 0.5
125
+ """Seconds between subscribing and the first write.
126
+
127
+ ESPHome measured on a Grundfos ALPHA3 that requests sent 0-200 ms after notifications were
128
+ enabled were lost in 4-5 of 10 connections, and none at 300-500 ms (esphome/esphome#22651)."""
129
+ subscribe_retry: SubscribeRetry = SubscribeRetry.ANY_LINK_ERROR
130
+ subscribe_retry_delay: float = 0.5
131
+ insufficient_authentication_is_evidence: bool = False
132
+ """Report a subscription refused twice for want of encryption as
133
+ ``PairingRequired(refused=False)`` (weak evidence about the bond) rather than a plain
134
+ :class:`~ble_bond.exceptions.LinkError`."""
135
+ retry_unpaired: bool = False
136
+ """When the adapter or proxy cannot pair at all, connect once more without pairing: a bond
137
+ it already holds may still encrypt the link. Otherwise raise
138
+ :class:`~ble_bond.exceptions.PairingUnsupported`. Only for devices that answer on an
139
+ unencrypted link or encrypt by themselves."""
140
+ write_chunk: int | None = DEFAULT_WRITE_CHUNK
141
+ """Bytes per write; None writes as much as the negotiated MTU allows (at least 20)."""
142
+ chunk_spacing: float = 0.025
143
+ """Seconds between the writes of one frame."""
144
+ connection_params: tuple[int, int, int, int] | None = None
145
+ """(min interval, max interval, latency, supervision timeout) in BLE units, requested
146
+ best-effort where the backend can (Home Assistant's client can, through a proxy)."""
147
+ connect_timeout: float = 10.0
148
+ """Seconds allowed for one connect-and-pair attempt."""
149
+ request_timeout: float = 10.0
150
+ """Seconds to wait for a whole reply, write included.
151
+
152
+ Kept above the 8 s link supervision timeout Home Assistant and ESPHome proxies use, so a
153
+ link that stalls and recovers answers late rather than being torn down."""
154
+
155
+
156
+ class Assembler(Protocol):
157
+ """Puts notification pieces together into whole frames (the device library's framing)."""
158
+
159
+ def feed(self, data: bytes | bytearray) -> list[bytes]:
160
+ """Add one notification and return every frame it completed."""
161
+ ...
162
+
163
+ def reset(self) -> None:
164
+ """Forget any partial frame."""
165
+ ...
166
+
167
+
168
+ # --- Which adapter or proxy an attempt used ---------------------------------------------------
169
+
170
+ _attempt_source: ContextVar[list[str | None] | None] = ContextVar(
171
+ "ble_bond_attempt_source", default=None
172
+ )
173
+ """Where the client class below records the Bluetooth source of the current attempt."""
174
+
175
+
176
+ @functools.cache
177
+ def _source_recording(base: Any) -> Any: # noqa: ANN401 - a class only known at run time
178
+ """Wrap Home Assistant's client class so that it records the scanner it connects through.
179
+
180
+ Home Assistant (habluetooth) replaces bleak's client with one that picks a local adapter or
181
+ a proxy at connect time, by signal and free slots, and keeps the choice private until the
182
+ connection succeeds. A refused attempt must be pinned on the path that was asked, so this
183
+ subclass reads the choice from that private method as it is made. With plain bleak the
184
+ method does not exist and ``base`` is returned unchanged.
185
+ """
186
+ if not hasattr(base, "_async_get_best_available_backend_and_device"):
187
+ return base
188
+
189
+ class SourceRecordingClient(base): # type: ignore[misc]
190
+ def _async_get_best_available_backend_and_device(self, manager: Any) -> Any: # noqa: ANN401
191
+ backend = super()._async_get_best_available_backend_and_device(manager)
192
+ if (slot := _attempt_source.get()) is not None:
193
+ with contextlib.suppress(Exception):
194
+ slot[0] = backend.scanner.source
195
+ return backend
196
+
197
+ return SourceRecordingClient
198
+
199
+
200
+ def _details_source(device: BLEDevice) -> str | None:
201
+ details = device.details
202
+ if isinstance(details, dict) and isinstance(source := details.get("source"), str):
203
+ return source
204
+ return None
205
+
206
+
207
+ # --- The link -----------------------------------------------------------------------------------
208
+
209
+
210
+ class BondedLink:
211
+ """One bonded BLE link to a device that answers one request at a time.
212
+
213
+ ``notify_uuid`` is the characteristic replies arrive on; ``write_uuid`` the one requests are
214
+ written to (the same one by default). ``assembler`` turns notification pieces into frames.
215
+
216
+ ``device_callback``, when given, is asked for the device again before every connection
217
+ attempt, so a retry goes through whichever adapter or proxy now hears the device best. It
218
+ may return None to keep the last device.
219
+
220
+ ``expect_new_bond`` says a new bond may be made on this link (the device's button was just
221
+ pressed). Only then is a BlueZ pairing agent registered on a local adapter; without it an
222
+ unbonded local adapter's pairing is refused, which is what a missed window looks like.
223
+
224
+ ``disconnected_callback`` is called when the device or the adapter drops the live link, not
225
+ when the link is closed on purpose.
226
+
227
+ ``async with BondedLink(...) as link:`` connects on entry and disconnects on exit.
228
+ """
229
+
230
+ def __init__(
231
+ self,
232
+ device: BLEDevice,
233
+ *,
234
+ notify_uuid: str,
235
+ assembler: Assembler,
236
+ write_uuid: str | None = None,
237
+ policy: LinkPolicy | None = None,
238
+ name: str | None = None,
239
+ max_attempts: int = 2,
240
+ connect_timeout: float | None = None,
241
+ request_timeout: float | None = None,
242
+ disconnected_callback: Callable[[], None] | None = None,
243
+ device_callback: Callable[[], BLEDevice | None] | None = None,
244
+ expect_new_bond: bool = False,
245
+ ) -> None:
246
+ self._device = device
247
+ self._notify_uuid = notify_uuid
248
+ self._write_uuid = write_uuid or notify_uuid
249
+ self._assembler = assembler
250
+ self._policy = policy or LinkPolicy()
251
+ self._name = name or device.name or device.address
252
+ self._max_attempts = max(1, max_attempts)
253
+ self._connect_timeout = (
254
+ self._policy.connect_timeout if connect_timeout is None else connect_timeout
255
+ )
256
+ self._request_timeout = (
257
+ self._policy.request_timeout if request_timeout is None else request_timeout
258
+ )
259
+ self._disconnected_callback = disconnected_callback
260
+ self._device_callback = device_callback
261
+ self._expect_new_bond = expect_new_bond
262
+ self._client: BleakClient | None = None
263
+ self._lock = asyncio.Lock()
264
+ self._connect_lock = asyncio.Lock()
265
+ self._pending: asyncio.Future[bytes] | None = None
266
+ self._accept: Accept | None = None
267
+ self._pieces: deque[bytes] = deque(maxlen=MAX_PIECES_KEPT)
268
+ self._unmatched = 0
269
+ self._reply_seen = False
270
+ self._last_source: str | None = None
271
+ self.unsolicited = 0
272
+ """Frames received that no request was waiting for, or that no check accepted."""
273
+ self.last_frames: deque[tuple[str, bytes]] = deque(maxlen=48)
274
+ """Recent traffic as ("tx" | "rx", frame), for diagnostics and fixture capture."""
275
+
276
+ async def __aenter__(self) -> Self:
277
+ """Connect, as :meth:`connect` does, and return the link."""
278
+ await self.connect()
279
+ return self
280
+
281
+ async def __aexit__(
282
+ self,
283
+ exc_type: type[BaseException] | None,
284
+ exc: BaseException | None,
285
+ traceback: TracebackType | None,
286
+ ) -> None:
287
+ """Disconnect, whatever happened in the block."""
288
+ await self.disconnect()
289
+
290
+ @property
291
+ def device(self) -> BLEDevice:
292
+ """The device this link talks to (the latest one ``device_callback`` gave)."""
293
+ return self._device
294
+
295
+ @property
296
+ def policy(self) -> LinkPolicy:
297
+ """How this link is handled."""
298
+ return self._policy
299
+
300
+ @property
301
+ def is_connected(self) -> bool:
302
+ """True while the BLE link is up."""
303
+ return self._client is not None and self._client.is_connected
304
+
305
+ @property
306
+ def reply_seen(self) -> bool:
307
+ """True once the device has sent a frame on the current or last link."""
308
+ return self._reply_seen
309
+
310
+ @property
311
+ def last_source(self) -> str | None:
312
+ """The Bluetooth source (adapter or proxy) the latest connection attempt went through.
313
+
314
+ Under Home Assistant this is the scanner habluetooth chose for the attempt, refused
315
+ attempts included, read from a private method; elsewhere, or if that changes, it is the
316
+ source the device was last heard through when the attempt started. None when neither
317
+ is known. A refusal says something about the bond only when it came through the
318
+ adapter or proxy that holds it.
319
+ """
320
+ return self._last_source
321
+
322
+ # -- connecting --------------------------------------------------------------------------
323
+
324
+ async def connect(self) -> None:
325
+ """Connect through the device's path, pair (encrypt), subscribe and let the link settle.
326
+
327
+ Retries run here, one connection attempt at a time, so that a refusal on any attempt is
328
+ seen; bleak-retry-connector reports only the last attempt's error. Concurrent calls
329
+ share one connection.
330
+ """
331
+ async with self._connect_lock:
332
+ if self.is_connected:
333
+ return
334
+ self._assembler.reset()
335
+ self._pieces.clear()
336
+ self._reply_seen = False
337
+ client = await self._connect_with_retries()
338
+ self._client = client
339
+ try:
340
+ await self._set_connection_params(client)
341
+ if self._policy.settle_after_pair:
342
+ await asyncio.sleep(self._policy.settle_after_pair)
343
+ await self._subscribe(client)
344
+ except BaseException:
345
+ await self.disconnect()
346
+ raise
347
+ _LOGGER.debug("%s: connected and subscribed", self._name)
348
+ if self._policy.settle_after_subscribe:
349
+ await asyncio.sleep(self._policy.settle_after_subscribe)
350
+
351
+ async def _connect_with_retries(self) -> BleakClient:
352
+ last: LinkError | None = None
353
+ for attempt in range(self._max_attempts):
354
+ if attempt:
355
+ await asyncio.sleep(RETRY_DELAY)
356
+ if self._device_callback is not None:
357
+ self._device = self._device_callback() or self._device
358
+ slot: list[str | None] = [None]
359
+ token = _attempt_source.set(slot)
360
+ try:
361
+ async with (
362
+ asyncio.timeout(self._connect_timeout),
363
+ bluez_pairing_agent(self._device, enabled=self._expect_new_bond),
364
+ ):
365
+ return await self._establish_pairing()
366
+ except _LINK_ERRORS as err:
367
+ last = self._translate(err)
368
+ last.__cause__ = err
369
+ if isinstance(last, (PairingRequired, PairingUnsupported)):
370
+ raise last from err
371
+ except TimeoutError as err:
372
+ last = LinkError(f"timed out connecting to {self._name}")
373
+ last.__cause__ = err
374
+ finally:
375
+ _attempt_source.reset(token)
376
+ self._last_source = slot[0] or _details_source(self._device)
377
+ assert last is not None
378
+ raise last
379
+
380
+ async def _establish_pairing(self) -> BleakClient:
381
+ """Connect and pair; with ``retry_unpaired``, retry once unpaired if pairing is absent."""
382
+ try:
383
+ return await self._establish(pair=True)
384
+ except _LINK_ERRORS as err:
385
+ if not self._policy.retry_unpaired or not self._pairing_unsupported(err):
386
+ raise
387
+ _LOGGER.debug("%s: the adapter cannot pair (%s); trying unpaired", self._name, err)
388
+ return await self._establish(pair=False)
389
+
390
+ async def _establish(self, *, pair: bool) -> BleakClient:
391
+ return await establish_connection(
392
+ # Looked up at call time: Home Assistant swaps the class in after import.
393
+ _source_recording(bleak_retry_connector.BleakClientWithServiceCache),
394
+ self._device,
395
+ self._name,
396
+ disconnected_callback=self._on_disconnect,
397
+ max_attempts=1,
398
+ pair=pair,
399
+ # With bleak's own cache a local connect returns before bluetoothd has finished
400
+ # setting up GATT; without it bleak waits for ServicesResolved, which BlueZ's cache
401
+ # for a bonded device keeps quick. A proxy keeps its cache: it reports the link only
402
+ # once encrypted and set up.
403
+ use_services_cache=bluez_device_path(self._device) is None,
404
+ )
405
+
406
+ async def _set_connection_params(self, client: BleakClient) -> None:
407
+ """Ask for the policy's connection parameters where the backend can; never fail on it."""
408
+ params = self._policy.connection_params
409
+ setter = getattr(client, "set_connection_params", None)
410
+ if params is None or setter is None:
411
+ return
412
+ try:
413
+ await setter(*params)
414
+ except Exception as err: # best effort: every backend differs
415
+ _LOGGER.debug("%s: connection parameters not set: %s", self._name, err)
416
+
417
+ async def _subscribe(self, client: BleakClient) -> None:
418
+ """Subscribe to replies, retrying once on the same link as the policy says."""
419
+ policy = self._policy
420
+ for final_try in (False, True):
421
+ try:
422
+ await client.start_notify(self._notify_uuid, self._on_notify)
423
+ except BleakCharacteristicNotFoundError as err:
424
+ # The service cache is stale (yalexs-ble finds the same), or this device does
425
+ # not offer the characteristic: drop the cache so the next connection resolves
426
+ # the services afresh.
427
+ if hasattr(client, "clear_cache"):
428
+ with contextlib.suppress(Exception):
429
+ await client.clear_cache()
430
+ raise LinkError(
431
+ f"{self._name}: characteristic {self._notify_uuid} not found; the device "
432
+ f"does not offer it, or a cached service list is stale ({err})"
433
+ ) from err
434
+ except (*_LINK_ERRORS, TimeoutError) as err:
435
+ unencrypted = bool(_INSUFFICIENT_AUTHENTICATION.search(str(err)))
436
+ retry = policy.subscribe_retry is SubscribeRetry.ANY_LINK_ERROR or (
437
+ policy.subscribe_retry is SubscribeRetry.INSUFFICIENT_AUTHENTICATION
438
+ and unencrypted
439
+ )
440
+ if final_try or not retry or not client.is_connected:
441
+ raise self._subscribe_error(err, unencrypted=unencrypted) from err
442
+ _LOGGER.debug("%s: subscribing failed (%s); retrying once", self._name, err)
443
+ await asyncio.sleep(policy.subscribe_retry_delay)
444
+ else:
445
+ return
446
+
447
+ def _subscribe_error(self, err: BaseException, *, unencrypted: bool) -> LinkError:
448
+ """Translate a failed subscription: weak pairing evidence only if the policy says so."""
449
+ if unencrypted and self._policy.insufficient_authentication_is_evidence:
450
+ # The link came up but was not encrypted, twice. Weak evidence about the bond.
451
+ return PairingRequired(
452
+ f"{self._name}: {err}", INSUFFICIENT_AUTHENTICATION_CODE, refused=False
453
+ )
454
+ return self._link_error(err)
455
+
456
+ async def disconnect(self) -> None:
457
+ """Unsubscribe and drop the link; safe to call when not connected."""
458
+ client, self._client = self._client, None
459
+ if client is None:
460
+ return
461
+ if client.is_connected:
462
+ # Leaving notifications running can let a native callback fire into a torn-down
463
+ # client (seen crashing a process on exit).
464
+ with contextlib.suppress(Exception):
465
+ async with asyncio.timeout(1.0):
466
+ await client.stop_notify(self._notify_uuid)
467
+ with contextlib.suppress(Exception):
468
+ await client.disconnect()
469
+
470
+ # -- requests ----------------------------------------------------------------------------
471
+
472
+ async def request(
473
+ self, frame: bytes, *, accept: Accept | None = None, timeout: float | None = None
474
+ ) -> bytes:
475
+ """Write ``frame`` and return the device's reply as a whole frame, one at a time.
476
+
477
+ ``accept`` says whether a complete frame is this request's reply; one that is not is
478
+ logged as unsolicited and the wait goes on within the same deadline. Without it the
479
+ first frame answers. A request that does not complete with a reply, whether it timed
480
+ out, was cancelled or failed to write, closes the link.
481
+ """
482
+ async with self._lock:
483
+ client = self._require_client()
484
+ loop = asyncio.get_running_loop()
485
+ future: asyncio.Future[bytes] = loop.create_future()
486
+ self._assembler.reset()
487
+ self._pieces.clear()
488
+ self._unmatched = 0
489
+ self._pending, self._accept = future, accept
490
+ replied = False
491
+ try:
492
+ async with asyncio.timeout(self._request_timeout if timeout is None else timeout):
493
+ await self._write(client, frame)
494
+ reply = await future
495
+ replied = True
496
+ except TimeoutError as err:
497
+ raise RequestTimeout(
498
+ f"{self._name}: no reply to {frame.hex(' ')}; {self._received()}"
499
+ ) from err
500
+ finally:
501
+ self._pending = self._accept = None
502
+ if future.done() and not future.cancelled():
503
+ future.exception() # mark as retrieved
504
+ else:
505
+ future.cancel()
506
+ if not replied:
507
+ await self.disconnect()
508
+ return reply
509
+
510
+ async def send(self, frame: bytes) -> None:
511
+ """Write ``frame`` without waiting for a reply; a failed write closes the link."""
512
+ async with self._lock:
513
+ client = self._require_client()
514
+ try:
515
+ await self._write(client, frame)
516
+ except BaseException:
517
+ await self.disconnect()
518
+ raise
519
+
520
+ def _require_client(self) -> BleakClient:
521
+ if self._client is None or not self._client.is_connected:
522
+ raise ConnectionLost(f"{self._name}: not connected")
523
+ return self._client
524
+
525
+ async def _write(self, client: BleakClient, frame: bytes) -> None:
526
+ self.last_frames.append(("tx", frame))
527
+ _LOGGER.debug("%s: tx %s", self._name, frame.hex(" "))
528
+ size = self._write_size(client)
529
+ for start in range(0, len(frame), size):
530
+ if start:
531
+ await asyncio.sleep(self._policy.chunk_spacing)
532
+ try:
533
+ await client.write_gatt_char(
534
+ self._write_uuid, frame[start : start + size], response=False
535
+ )
536
+ except _LINK_ERRORS as err:
537
+ raise self._link_error(err) from err
538
+
539
+ def _write_size(self, client: BleakClient) -> int:
540
+ if self._policy.write_chunk is not None:
541
+ return self._policy.write_chunk
542
+ try:
543
+ mtu = int(client.mtu_size)
544
+ except Exception: # some backends only know the MTU after an exchange
545
+ return DEFAULT_WRITE_CHUNK
546
+ return max(DEFAULT_WRITE_CHUNK, mtu - ATT_OVERHEAD)
547
+
548
+ def _received(self) -> str:
549
+ """Describe what came for a request that got no accepted reply."""
550
+ unmatched = (
551
+ f"; {self._unmatched} frame(s) did not answer the request" if self._unmatched else ""
552
+ )
553
+ if not self._pieces:
554
+ return "nothing received" + unmatched
555
+ pieces = list(self._pieces)
556
+ quoted = " | ".join(piece.hex(" ") for piece in pieces[:MAX_PIECES_REPORTED])
557
+ more = " | ..." if len(pieces) > MAX_PIECES_REPORTED else ""
558
+ return f"{len(pieces)} piece(s) received: {quoted}{more}{unmatched}"
559
+
560
+ def _on_notify(self, _characteristic: BleakGATTCharacteristic, data: bytearray) -> None:
561
+ self._pieces.append(bytes(data))
562
+ for frame in self._assembler.feed(data):
563
+ self.last_frames.append(("rx", frame))
564
+ self._reply_seen = True
565
+ _LOGGER.debug("%s: rx %s", self._name, frame.hex(" "))
566
+ pending = self._pending
567
+ if pending is None or pending.done():
568
+ self.unsolicited += 1
569
+ _LOGGER.debug("%s: unsolicited frame %s", self._name, frame.hex(" "))
570
+ elif self._accept is not None and not self._accepts(frame):
571
+ self._unmatched += 1
572
+ self.unsolicited += 1
573
+ _LOGGER.debug(
574
+ "%s: frame did not answer the request: %s", self._name, frame.hex(" ")
575
+ )
576
+ else:
577
+ pending.set_result(frame)
578
+
579
+ def _accepts(self, frame: bytes) -> bool:
580
+ assert self._accept is not None
581
+ try:
582
+ return self._accept(frame)
583
+ except Exception: # a check that cannot read the frame does not accept it
584
+ _LOGGER.debug("%s: the reply check failed on %s", self._name, frame.hex(" "))
585
+ return False
586
+
587
+ def _on_disconnect(self, client: BleakClient) -> None:
588
+ if self._client is None or client is not self._client:
589
+ return # our own disconnect, a failed attempt, or a late callback from an old link
590
+ self._client = None
591
+ pending = self._pending
592
+ if pending is not None and not pending.done():
593
+ pending.set_exception(ConnectionLost(f"{self._name}: disconnected"))
594
+ if self._disconnected_callback is not None:
595
+ self._disconnected_callback()
596
+
597
+ # -- classifying failures ----------------------------------------------------------------
598
+
599
+ @staticmethod
600
+ def _pairing_unsupported(err: BaseException) -> bool:
601
+ if isinstance(err, NotImplementedError) or _PAIRING_UNAVAILABLE in str(err):
602
+ return True
603
+ match = _PAIRING_FAILED.search(str(err))
604
+ return match is not None and int(match.group(1)) in PAIRING_UNSUPPORTED_CODES
605
+
606
+ def _link_error(self, err: BaseException) -> LinkError:
607
+ """Translate an error on an established link: never evidence about pairing."""
608
+ return LinkError(f"{self._name}: {type(err).__name__}: {err}")
609
+
610
+ def _translate(self, err: BaseException) -> LinkError:
611
+ """Translate a failed connection attempt, telling refusals from other failures."""
612
+ text = str(err)
613
+ if match := _PAIRING_FAILED.search(text):
614
+ code = int(match.group(1))
615
+ if code in PAIRING_REFUSED_CODES:
616
+ return PairingRequired(f"{self._name}: {text}", code)
617
+ if code in PAIRING_UNSUPPORTED_CODES:
618
+ return PairingUnsupported(f"{self._name}: {text}", code)
619
+ return LinkError(f"{self._name}: {text}", code)
620
+ if BLUEZ_AUTHENTICATION_FAILED in text:
621
+ return PairingRequired(f"{self._name}: {text}")
622
+ if self._pairing_unsupported(err):
623
+ return PairingUnsupported(f"{self._name}: {text}")
624
+ return LinkError(f"{self._name}: {type(err).__name__}: {text}")
ble_bond/py.typed ADDED
File without changes
ble_bond/testing.py ADDED
@@ -0,0 +1,91 @@
1
+ """Test helpers: a fake bleak client and a patch that hands it to :class:`BondedLink`.
2
+
3
+ ``FakeClient`` answers a written frame from a table of replies, delivered as 20-byte
4
+ notifications, or stays silent. ``patched_establish`` replaces the connection call, so a test
5
+ needs neither an adapter nor a device::
6
+
7
+ client = FakeClient({request: reply})
8
+ with patched_establish(client) as calls:
9
+ async with BondedLink(device, notify_uuid=UUID, assembler=...) as link:
10
+ assert await link.request(request) == reply
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ from collections.abc import Callable, Iterator
17
+ from typing import Any
18
+ from unittest.mock import patch
19
+
20
+ from ble_bond import link as link_module
21
+
22
+ NOTIFICATION_SIZE = 20
23
+
24
+
25
+ class FakeClient:
26
+ """Enough of ``BleakClient`` for the link: notifications, writes, drops and disconnects."""
27
+
28
+ def __init__(self, replies: dict[bytes, bytes] | None = None, *, mtu_size: int = 23) -> None:
29
+ self.replies = replies or {}
30
+ self.writes: list[bytes] = []
31
+ self.is_connected = True
32
+ self.mtu_size = mtu_size
33
+ self.notify_cb: Callable[[Any, bytearray], None] | None = None
34
+ self.disconnected_callback: Callable[[Any], None] | None = None
35
+ self.auto_reply = True
36
+ self.unsubscribed = False
37
+ self.connection_params: tuple[int, ...] | None = None
38
+
39
+ async def start_notify(self, _char: str, callback: Callable[[Any, bytearray], None]) -> None:
40
+ """Remember the notification callback."""
41
+ self.notify_cb = callback
42
+
43
+ async def stop_notify(self, _char: str) -> None:
44
+ """Note the unsubscription."""
45
+ self.unsubscribed = True
46
+
47
+ async def write_gatt_char(self, _char: str, data: bytes, response: bool | None = None) -> None:
48
+ """Record a write; answer once the written pieces make up a known request."""
49
+ del response
50
+ self.writes.append(bytes(data))
51
+ if not self.auto_reply:
52
+ return
53
+ frame = b"".join(self.writes)
54
+ if frame in self.replies:
55
+ self.writes.clear()
56
+ self.notify(self.replies[frame])
57
+
58
+ def notify(self, data: bytes) -> None:
59
+ """Deliver ``data`` as notifications of at most 20 bytes."""
60
+ assert self.notify_cb is not None, "not subscribed"
61
+ for start in range(0, len(data), NOTIFICATION_SIZE):
62
+ self.notify_cb(None, bytearray(data[start : start + NOTIFICATION_SIZE]))
63
+
64
+ async def set_connection_params(self, *params: int) -> None:
65
+ """Record the requested connection parameters."""
66
+ self.connection_params = params
67
+
68
+ async def disconnect(self) -> None:
69
+ """Close the link."""
70
+ self.is_connected = False
71
+
72
+ def drop(self) -> None:
73
+ """Lose the link from the device's side."""
74
+ self.is_connected = False
75
+ assert self.disconnected_callback is not None
76
+ self.disconnected_callback(self)
77
+
78
+
79
+ @contextlib.contextmanager
80
+ def patched_establish(client: Any) -> Iterator[list[dict[str, Any]]]: # noqa: ANN401
81
+ """Make every connection attempt return ``client``; yield the attempts' keyword arguments."""
82
+ calls: list[dict[str, Any]] = []
83
+
84
+ async def establish(_cls: Any, _device: Any, _name: str, **kwargs: Any) -> Any: # noqa: ANN401
85
+ calls.append(kwargs)
86
+ if hasattr(client, "disconnected_callback"):
87
+ client.disconnected_callback = kwargs["disconnected_callback"]
88
+ return client
89
+
90
+ with patch.object(link_module, "establish_connection", establish):
91
+ yield calls
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.5
2
+ Name: ble-bond
3
+ Version: 1.0.0
4
+ Summary: Bonded Bluetooth LE sessions for devices that pair in a button window and answer one request at a time
5
+ Project-URL: Homepage, https://github.com/83noit/ble-bond
6
+ Project-URL: Repository, https://github.com/83noit/ble-bond
7
+ Project-URL: Issues, https://github.com/83noit/ble-bond/issues
8
+ Project-URL: Changelog, https://github.com/83noit/ble-bond/blob/main/CHANGELOG.md
9
+ Author: 83noit
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ License-File: THIRD_PARTY_NOTICES.md
13
+ Keywords: ble,bleak,bluetooth,bonding,esphome,home-assistant,pairing
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
22
+ Classifier: Topic :: Home Automation
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.13
25
+ Requires-Dist: bleak-retry-connector>=4.7.1
26
+ Requires-Dist: bleak>=3.0.2
27
+ Requires-Dist: dbus-fast>=4.0; sys_platform == 'linux'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # ble-bond
31
+
32
+ [![CI](https://github.com/83noit/ble-bond/actions/workflows/ci.yml/badge.svg)](https://github.com/83noit/ble-bond/actions/workflows/ci.yml)
33
+ [![PyPI](https://img.shields.io/pypi/v/ble-bond)](https://pypi.org/project/ble-bond/)
34
+ [![License: MIT](https://img.shields.io/github/license/83noit/ble-bond)](https://github.com/83noit/ble-bond/blob/main/LICENSE)
35
+
36
+ Bonded Bluetooth LE sessions for devices that pair in a button window and answer one request at
37
+ a time.
38
+
39
+ Some devices accept a new bond only for a few seconds after a button is pressed, drop any link
40
+ that is not encrypted, and then answer requests with no request id, so a late or stray reply can
41
+ be taken for the wrong request. Reaching them through a Home Assistant Bluetooth proxy adds its
42
+ own traps: the bond lives on one proxy, Home Assistant picks the proxy for each attempt, and a
43
+ refusal through the wrong proxy says nothing about the bond. ble-bond handles that part, built
44
+ on [bleak](https://github.com/hbldh/bleak) and
45
+ [bleak-retry-connector](https://github.com/Bluetooth-Devices/bleak-retry-connector), and leaves
46
+ framing and the device's protocol to the device library.
47
+
48
+ Used by [grundfos-ble](https://github.com/83noit/grundfos-ble) (Grundfos ALPHA2 GO pumps) and
49
+ [mira-ble](https://github.com/83noit/mira-ble) (Mira digital showers).
50
+
51
+ ## What it does
52
+
53
+ - Pairs on every connection: on an ESPHome proxy a quick re-encrypt with the stored bond, real
54
+ pairing otherwise. A refusal (ESP-IDF reason 82, BlueZ `AuthenticationFailed`) raises
55
+ `PairingRequired`; a proxy that cannot pair at all raises `PairingUnsupported`.
56
+ - Records which adapter or proxy each attempt went through (`last_source`), refused attempts
57
+ included, so a refusal can be pinned on the path that saw it.
58
+ - On a local Linux adapter, registers a BlueZ pairing agent, one at a time, only while a new
59
+ bond is expected; `remove_bluez_bond` makes BlueZ forget a bond the device dropped.
60
+ - Runs one request at a time. A frame is taken as the reply only when the caller's check
61
+ accepts it; a request that does not finish (timeout, cancellation, failed write) closes the
62
+ link, so its late reply cannot answer the next request.
63
+ - What differs between devices (pauses, retries, how weak evidence about the bond is reported,
64
+ write size, connection parameters) is one `LinkPolicy`.
65
+
66
+ ## Usage
67
+
68
+ ```python
69
+ import asyncio
70
+
71
+ from bleak import BleakScanner
72
+ from ble_bond import BondedLink, LinkPolicy, PairingRequired
73
+
74
+ REPLY_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb"
75
+
76
+
77
+ class LengthFramed:
78
+ """The device's framing: here, a length byte that counts the whole frame."""
79
+
80
+ def __init__(self) -> None:
81
+ self.buffer = bytearray()
82
+
83
+ def feed(self, data: bytes | bytearray) -> list[bytes]:
84
+ self.buffer += data
85
+ frames = []
86
+ while self.buffer and len(self.buffer) >= self.buffer[0] > 0:
87
+ frames.append(bytes(self.buffer[: self.buffer[0]]))
88
+ del self.buffer[: self.buffer[0]]
89
+ return frames
90
+
91
+ def reset(self) -> None:
92
+ self.buffer.clear()
93
+
94
+
95
+ async def main() -> None:
96
+ device = await BleakScanner.find_device_by_address("AA:BB:CC:DD:EE:FF")
97
+ policy = LinkPolicy(settle_after_subscribe=0.5)
98
+ try:
99
+ async with BondedLink(
100
+ device, notify_uuid=REPLY_UUID, assembler=LengthFramed(), policy=policy
101
+ ) as link:
102
+ reply = await link.request(b"\x02\x01", accept=lambda frame: frame[1] == 0x01)
103
+ print(reply.hex(" "), "via", link.last_source)
104
+ except PairingRequired:
105
+ print("Press the device's button, then connect with expect_new_bond=True.")
106
+
107
+
108
+ asyncio.run(main())
109
+ ```
110
+
111
+ `ble_bond.testing` has a fake bleak client and a patch for the connection call, so a device
112
+ library can test its transport without hardware.
113
+
114
+ ## Compatibility
115
+
116
+ Every 1.x release is backward compatible: several device libraries may be installed in one Home
117
+ Assistant, which then holds a single copy of this package. Depend on `ble-bond>=1.0,<2`.
118
+
119
+ ## Acknowledgements
120
+
121
+ The BlueZ pairing agent is adapted from [alpha-hwr](https://github.com/eman/alpha-hwr) (MIT);
122
+ its notice is in [THIRD_PARTY_NOTICES.md](https://github.com/83noit/ble-bond/blob/main/THIRD_PARTY_NOTICES.md).
123
+ The pause after subscribing follows ESPHome's measurement in
124
+ [esphome/esphome#22651](https://github.com/esphome/esphome/pull/22651).
125
+
126
+ ## Licence
127
+
128
+ MIT
@@ -0,0 +1,11 @@
1
+ ble_bond/__init__.py,sha256=6hym8chYkQgHYdR2BhxoEzuveA7wyYg8s0gePI-PWfM,1170
2
+ ble_bond/bluez.py,sha256=UDFdkiu4Ke9H3KmEyb7ZVhTr00FCuj6F6X02KGBo0ZM,9190
3
+ ble_bond/exceptions.py,sha256=Pc3S1QvBJTw9GYtqqrlayNdEHeNlSUH95TypHypjlSc,2280
4
+ ble_bond/link.py,sha256=fCZWKyVq9wI6iNFitdIcvRYeClfPfH6AmJMJ6LhUYs8,28641
5
+ ble_bond/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ ble_bond/testing.py,sha256=uGxDO5zDS3_U5aS6IjxpUS_itaahlEj4L_gtHe5chNs,3561
7
+ ble_bond-1.0.0.dist-info/METADATA,sha256=WTgeeoGet_Cv67Dzw7LOOscbQpXZKuxoYN9_f53d2a8,5592
8
+ ble_bond-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ ble_bond-1.0.0.dist-info/licenses/LICENSE,sha256=8evlOimVnoLop3x6BmQ2ILzSd7KV3veAQI5VvEtNyKE,1063
10
+ ble_bond-1.0.0.dist-info/licenses/THIRD_PARTY_NOTICES.md,sha256=csw_18eKBJm4HS7Nop64SZx0ud2fGPSyDwOetxoAy0I,1507
11
+ ble_bond-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 83noit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,35 @@
1
+ # Third-party notices
2
+
3
+ ble-bond is MIT-licensed (see `LICENSE`). It includes code adapted from the project below,
4
+ whose licence asks for its copyright and permission notice to travel with every copy.
5
+
6
+ ## alpha-hwr
7
+
8
+ - Project: <https://github.com/eman/alpha-hwr>
9
+ - Used in: `src/ble_bond/bluez.py` (the BlueZ pairing agent and its one-at-a-time lock), adapted from
10
+ `src/alpha_hwr/core/pairing_agent.py`
11
+ - Licence: MIT
12
+
13
+ ```text
14
+ MIT License
15
+
16
+ Copyright (c) 2026 Emmanuel Levijarvi
17
+
18
+ Permission is hereby granted, free of charge, to any person obtaining a copy
19
+ of this software and associated documentation files (the "Software"), to deal
20
+ in the Software without restriction, including without limitation the rights
21
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22
+ copies of the Software, and to permit persons to whom the Software is
23
+ furnished to do so, subject to the following conditions:
24
+
25
+ The above copyright notice and this permission notice shall be included in all
26
+ copies or substantial portions of the Software.
27
+
28
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
34
+ SOFTWARE.
35
+ ```