offline-protocol-sdk 0.28.0__py3-none-win_amd64.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.
- offline_protocol_sdk/__init__.py +22 -0
- offline_protocol_sdk/_callback_reentrancy.py +64 -0
- offline_protocol_sdk/address_declaration.py +207 -0
- offline_protocol_sdk/ble_manager.py +595 -0
- offline_protocol_sdk/ble_peripheral.py +673 -0
- offline_protocol_sdk/dnssd_bridge.py +614 -0
- offline_protocol_sdk/gateway_attach_policy.py +437 -0
- offline_protocol_sdk/gateway_manager.py +1217 -0
- offline_protocol_sdk/gateway_verdict_tracker.py +97 -0
- offline_protocol_sdk/internet_manager.py +1444 -0
- offline_protocol_sdk/legacy_store_adoption.py +184 -0
- offline_protocol_sdk/local_api/__init__.py +34 -0
- offline_protocol_sdk/local_api/authz.py +180 -0
- offline_protocol_sdk/local_api/cli.py +171 -0
- offline_protocol_sdk/local_api/codec.py +210 -0
- offline_protocol_sdk/local_api/dispatch.py +537 -0
- offline_protocol_sdk/local_api/mux.py +239 -0
- offline_protocol_sdk/local_api/server.py +546 -0
- offline_protocol_sdk/local_api/session.py +86 -0
- offline_protocol_sdk/local_api/table.py +849 -0
- offline_protocol_sdk/offline_protocol.py +13508 -0
- offline_protocol_sdk/peer_stream_manager.py +1303 -0
- offline_protocol_sdk/presence_watch_policy.py +102 -0
- offline_protocol_sdk/protocol_manager.py +1108 -0
- offline_protocol_sdk/relay_answer_prefixes.py +61 -0
- offline_protocol_sdk/secure_storage.py +551 -0
- offline_protocol_sdk/services.py +195 -0
- offline_protocol_sdk/state_storage.py +452 -0
- offline_protocol_sdk/storage_namespace.py +33 -0
- offline_protocol_sdk/transport_manager.py +138 -0
- offline_protocol_sdk/uniffi.dll +0 -0
- offline_protocol_sdk-0.28.0.dist-info/METADATA +519 -0
- offline_protocol_sdk-0.28.0.dist-info/RECORD +40 -0
- offline_protocol_sdk-0.28.0.dist-info/WHEEL +5 -0
- offline_protocol_sdk-0.28.0.dist-info/entry_points.txt +2 -0
- offline_protocol_sdk-0.28.0.dist-info/licenses/EXPORT.md +68 -0
- offline_protocol_sdk-0.28.0.dist-info/licenses/LICENSE +661 -0
- offline_protocol_sdk-0.28.0.dist-info/licenses/LICENSE-COMMERCIAL.md +89 -0
- offline_protocol_sdk-0.28.0.dist-info/licenses/THIRD-PARTY-NOTICES.md +6645 -0
- offline_protocol_sdk-0.28.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
"""BLE transport manager using the ``bleak`` library.
|
|
2
|
+
|
|
3
|
+
Mirrors the central (scanner) role from ``BleManager.swift`` /
|
|
4
|
+
``BleManager.kt``. Connects to nearby mesh peers over Bluetooth Low
|
|
5
|
+
Energy, verifies their identity, subscribes to message notifications, and
|
|
6
|
+
drives the UniFFI ``OfflineProtocol`` BLE transport methods.
|
|
7
|
+
|
|
8
|
+
A peer id handed to the core is a proved address, never a label. The
|
|
9
|
+
central reads the peer's Identity characteristic, hands the bytes to the
|
|
10
|
+
core's ``verify_identity_assertion`` (the one verifier of that layout), and
|
|
11
|
+
compares the address it returns to the Device id characteristic, exactly.
|
|
12
|
+
Only then is the peer announced, and it is announced under the derived
|
|
13
|
+
address rather than the string it served. A link whose peer cannot be
|
|
14
|
+
verified is disconnected and never announced, not even under its Bluetooth
|
|
15
|
+
address: an unverifiable identity and an absent one are the same thing.
|
|
16
|
+
|
|
17
|
+
**Known limitation:** ``bleak`` only supports the *central* (scanner/client)
|
|
18
|
+
role. Peripheral (advertiser/GATT server) support requires the ``bless``
|
|
19
|
+
library or platform-specific code and is not included here. This means a
|
|
20
|
+
desktop node can *discover and receive from* mobile peers, but mobile peers
|
|
21
|
+
cannot discover the desktop unless the desktop also runs a GATT server via
|
|
22
|
+
``bless`` or an external tool.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import asyncio
|
|
28
|
+
import logging
|
|
29
|
+
import threading
|
|
30
|
+
import time
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
from bleak import BleakClient, BleakScanner
|
|
34
|
+
from bleak.backends.device import BLEDevice
|
|
35
|
+
from bleak.backends.scanner import AdvertisementData
|
|
36
|
+
|
|
37
|
+
from .offline_protocol import verify_identity_assertion
|
|
38
|
+
from .transport_manager import TransportError, TransportManager, TransportState
|
|
39
|
+
|
|
40
|
+
logger = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
# -- BLE constants (matching iOS/Android) -------------------------------------
|
|
43
|
+
|
|
44
|
+
SERVICE_UUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
|
|
45
|
+
MESSAGE_CHAR_UUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
|
|
46
|
+
DEVICE_ID_CHAR_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
|
|
47
|
+
IDENTITY_CHAR_UUID = "6e400004-b5a3-f393-e0a9-e50e24dcca9e"
|
|
48
|
+
|
|
49
|
+
MAX_FRAGMENT_SIZE = 185
|
|
50
|
+
CONNECTION_TIMEOUT = 10.0 # seconds
|
|
51
|
+
ADAPTIVE_MIN_RSSI = -85
|
|
52
|
+
ADAPTIVE_LOW_DENSITY_THRESHOLD = 10
|
|
53
|
+
ADAPTIVE_HIGH_DENSITY_THRESHOLD = 50
|
|
54
|
+
ADAPTIVE_MAX_CONNECTIONS_PER_MINUTE = 6
|
|
55
|
+
ADAPTIVE_COOLDOWN_PER_PERIPHERAL = 30.0 # seconds
|
|
56
|
+
# Ceiling on the per-peripheral cooldown after repeated identity refusals. A
|
|
57
|
+
# peer that cannot prove its address (an old peripheral, a phone before MLS
|
|
58
|
+
# init) fails the same way every time, and without a backoff each retry spends
|
|
59
|
+
# the global per-minute connection budget that verifiable peers need.
|
|
60
|
+
REFUSAL_BACKOFF_MAX = 600.0 # seconds
|
|
61
|
+
PEER_LOST_TIMEOUT = 30.0 # seconds since last seen
|
|
62
|
+
SCAN_RESTART_INTERVAL = 30.0
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class BleManager(TransportManager):
|
|
66
|
+
"""BLE transport — central (scanner) role.
|
|
67
|
+
|
|
68
|
+
Discovers nearby mesh peripherals advertising ``SERVICE_UUID``, connects
|
|
69
|
+
to them, verifies the address they claim, subscribes to the message
|
|
70
|
+
characteristic, and forwards incoming BLE fragments to the Rust protocol
|
|
71
|
+
core.
|
|
72
|
+
|
|
73
|
+
Outgoing fragments are sent event-driven: the protocol calls
|
|
74
|
+
``BleTransportCallback.on_fragments_available()`` which triggers
|
|
75
|
+
:meth:`_drain_outgoing_fragments`.
|
|
76
|
+
|
|
77
|
+
Parameters
|
|
78
|
+
----------
|
|
79
|
+
protocol:
|
|
80
|
+
The ``OfflineProtocol`` UniFFI instance.
|
|
81
|
+
device_id:
|
|
82
|
+
Local device identifier.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
transport_id = "ble"
|
|
86
|
+
transport_name = "Bluetooth Low Energy"
|
|
87
|
+
|
|
88
|
+
def __init__(self, protocol: Any, device_id: str) -> None:
|
|
89
|
+
super().__init__()
|
|
90
|
+
self._protocol = protocol
|
|
91
|
+
self._device_id = device_id
|
|
92
|
+
|
|
93
|
+
# Scanner
|
|
94
|
+
self._scanner: BleakScanner | None = None
|
|
95
|
+
self._scan_task: asyncio.Task[None] | None = None
|
|
96
|
+
|
|
97
|
+
# Lock protecting shared state accessed from bleak's scanner thread
|
|
98
|
+
# (_on_advertisement) AND the asyncio event loop. Guards: _last_seen,
|
|
99
|
+
# _connection_attempts, _global_attempts, _connecting, _clients,
|
|
100
|
+
# _peer_device_ids, _refusals.
|
|
101
|
+
self._lock = threading.Lock()
|
|
102
|
+
|
|
103
|
+
# Connected peers: address -> BleakClient
|
|
104
|
+
self._clients: dict[str, BleakClient] = {}
|
|
105
|
+
# address -> device_id mapping
|
|
106
|
+
self._peer_device_ids: dict[str, str] = {}
|
|
107
|
+
# device_id -> address reverse lookup (avoids linear scan)
|
|
108
|
+
self._device_id_to_addr: dict[str, str] = {}
|
|
109
|
+
# address -> last-seen timestamp
|
|
110
|
+
self._last_seen: dict[str, float] = {}
|
|
111
|
+
# address -> last connection attempt timestamp (rate limiting)
|
|
112
|
+
self._connection_attempts: dict[str, float] = {}
|
|
113
|
+
# Global connection attempt timestamps (rate limiting)
|
|
114
|
+
self._global_attempts: list[float] = []
|
|
115
|
+
# Addresses currently being connected to (prevent concurrent attempts)
|
|
116
|
+
self._connecting: set[str] = set()
|
|
117
|
+
# address -> consecutive identity refusals; each doubles the cooldown
|
|
118
|
+
self._refusals: dict[str, int] = {}
|
|
119
|
+
|
|
120
|
+
# Metrics
|
|
121
|
+
self._bytes_sent: int = 0
|
|
122
|
+
self._bytes_received: int = 0
|
|
123
|
+
self._fragments_sent: int = 0
|
|
124
|
+
self._fragments_received: int = 0
|
|
125
|
+
|
|
126
|
+
# Event loop — captured in start() for thread-safe callback scheduling
|
|
127
|
+
self._loop: asyncio.AbstractEventLoop | None = None
|
|
128
|
+
|
|
129
|
+
# Serialisation flag — prevents concurrent _drain_outgoing_fragments
|
|
130
|
+
self._draining: bool = False
|
|
131
|
+
|
|
132
|
+
# Tasks
|
|
133
|
+
self._peer_cleanup_task: asyncio.Task[None] | None = None
|
|
134
|
+
|
|
135
|
+
# -- TransportManager interface -------------------------------------------
|
|
136
|
+
|
|
137
|
+
def is_available(self) -> bool:
|
|
138
|
+
# bleak should be importable; actual adapter availability is checked
|
|
139
|
+
# when scanning starts.
|
|
140
|
+
return True
|
|
141
|
+
|
|
142
|
+
async def start(self) -> None:
|
|
143
|
+
if self._state == TransportState.RUNNING:
|
|
144
|
+
raise TransportError("BLE transport is already running")
|
|
145
|
+
|
|
146
|
+
self._loop = asyncio.get_running_loop()
|
|
147
|
+
self._update_state(TransportState.STARTING)
|
|
148
|
+
self._emit_diagnostic("info", "Starting BLE transport", {
|
|
149
|
+
"device_id": self._device_id,
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
try:
|
|
153
|
+
self._scanner = BleakScanner(
|
|
154
|
+
detection_callback=self._on_advertisement,
|
|
155
|
+
service_uuids=[SERVICE_UUID],
|
|
156
|
+
)
|
|
157
|
+
await self._scanner.start()
|
|
158
|
+
except Exception as exc:
|
|
159
|
+
self._update_state(TransportState.STOPPED)
|
|
160
|
+
raise TransportError(f"BLE scan start failed: {exc}") from exc
|
|
161
|
+
|
|
162
|
+
# Notify protocol
|
|
163
|
+
try:
|
|
164
|
+
self._protocol.ble_status_changed(is_available=True)
|
|
165
|
+
except Exception:
|
|
166
|
+
logger.debug("ble_status_changed(True) failed", exc_info=True)
|
|
167
|
+
|
|
168
|
+
self._update_state(TransportState.RUNNING)
|
|
169
|
+
|
|
170
|
+
# Start background tasks
|
|
171
|
+
self._peer_cleanup_task = asyncio.ensure_future(
|
|
172
|
+
self._peer_cleanup_loop()
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
self._emit_diagnostic("info", "BLE transport started")
|
|
176
|
+
|
|
177
|
+
async def stop(self) -> None:
|
|
178
|
+
# STOPPING too: a stop() cancelled part-way (a shutdown deadline)
|
|
179
|
+
# leaves the transport there, and a retry that returned at once would
|
|
180
|
+
# leave it half torn down for good. Every step below is idempotent.
|
|
181
|
+
if self._state not in (
|
|
182
|
+
TransportState.RUNNING,
|
|
183
|
+
TransportState.STARTING,
|
|
184
|
+
TransportState.STOPPING,
|
|
185
|
+
):
|
|
186
|
+
return
|
|
187
|
+
|
|
188
|
+
self._update_state(TransportState.STOPPING)
|
|
189
|
+
|
|
190
|
+
# Stop scanner
|
|
191
|
+
if self._scanner is not None:
|
|
192
|
+
try:
|
|
193
|
+
await self._scanner.stop()
|
|
194
|
+
except Exception:
|
|
195
|
+
pass
|
|
196
|
+
self._scanner = None
|
|
197
|
+
|
|
198
|
+
# Cancel background tasks
|
|
199
|
+
if self._peer_cleanup_task is not None and not self._peer_cleanup_task.done():
|
|
200
|
+
self._peer_cleanup_task.cancel()
|
|
201
|
+
self._peer_cleanup_task = None
|
|
202
|
+
|
|
203
|
+
# Disconnect all clients
|
|
204
|
+
with self._lock:
|
|
205
|
+
clients_snapshot = list(self._clients.items())
|
|
206
|
+
for addr, client in clients_snapshot:
|
|
207
|
+
try:
|
|
208
|
+
await client.disconnect()
|
|
209
|
+
except Exception:
|
|
210
|
+
pass
|
|
211
|
+
with self._lock:
|
|
212
|
+
self._clients.clear()
|
|
213
|
+
self._peer_device_ids.clear()
|
|
214
|
+
self._device_id_to_addr.clear()
|
|
215
|
+
self._last_seen.clear()
|
|
216
|
+
self._connecting.clear()
|
|
217
|
+
|
|
218
|
+
try:
|
|
219
|
+
self._protocol.ble_status_changed(is_available=False)
|
|
220
|
+
except Exception:
|
|
221
|
+
logger.debug("ble_status_changed(False) failed")
|
|
222
|
+
|
|
223
|
+
self._update_state(TransportState.STOPPED)
|
|
224
|
+
self._emit_diagnostic("info", "BLE transport stopped")
|
|
225
|
+
|
|
226
|
+
def get_metrics(self) -> dict[str, Any]:
|
|
227
|
+
with self._lock:
|
|
228
|
+
return {
|
|
229
|
+
"bytes_sent": self._bytes_sent,
|
|
230
|
+
"bytes_received": self._bytes_received,
|
|
231
|
+
"fragments_sent": self._fragments_sent,
|
|
232
|
+
"fragments_received": self._fragments_received,
|
|
233
|
+
"connected_peers": len(self._clients),
|
|
234
|
+
"discovered_peers": len(self._last_seen),
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
# -- scanning / discovery -------------------------------------------------
|
|
238
|
+
|
|
239
|
+
def _on_advertisement(
|
|
240
|
+
self, device: BLEDevice, adv_data: AdvertisementData
|
|
241
|
+
) -> None:
|
|
242
|
+
"""Called by bleak for each BLE advertisement detected.
|
|
243
|
+
|
|
244
|
+
NOTE: This is invoked from bleak's scanner thread, not the asyncio
|
|
245
|
+
event loop. All shared-state mutations go through ``_lock``.
|
|
246
|
+
"""
|
|
247
|
+
addr = device.address
|
|
248
|
+
rssi = adv_data.rssi if adv_data.rssi is not None else -100
|
|
249
|
+
|
|
250
|
+
# Filter weak signals
|
|
251
|
+
if rssi < ADAPTIVE_MIN_RSSI:
|
|
252
|
+
return
|
|
253
|
+
|
|
254
|
+
now = time.monotonic()
|
|
255
|
+
should_connect = False
|
|
256
|
+
|
|
257
|
+
with self._lock:
|
|
258
|
+
self._last_seen[addr] = now
|
|
259
|
+
|
|
260
|
+
# A peer is announced only under an address this link proved.
|
|
261
|
+
# Before that there is nothing to announce: a Bluetooth address
|
|
262
|
+
# is a label, and the core keys routes by what it is handed.
|
|
263
|
+
peer_id = self._peer_device_ids.get(addr)
|
|
264
|
+
|
|
265
|
+
# Attempt connection if not already connected / connecting.
|
|
266
|
+
if addr not in self._clients and addr not in self._connecting:
|
|
267
|
+
if self._should_connect_locked(addr, now):
|
|
268
|
+
self._connecting.add(addr)
|
|
269
|
+
should_connect = True
|
|
270
|
+
|
|
271
|
+
# Protocol calls outside the lock to avoid holding it during FFI
|
|
272
|
+
if peer_id is not None:
|
|
273
|
+
try:
|
|
274
|
+
self._protocol.ble_peer_discovered(peer_id=peer_id, rssi=rssi)
|
|
275
|
+
except Exception:
|
|
276
|
+
logger.debug("ble_peer_discovered failed for %s", peer_id)
|
|
277
|
+
|
|
278
|
+
if should_connect:
|
|
279
|
+
loop = self._loop
|
|
280
|
+
if loop is not None and not loop.is_closed() and loop.is_running():
|
|
281
|
+
loop.call_soon_threadsafe(
|
|
282
|
+
asyncio.ensure_future,
|
|
283
|
+
self._connect_to_peer(device),
|
|
284
|
+
)
|
|
285
|
+
else:
|
|
286
|
+
with self._lock:
|
|
287
|
+
self._connecting.discard(addr)
|
|
288
|
+
|
|
289
|
+
def _should_connect_locked(self, addr: str, now: float) -> bool:
|
|
290
|
+
"""Adaptive rate-limiting. Caller must hold ``_lock``."""
|
|
291
|
+
# Per-peripheral cooldown
|
|
292
|
+
last_attempt = self._connection_attempts.get(addr, 0)
|
|
293
|
+
if now - last_attempt < self._cooldown_locked(addr):
|
|
294
|
+
return False
|
|
295
|
+
|
|
296
|
+
# Global rate limiting
|
|
297
|
+
cutoff = now - 60.0
|
|
298
|
+
self._global_attempts = [t for t in self._global_attempts if t > cutoff]
|
|
299
|
+
if len(self._global_attempts) >= ADAPTIVE_MAX_CONNECTIONS_PER_MINUTE:
|
|
300
|
+
return False
|
|
301
|
+
|
|
302
|
+
return True
|
|
303
|
+
|
|
304
|
+
def _cooldown_locked(self, addr: str) -> float:
|
|
305
|
+
"""Per-peripheral cooldown, doubled per consecutive identity refusal
|
|
306
|
+
and capped at ``REFUSAL_BACKOFF_MAX``. Caller must hold ``_lock``."""
|
|
307
|
+
refusals = self._refusals.get(addr, 0)
|
|
308
|
+
if refusals == 0:
|
|
309
|
+
return ADAPTIVE_COOLDOWN_PER_PERIPHERAL
|
|
310
|
+
return min(
|
|
311
|
+
ADAPTIVE_COOLDOWN_PER_PERIPHERAL * (2 ** min(refusals, 16)),
|
|
312
|
+
REFUSAL_BACKOFF_MAX,
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
def _record_refusal(self, addr: str) -> None:
|
|
316
|
+
with self._lock:
|
|
317
|
+
self._refusals[addr] = self._refusals.get(addr, 0) + 1
|
|
318
|
+
|
|
319
|
+
# -- connection management ------------------------------------------------
|
|
320
|
+
|
|
321
|
+
async def _connect_to_peer(self, device: BLEDevice) -> None:
|
|
322
|
+
addr = device.address
|
|
323
|
+
# addr is already in self._connecting (added in _on_advertisement)
|
|
324
|
+
now = time.monotonic()
|
|
325
|
+
with self._lock:
|
|
326
|
+
self._connection_attempts[addr] = now
|
|
327
|
+
self._global_attempts.append(now)
|
|
328
|
+
|
|
329
|
+
try:
|
|
330
|
+
client = BleakClient(
|
|
331
|
+
device,
|
|
332
|
+
timeout=CONNECTION_TIMEOUT,
|
|
333
|
+
disconnected_callback=lambda c, _addr=addr: (
|
|
334
|
+
self._loop.call_soon_threadsafe(
|
|
335
|
+
asyncio.ensure_future,
|
|
336
|
+
self._on_peer_disconnected(_addr),
|
|
337
|
+
)
|
|
338
|
+
if self._loop is not None
|
|
339
|
+
and not self._loop.is_closed()
|
|
340
|
+
and self._loop.is_running()
|
|
341
|
+
else None
|
|
342
|
+
),
|
|
343
|
+
)
|
|
344
|
+
await client.connect()
|
|
345
|
+
|
|
346
|
+
# The claim, then the proof. Both reads must succeed and the
|
|
347
|
+
# proof must name the claim, or the link is dropped unannounced.
|
|
348
|
+
claimed = await self._read_device_id(client)
|
|
349
|
+
if claimed is None:
|
|
350
|
+
self._record_refusal(addr)
|
|
351
|
+
await client.disconnect()
|
|
352
|
+
return
|
|
353
|
+
identity = await self._read_identity(client)
|
|
354
|
+
device_id = self._verify_peer(addr, claimed, identity)
|
|
355
|
+
if device_id is None:
|
|
356
|
+
self._record_refusal(addr)
|
|
357
|
+
await client.disconnect()
|
|
358
|
+
return
|
|
359
|
+
|
|
360
|
+
with self._lock:
|
|
361
|
+
self._refusals.pop(addr, None)
|
|
362
|
+
self._clients[addr] = client
|
|
363
|
+
self._peer_device_ids[addr] = device_id
|
|
364
|
+
self._device_id_to_addr[device_id] = addr
|
|
365
|
+
|
|
366
|
+
# Announce the peer under the address it proved
|
|
367
|
+
try:
|
|
368
|
+
rssi = -70 # approximate; bleak doesn't expose RSSI post-connect
|
|
369
|
+
self._protocol.ble_peer_discovered(peer_id=device_id, rssi=rssi)
|
|
370
|
+
except Exception:
|
|
371
|
+
logger.debug("ble_peer_discovered failed for %s", device_id)
|
|
372
|
+
|
|
373
|
+
# Subscribe to message notifications
|
|
374
|
+
await self._subscribe_to_messages(client, addr, device_id)
|
|
375
|
+
|
|
376
|
+
self._emit_diagnostic("info", "Connected to peer", {
|
|
377
|
+
"address": addr,
|
|
378
|
+
"device_id": device_id,
|
|
379
|
+
})
|
|
380
|
+
|
|
381
|
+
except Exception as exc:
|
|
382
|
+
self._emit_diagnostic("debug", f"Connection to {addr} failed: {exc}")
|
|
383
|
+
finally:
|
|
384
|
+
with self._lock:
|
|
385
|
+
self._connecting.discard(addr)
|
|
386
|
+
|
|
387
|
+
async def _read_device_id(self, client: BleakClient) -> str | None:
|
|
388
|
+
"""Read the device ID characteristic from a connected peripheral."""
|
|
389
|
+
try:
|
|
390
|
+
data = await client.read_gatt_char(DEVICE_ID_CHAR_UUID)
|
|
391
|
+
return data.decode("utf-8").strip("\x00")
|
|
392
|
+
except Exception as exc:
|
|
393
|
+
self._emit_diagnostic("debug", f"Failed to read device ID: {exc}")
|
|
394
|
+
return None
|
|
395
|
+
|
|
396
|
+
async def _read_identity(self, client: BleakClient) -> bytes | None:
|
|
397
|
+
"""Read the Identity characteristic from a connected peripheral."""
|
|
398
|
+
try:
|
|
399
|
+
return bytes(await client.read_gatt_char(IDENTITY_CHAR_UUID))
|
|
400
|
+
except Exception as exc:
|
|
401
|
+
self._emit_diagnostic("debug", f"Failed to read identity: {exc}")
|
|
402
|
+
return None
|
|
403
|
+
|
|
404
|
+
def _verify_peer(
|
|
405
|
+
self, addr: str, claimed: str, identity: bytes | None
|
|
406
|
+
) -> str | None:
|
|
407
|
+
"""Turn a claim and a proof into the one address to announce.
|
|
408
|
+
|
|
409
|
+
Runs the four steps the Bluetooth LE framing chapter specifies. The
|
|
410
|
+
first three (parse, verify the signature under the key, derive the
|
|
411
|
+
address) are the core's, through ``verify_identity_assertion``; the
|
|
412
|
+
fourth, the exact comparison against the Device id characteristic,
|
|
413
|
+
is here because only this side read that characteristic. Every
|
|
414
|
+
failure returns ``None`` and emits why, and the caller disconnects:
|
|
415
|
+
there is no accept-but-flag state, because what this returns becomes
|
|
416
|
+
``Message.recipient`` on every outbound frame and the peer id the
|
|
417
|
+
core matches ``Message.sender`` against.
|
|
418
|
+
"""
|
|
419
|
+
if identity is None:
|
|
420
|
+
self._emit_diagnostic("warning", "Peer served no identity", {
|
|
421
|
+
"address": addr,
|
|
422
|
+
"claimed": claimed,
|
|
423
|
+
})
|
|
424
|
+
return None
|
|
425
|
+
try:
|
|
426
|
+
derived = verify_identity_assertion(list(identity))
|
|
427
|
+
except Exception as exc:
|
|
428
|
+
self._emit_diagnostic("warning", "Peer identity did not verify", {
|
|
429
|
+
"address": addr,
|
|
430
|
+
"claimed": claimed,
|
|
431
|
+
"error": str(exc),
|
|
432
|
+
})
|
|
433
|
+
return None
|
|
434
|
+
if derived != claimed:
|
|
435
|
+
# Exact, never normalised: a value differing only in case belongs
|
|
436
|
+
# to a peer that did not derive its own id the way this one did.
|
|
437
|
+
self._emit_diagnostic("warning", "Peer identity names another address", {
|
|
438
|
+
"address": addr,
|
|
439
|
+
"claimed": claimed,
|
|
440
|
+
"derived": derived,
|
|
441
|
+
})
|
|
442
|
+
return None
|
|
443
|
+
return derived
|
|
444
|
+
|
|
445
|
+
async def _subscribe_to_messages(
|
|
446
|
+
self, client: BleakClient, addr: str, device_id: str
|
|
447
|
+
) -> None:
|
|
448
|
+
"""Subscribe to the message characteristic for incoming fragments."""
|
|
449
|
+
try:
|
|
450
|
+
def on_notification(_sender: int, data: bytearray) -> None:
|
|
451
|
+
self._on_fragment_received(device_id, bytes(data))
|
|
452
|
+
|
|
453
|
+
await client.start_notify(MESSAGE_CHAR_UUID, on_notification)
|
|
454
|
+
except Exception as exc:
|
|
455
|
+
self._emit_diagnostic(
|
|
456
|
+
"warning", f"Failed to subscribe to messages from {device_id}: {exc}"
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
def _on_fragment_received(self, sender_id: str, fragment: bytes) -> None:
|
|
460
|
+
"""Handle an incoming BLE fragment from a peer."""
|
|
461
|
+
with self._lock:
|
|
462
|
+
self._bytes_received += len(fragment)
|
|
463
|
+
self._fragments_received += 1
|
|
464
|
+
try:
|
|
465
|
+
self._protocol.ble_fragment_received(
|
|
466
|
+
sender_id=sender_id, fragment=list(fragment)
|
|
467
|
+
)
|
|
468
|
+
except Exception as exc:
|
|
469
|
+
self._emit_diagnostic("error", f"Error feeding fragment to protocol: {exc}")
|
|
470
|
+
|
|
471
|
+
async def _on_peer_disconnected(self, addr: str) -> None:
|
|
472
|
+
"""Called when a peer disconnects."""
|
|
473
|
+
with self._lock:
|
|
474
|
+
device_id = self._peer_device_ids.pop(addr, None)
|
|
475
|
+
self._clients.pop(addr, None)
|
|
476
|
+
if device_id is not None:
|
|
477
|
+
self._device_id_to_addr.pop(device_id, None)
|
|
478
|
+
|
|
479
|
+
# A link that never proved a peer was never announced, so there is
|
|
480
|
+
# nothing to report lost.
|
|
481
|
+
if device_id is None:
|
|
482
|
+
self._emit_diagnostic("debug", f"Unverified link closed: {addr}")
|
|
483
|
+
return
|
|
484
|
+
|
|
485
|
+
try:
|
|
486
|
+
self._protocol.ble_peer_lost(peer_id=device_id)
|
|
487
|
+
except Exception:
|
|
488
|
+
logger.debug("ble_peer_lost failed for %s", device_id)
|
|
489
|
+
|
|
490
|
+
self._emit_diagnostic("info", f"Peer disconnected: {device_id}")
|
|
491
|
+
|
|
492
|
+
# -- outgoing fragment handling -------------------------------------------
|
|
493
|
+
|
|
494
|
+
def on_fragments_available(self) -> None:
|
|
495
|
+
"""Called by ``BleTransportCallback.on_fragments_available()``.
|
|
496
|
+
|
|
497
|
+
Drains outgoing fragments from the protocol core and writes them
|
|
498
|
+
to connected peers via GATT.
|
|
499
|
+
|
|
500
|
+
This is invoked from a Rust UniFFI callback thread, so we must use
|
|
501
|
+
``call_soon_threadsafe`` to schedule work on the asyncio event loop.
|
|
502
|
+
"""
|
|
503
|
+
loop = self._loop
|
|
504
|
+
if loop is not None and not loop.is_closed() and loop.is_running():
|
|
505
|
+
loop.call_soon_threadsafe(asyncio.ensure_future, self._drain_outgoing_fragments())
|
|
506
|
+
|
|
507
|
+
async def _drain_outgoing_fragments(self) -> None:
|
|
508
|
+
"""Poll and send all queued outgoing fragments."""
|
|
509
|
+
if self._draining:
|
|
510
|
+
return
|
|
511
|
+
self._draining = True
|
|
512
|
+
try:
|
|
513
|
+
await self._drain_outgoing_fragments_inner()
|
|
514
|
+
finally:
|
|
515
|
+
self._draining = False
|
|
516
|
+
|
|
517
|
+
async def _drain_outgoing_fragments_inner(self) -> None:
|
|
518
|
+
while True:
|
|
519
|
+
try:
|
|
520
|
+
frag = self._protocol.ble_get_next_fragment()
|
|
521
|
+
except (AttributeError, ReferenceError) as exc:
|
|
522
|
+
logger.error("Protocol instance invalid: %s", exc)
|
|
523
|
+
break
|
|
524
|
+
except Exception as exc:
|
|
525
|
+
logger.warning("Unexpected error getting next fragment: %s", exc)
|
|
526
|
+
break
|
|
527
|
+
if frag is None:
|
|
528
|
+
break
|
|
529
|
+
|
|
530
|
+
recipient = frag.recipient_id
|
|
531
|
+
data = bytes(frag.data)
|
|
532
|
+
|
|
533
|
+
# Find the client for this recipient
|
|
534
|
+
client = self._find_client_for_peer(recipient)
|
|
535
|
+
if client is not None and client.is_connected:
|
|
536
|
+
try:
|
|
537
|
+
await client.write_gatt_char(
|
|
538
|
+
MESSAGE_CHAR_UUID,
|
|
539
|
+
data,
|
|
540
|
+
response=False,
|
|
541
|
+
)
|
|
542
|
+
with self._lock:
|
|
543
|
+
self._bytes_sent += len(data)
|
|
544
|
+
self._fragments_sent += 1
|
|
545
|
+
except Exception as exc:
|
|
546
|
+
self._emit_diagnostic(
|
|
547
|
+
"warning", f"Failed to send fragment to {recipient}: {exc}"
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
# Return fragment to pool regardless of send outcome
|
|
551
|
+
try:
|
|
552
|
+
self._protocol.ble_return_fragment()
|
|
553
|
+
except Exception:
|
|
554
|
+
logger.debug("ble_return_fragment failed", exc_info=True)
|
|
555
|
+
|
|
556
|
+
def _find_client_for_peer(self, peer_id: str) -> BleakClient | None:
|
|
557
|
+
"""Find the BleakClient for a given device ID (O(1) via reverse map)."""
|
|
558
|
+
with self._lock:
|
|
559
|
+
addr = self._device_id_to_addr.get(peer_id)
|
|
560
|
+
if addr is not None:
|
|
561
|
+
return self._clients.get(addr)
|
|
562
|
+
return None
|
|
563
|
+
|
|
564
|
+
# -- background tasks -----------------------------------------------------
|
|
565
|
+
|
|
566
|
+
async def _peer_cleanup_loop(self) -> None:
|
|
567
|
+
"""Periodically remove stale peers that haven't been seen recently."""
|
|
568
|
+
try:
|
|
569
|
+
while True:
|
|
570
|
+
await asyncio.sleep(PEER_LOST_TIMEOUT / 2)
|
|
571
|
+
now = time.monotonic()
|
|
572
|
+
stale_device_ids: list[str] = []
|
|
573
|
+
with self._lock:
|
|
574
|
+
stale = [
|
|
575
|
+
addr
|
|
576
|
+
for addr, ts in self._last_seen.items()
|
|
577
|
+
if now - ts > PEER_LOST_TIMEOUT
|
|
578
|
+
and addr not in self._clients
|
|
579
|
+
]
|
|
580
|
+
for addr in stale:
|
|
581
|
+
self._last_seen.pop(addr, None)
|
|
582
|
+
self._refusals.pop(addr, None)
|
|
583
|
+
device_id = self._peer_device_ids.pop(addr, None)
|
|
584
|
+
if device_id is None:
|
|
585
|
+
continue # never announced, nothing to report
|
|
586
|
+
self._device_id_to_addr.pop(device_id, None)
|
|
587
|
+
stale_device_ids.append(device_id)
|
|
588
|
+
# Notify protocol outside the lock
|
|
589
|
+
for device_id in stale_device_ids:
|
|
590
|
+
try:
|
|
591
|
+
self._protocol.ble_peer_lost(peer_id=device_id)
|
|
592
|
+
except Exception:
|
|
593
|
+
logger.debug("ble_peer_lost failed for %s", device_id)
|
|
594
|
+
except asyncio.CancelledError:
|
|
595
|
+
return
|