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.
Files changed (40) hide show
  1. offline_protocol_sdk/__init__.py +22 -0
  2. offline_protocol_sdk/_callback_reentrancy.py +64 -0
  3. offline_protocol_sdk/address_declaration.py +207 -0
  4. offline_protocol_sdk/ble_manager.py +595 -0
  5. offline_protocol_sdk/ble_peripheral.py +673 -0
  6. offline_protocol_sdk/dnssd_bridge.py +614 -0
  7. offline_protocol_sdk/gateway_attach_policy.py +437 -0
  8. offline_protocol_sdk/gateway_manager.py +1217 -0
  9. offline_protocol_sdk/gateway_verdict_tracker.py +97 -0
  10. offline_protocol_sdk/internet_manager.py +1444 -0
  11. offline_protocol_sdk/legacy_store_adoption.py +184 -0
  12. offline_protocol_sdk/local_api/__init__.py +34 -0
  13. offline_protocol_sdk/local_api/authz.py +180 -0
  14. offline_protocol_sdk/local_api/cli.py +171 -0
  15. offline_protocol_sdk/local_api/codec.py +210 -0
  16. offline_protocol_sdk/local_api/dispatch.py +537 -0
  17. offline_protocol_sdk/local_api/mux.py +239 -0
  18. offline_protocol_sdk/local_api/server.py +546 -0
  19. offline_protocol_sdk/local_api/session.py +86 -0
  20. offline_protocol_sdk/local_api/table.py +849 -0
  21. offline_protocol_sdk/offline_protocol.py +13508 -0
  22. offline_protocol_sdk/peer_stream_manager.py +1303 -0
  23. offline_protocol_sdk/presence_watch_policy.py +102 -0
  24. offline_protocol_sdk/protocol_manager.py +1108 -0
  25. offline_protocol_sdk/relay_answer_prefixes.py +61 -0
  26. offline_protocol_sdk/secure_storage.py +551 -0
  27. offline_protocol_sdk/services.py +195 -0
  28. offline_protocol_sdk/state_storage.py +452 -0
  29. offline_protocol_sdk/storage_namespace.py +33 -0
  30. offline_protocol_sdk/transport_manager.py +138 -0
  31. offline_protocol_sdk/uniffi.dll +0 -0
  32. offline_protocol_sdk-0.28.0.dist-info/METADATA +519 -0
  33. offline_protocol_sdk-0.28.0.dist-info/RECORD +40 -0
  34. offline_protocol_sdk-0.28.0.dist-info/WHEEL +5 -0
  35. offline_protocol_sdk-0.28.0.dist-info/entry_points.txt +2 -0
  36. offline_protocol_sdk-0.28.0.dist-info/licenses/EXPORT.md +68 -0
  37. offline_protocol_sdk-0.28.0.dist-info/licenses/LICENSE +661 -0
  38. offline_protocol_sdk-0.28.0.dist-info/licenses/LICENSE-COMMERCIAL.md +89 -0
  39. offline_protocol_sdk-0.28.0.dist-info/licenses/THIRD-PARTY-NOTICES.md +6645 -0
  40. offline_protocol_sdk-0.28.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,673 @@
1
+ """BLE transport manager — peripheral (advertiser/GATT server) role.
2
+
3
+ Complements :class:`BleManager` (central/scanner role) by advertising a
4
+ GATT service so that phones and hardware devices can discover this desktop
5
+ node, connect, and exchange mesh messages over Bluetooth Low Energy.
6
+
7
+ Uses the ``bless`` library for GATT server functionality. On macOS this
8
+ is backed by CoreBluetooth; on Linux by BlueZ/D-Bus.
9
+
10
+ Typical usage::
11
+
12
+ peripheral = BlePeripheral(protocol, device_id="coordinator")
13
+ await peripheral.start() # begins advertising
14
+ # phones now discover this device, read and verify its address, connect
15
+ await peripheral.stop()
16
+
17
+ What a central reads from this peripheral is the pair the Bluetooth LE
18
+ framing chapter requires: the Device id characteristic carries this device's
19
+ ``off1...`` address, and the Identity characteristic carries the identity
20
+ assertion the core builds over that address's key. A phone verifies the
21
+ second and compares it to the first, exactly, before it surfaces the peer.
22
+ Neither value exists before MLS has been initialised, so ``start()`` refuses
23
+ to advertise without an address rather than advertise something no central
24
+ can verify.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import asyncio
30
+ import logging
31
+ import sys
32
+ import threading
33
+ import time
34
+ from typing import Any
35
+
36
+ # bless is not installed on Windows (pyproject.toml leaves it out there: it
37
+ # has no Windows backend), and this module is imported by the package's
38
+ # __init__, so a bare import here is `import offline_protocol_sdk` failing
39
+ # on Windows. The names are only reached from start(), behind
40
+ # is_available(), which answers False without them.
41
+ try:
42
+ from bless import (
43
+ BlessServer,
44
+ GATTAttributePermissions,
45
+ GATTCharacteristicProperties,
46
+ )
47
+ except ImportError: # pragma: no cover - the Windows wheel test covers it
48
+ BlessServer = None # type: ignore[assignment, misc]
49
+ GATTAttributePermissions = None # type: ignore[assignment, misc]
50
+ GATTCharacteristicProperties = None # type: ignore[assignment, misc]
51
+
52
+ from .ble_manager import (
53
+ DEVICE_ID_CHAR_UUID,
54
+ IDENTITY_CHAR_UUID,
55
+ MESSAGE_CHAR_UUID,
56
+ SERVICE_UUID,
57
+ )
58
+ from .transport_manager import TransportError, TransportManager, TransportState
59
+
60
+ logger = logging.getLogger(__name__)
61
+
62
+ # Inter-frame delay when sending multiple notification fragments (matches
63
+ # the 5 ms delay used by the M5StickC firmware in ble_mesh.h).
64
+ _INTER_FRAME_DELAY = 0.005
65
+
66
+ # How often to poll the bless delegate for subscription changes.
67
+ _PEER_MONITOR_INTERVAL = 1.0
68
+
69
+
70
+ class BlePeripheral(TransportManager):
71
+ """BLE transport — peripheral (advertiser / GATT server) role.
72
+
73
+ Advertises a GATT service with the standard Offline Protocol BLE UUIDs,
74
+ accepts connections from phones and hardware, receives incoming fragments
75
+ via GATT write requests, and sends outgoing fragments via notifications.
76
+
77
+ The peripheral passes raw fragment bytes through to the
78
+ :class:`OfflineProtocol` Rust core — the core handles reassembly and
79
+ routing internally.
80
+
81
+ Parameters
82
+ ----------
83
+ protocol:
84
+ The ``OfflineProtocol`` UniFFI instance (shared with ``BleManager``).
85
+ device_id:
86
+ A label for this peripheral, used only as the advertised local name
87
+ (truncated to ten characters). It is **not** what a central learns as
88
+ this device's id: the Device id characteristic carries the derived
89
+ ``off1...`` address, resolved from the core when ``start()`` runs.
90
+ max_connections:
91
+ Maximum number of simultaneous central connections (default 4).
92
+ """
93
+
94
+ transport_id = "ble-peripheral"
95
+ transport_name = "Bluetooth Low Energy (Peripheral)"
96
+
97
+ def __init__(
98
+ self,
99
+ protocol: Any,
100
+ device_id: str,
101
+ *,
102
+ max_connections: int = 4,
103
+ ) -> None:
104
+ super().__init__()
105
+ self._protocol = protocol
106
+ self._device_id = device_id
107
+ self._max_connections = max_connections
108
+
109
+ # What the two identity characteristics serve. Both come from the
110
+ # core at start(): the address is derived from the identity key MLS
111
+ # initialisation minted or loaded, and the assertion is signed by
112
+ # that key. Before then there is nothing to serve, and _on_read
113
+ # answers with nothing rather than with a label a central would
114
+ # refuse anyway.
115
+ self._address: str | None = None
116
+ self._identity_bytes: bytes = b""
117
+
118
+ # Server (created on start)
119
+ self._server: BlessServer | None = None
120
+
121
+ # Connected centrals: uuid -> connection timestamp
122
+ self._connected_centrals: dict[str, float] = {}
123
+
124
+ # Central UUID -> resolved user_id mapping. Populated when the
125
+ # protocol core emits a message_received event containing a
126
+ # ``sender`` field. Used to re-register the peer with its real
127
+ # user_id so the Rust BLE transport can route outgoing messages.
128
+ self._central_to_user_id: dict[str, str] = {}
129
+
130
+ # Sticky "last known" central for single-peer sender attribution —
131
+ # see _resolve_sender. Held to survive brief windows where the
132
+ # peer monitor loop has not yet populated _connected_centrals.
133
+ self._last_known_central: str | None = None
134
+
135
+ # Event loop — captured in start() for thread-safe callback scheduling
136
+ self._loop: asyncio.AbstractEventLoop | None = None
137
+
138
+ # Lock protecting state shared between bless's delegate thread
139
+ # (_on_write / _resolve_sender) and the asyncio event loop
140
+ # (_peer_monitor_loop, resolve_sender_identity, stop). Guards:
141
+ # metrics counters, _connected_centrals, _central_to_user_id,
142
+ # _last_known_central. Follow "snapshot under lock, FFI outside"
143
+ # so threading.Lock is never held across an await.
144
+ self._lock = threading.Lock()
145
+
146
+ # Metrics
147
+ self._bytes_sent: int = 0
148
+ self._bytes_received: int = 0
149
+ self._fragments_sent: int = 0
150
+ self._fragments_received: int = 0
151
+ self._is_advertising: bool = False
152
+
153
+ # Serialisation flag — prevents concurrent _drain_outgoing_fragments
154
+ self._draining: bool = False
155
+
156
+ # Background tasks
157
+ self._peer_monitor_task: asyncio.Task[None] | None = None
158
+
159
+ # -- TransportManager interface -------------------------------------------
160
+
161
+ def is_available(self) -> bool:
162
+ """Return True on platforms where bless is supported (macOS, Linux),
163
+ and only where it is installed."""
164
+ return sys.platform in ("darwin", "linux") and BlessServer is not None
165
+
166
+ def _resolve_identity(self) -> None:
167
+ """Fetch the address and the assertion this peripheral will serve.
168
+
169
+ The assertion is built by the core (``identity_assertion``): the
170
+ whole ``public_key(32) || signature(64) || signed_data`` layout,
171
+ so this binding assembles nothing and serves the same bytes for the
172
+ same key as a peripheral on any other platform. ``signed_data`` is
173
+ empty here. The chapter gives those bytes no meaning and a central
174
+ never reads them; the mobile peripherals put their mesh
175
+ advertisement there only because they have one.
176
+
177
+ Raises :class:`TransportError` when the core has no address yet,
178
+ which means MLS has not been initialised. A peripheral serving a
179
+ label in place of an address is one every conforming central
180
+ refuses, so refusing to start is the honest answer.
181
+ """
182
+ address = self._protocol.local_address()
183
+ if not address:
184
+ raise TransportError(
185
+ "BLE peripheral has no address to serve: initialise MLS "
186
+ "(ProtocolManager.start()) before starting the peripheral"
187
+ )
188
+ try:
189
+ assertion = bytes(self._protocol.identity_assertion([]))
190
+ except Exception as exc:
191
+ raise TransportError(
192
+ f"BLE peripheral could not build its identity assertion: {exc}"
193
+ ) from exc
194
+ self._address = address
195
+ self._identity_bytes = assertion
196
+
197
+ async def start(self) -> None:
198
+ """Set up the GATT server, register characteristics, and advertise."""
199
+ if self._state == TransportState.RUNNING:
200
+ raise TransportError("BLE peripheral is already running")
201
+
202
+ if not self.is_available():
203
+ raise TransportError(
204
+ f"BLE peripheral not available on {sys.platform}"
205
+ )
206
+
207
+ self._resolve_identity()
208
+
209
+ self._loop = asyncio.get_running_loop()
210
+ self._update_state(TransportState.STARTING)
211
+ self._emit_diagnostic("info", "Starting BLE peripheral", {
212
+ "device_id": self._device_id,
213
+ "address": self._address,
214
+ })
215
+
216
+ try:
217
+ # Truncate name — CoreBluetooth limits advertisement data to ~28
218
+ # bytes, and service UUIDs also consume space.
219
+ name = self._device_id[:10]
220
+ self._server = BlessServer(name=name)
221
+
222
+ await self._setup_gatt_server()
223
+
224
+ # Register read/write callbacks
225
+ self._server.read_request_func = self._on_read
226
+ self._server.write_request_func = self._on_write
227
+
228
+ # Start advertising — prioritize service UUID over local name so
229
+ # phones can discover us via SERVICE_UUID scanning.
230
+ await self._server.start(prioritize_local_name=False)
231
+ self._is_advertising = True
232
+ except Exception as exc:
233
+ self._update_state(TransportState.STOPPED)
234
+ raise TransportError(
235
+ f"BLE peripheral start failed: {exc}"
236
+ ) from exc
237
+
238
+ # Notify protocol
239
+ try:
240
+ self._protocol.ble_status_changed(is_available=True)
241
+ except Exception:
242
+ logger.debug("ble_status_changed(True) failed", exc_info=True)
243
+
244
+ self._update_state(TransportState.RUNNING)
245
+
246
+ # Start background peer monitor
247
+ self._peer_monitor_task = asyncio.ensure_future(
248
+ self._peer_monitor_loop()
249
+ )
250
+
251
+ self._emit_diagnostic("info", "BLE peripheral started — advertising")
252
+
253
+ async def stop(self) -> None:
254
+ """Stop advertising and disconnect all centrals."""
255
+ # STOPPING too: a stop() cancelled part-way (a shutdown deadline)
256
+ # leaves the transport there, and a retry that returned at once would
257
+ # leave it half torn down for good. Every step below is idempotent.
258
+ if self._state not in (
259
+ TransportState.RUNNING,
260
+ TransportState.STARTING,
261
+ TransportState.STOPPING,
262
+ ):
263
+ return
264
+
265
+ self._update_state(TransportState.STOPPING)
266
+
267
+ # Cancel background tasks
268
+ if self._peer_monitor_task is not None and not self._peer_monitor_task.done():
269
+ self._peer_monitor_task.cancel()
270
+ # Waited on, not awaited: catching CancelledError here would also
271
+ # swallow a cancel of this stop() itself, so a caller's shutdown
272
+ # deadline would be ignored and the teardown would run past it.
273
+ await asyncio.wait({self._peer_monitor_task})
274
+ self._peer_monitor_task = None
275
+
276
+ # Stop GATT server
277
+ if self._server is not None:
278
+ try:
279
+ await self._server.stop()
280
+ except Exception:
281
+ pass
282
+ self._server = None
283
+ self._is_advertising = False
284
+
285
+ # Snapshot under the lock so the delegate thread can't mutate
286
+ # these maps concurrently, then emit FFI notifications outside
287
+ # the lock (never hold threading.Lock across FFI).
288
+ with self._lock:
289
+ centrals_snapshot = list(self._connected_centrals.keys())
290
+ resolved_snapshot = dict(self._central_to_user_id)
291
+ self._connected_centrals.clear()
292
+ self._central_to_user_id.clear()
293
+ self._last_known_central = None
294
+
295
+ for central_uuid in centrals_snapshot:
296
+ try:
297
+ self._protocol.ble_peer_lost(peer_id=central_uuid)
298
+ except Exception:
299
+ logger.debug("ble_peer_lost failed for %s", central_uuid)
300
+ resolved_uid = resolved_snapshot.get(central_uuid)
301
+ if resolved_uid:
302
+ try:
303
+ self._protocol.ble_peer_lost(peer_id=resolved_uid)
304
+ except Exception:
305
+ logger.debug("ble_peer_lost failed for resolved %s", resolved_uid)
306
+
307
+ try:
308
+ self._protocol.ble_status_changed(is_available=False)
309
+ except Exception:
310
+ logger.debug("ble_status_changed(False) failed", exc_info=True)
311
+
312
+ self._update_state(TransportState.STOPPED)
313
+ self._emit_diagnostic("info", "BLE peripheral stopped")
314
+
315
+ def get_metrics(self) -> dict[str, Any]:
316
+ with self._lock:
317
+ return {
318
+ "bytes_sent": self._bytes_sent,
319
+ "bytes_received": self._bytes_received,
320
+ "fragments_sent": self._fragments_sent,
321
+ "fragments_received": self._fragments_received,
322
+ "connected_centrals": len(self._connected_centrals),
323
+ "is_advertising": self._is_advertising,
324
+ }
325
+
326
+ # -- GATT server setup ----------------------------------------------------
327
+
328
+ async def _setup_gatt_server(self) -> None:
329
+ """Add the mesh service and its characteristics."""
330
+ assert self._server is not None
331
+
332
+ await self._server.add_new_service(SERVICE_UUID)
333
+
334
+ # MESSAGE characteristic — bidirectional fragment transport
335
+ # NOTE: ``write`` (with-response) is required on macOS because the
336
+ # CoreBluetooth ``peripheralManager:didReceiveWriteRequests:``
337
+ # delegate callback is only invoked for ATT Write Requests, **not**
338
+ # ATT Write Commands (write-without-response). We keep both so
339
+ # peers that prefer write-without-response still see the property.
340
+ msg_props = (
341
+ GATTCharacteristicProperties.write
342
+ | GATTCharacteristicProperties.write_without_response
343
+ | GATTCharacteristicProperties.notify
344
+ )
345
+ msg_perms = (
346
+ GATTAttributePermissions.writeable
347
+ | GATTAttributePermissions.readable
348
+ )
349
+ await self._server.add_new_characteristic(
350
+ SERVICE_UUID,
351
+ MESSAGE_CHAR_UUID,
352
+ msg_props,
353
+ None,
354
+ msg_perms,
355
+ )
356
+
357
+ # DEVICE_ID characteristic — this device's address, as UTF-8
358
+ await self._server.add_new_characteristic(
359
+ SERVICE_UUID,
360
+ DEVICE_ID_CHAR_UUID,
361
+ GATTCharacteristicProperties.read,
362
+ bytearray(self._device_id_bytes()),
363
+ GATTAttributePermissions.readable,
364
+ )
365
+
366
+ # IDENTITY characteristic — the assertion that proves the address
367
+ await self._server.add_new_characteristic(
368
+ SERVICE_UUID,
369
+ IDENTITY_CHAR_UUID,
370
+ GATTCharacteristicProperties.read,
371
+ bytearray(self._identity_bytes),
372
+ GATTAttributePermissions.readable,
373
+ )
374
+
375
+ # -- GATT callbacks -------------------------------------------------------
376
+
377
+ @staticmethod
378
+ def _resolve_char_uuid(char_uuid: Any) -> str:
379
+ """Extract a lowercase UUID string from a characteristic or string.
380
+
381
+ ``bless`` may pass either a plain UUID string or a
382
+ ``BlessGATTCharacteristic*`` object depending on version/platform.
383
+ """
384
+ if isinstance(char_uuid, str):
385
+ return char_uuid.lower()
386
+ # BlessGATTCharacteristic objects expose a .uuid property (str)
387
+ if hasattr(char_uuid, "uuid"):
388
+ return str(char_uuid.uuid).lower()
389
+ # CoreBluetooth-backed objects — try ObjC CBCharacteristic.UUID()
390
+ if hasattr(char_uuid, "UUID"):
391
+ return str(char_uuid.UUID().UUIDString()).lower()
392
+ return str(char_uuid).lower()
393
+
394
+ def _device_id_bytes(self) -> bytes:
395
+ """The Device id characteristic's value: the address, or nothing."""
396
+ return self._address.encode("utf-8") if self._address else b""
397
+
398
+ def _on_read(self, char_uuid: Any) -> bytearray:
399
+ """Handle incoming GATT read requests."""
400
+ uuid = self._resolve_char_uuid(char_uuid)
401
+ if uuid == DEVICE_ID_CHAR_UUID.lower():
402
+ return bytearray(self._device_id_bytes())
403
+ if uuid == IDENTITY_CHAR_UUID.lower():
404
+ return bytearray(self._identity_bytes)
405
+ return bytearray(b"")
406
+
407
+ def _on_write(self, char_uuid: Any, value: Any) -> None:
408
+ """Handle incoming GATT write requests (fragments from phones).
409
+
410
+ This runs inside the bless/CoreBluetooth delegate callback. Any
411
+ unhandled exception here prevents ``respondToRequest:withResult:``
412
+ from being called, which causes CoreBluetooth to **drop the
413
+ connection**. Therefore the entire body is wrapped in try/except.
414
+ """
415
+ try:
416
+ resolved = self._resolve_char_uuid(char_uuid)
417
+ logger.debug(
418
+ "_on_write called: uuid=%s, value_type=%s, value_len=%d",
419
+ resolved, type(value).__name__, len(value) if value else 0,
420
+ )
421
+ if resolved != MESSAGE_CHAR_UUID.lower():
422
+ logger.debug("_on_write: ignoring write to %s", resolved)
423
+ return
424
+
425
+ fragment = bytes(value)
426
+ logger.debug(
427
+ "_on_write: %d bytes, sender=%s",
428
+ len(fragment), self._resolve_sender(),
429
+ )
430
+ with self._lock:
431
+ self._bytes_received += len(fragment)
432
+ self._fragments_received += 1
433
+
434
+ sender_id = self._resolve_sender()
435
+
436
+ self._protocol.ble_fragment_received(
437
+ sender_id=sender_id, fragment=list(fragment)
438
+ )
439
+ logger.debug("_on_write: fragment fed to protocol OK")
440
+ except Exception as exc:
441
+ logger.exception("_on_write failed: %s", exc)
442
+
443
+ def _resolve_sender(self) -> str:
444
+ """Best-effort identification of the writing central.
445
+
446
+ Called from the bless delegate thread, so state reads/writes must
447
+ take `self._lock` — the asyncio `_peer_monitor_loop` mutates
448
+ `_connected_centrals` / `_last_known_central` from a different
449
+ thread. Returns a stable sender ID so the Rust core can group
450
+ fragments from the same source.
451
+ """
452
+ with self._lock:
453
+ count = len(self._connected_centrals)
454
+ if count == 1:
455
+ central = next(iter(self._connected_centrals))
456
+ self._last_known_central = central
457
+ return central
458
+ if count > 1:
459
+ return "ble-peer"
460
+ # No centrals currently tracked — use last known if available.
461
+ return self._last_known_central or "ble-peer"
462
+
463
+ def resolve_sender_identity(self, sender_user_id: str) -> None:
464
+ """Associate a sender's user_id with the currently connected central.
465
+
466
+ Called by ``ProtocolManager`` when a reassembled message reveals the
467
+ sender's real user_id (from the message ``sender`` field). The BLE
468
+ central (scanner) path learns the peer's user_id by reading the
469
+ DEVICE_ID characteristic; the peripheral has no equivalent mechanism,
470
+ so it relies on the first received message to learn the mapping.
471
+
472
+ Once the mapping is established, the peer is re-registered with the
473
+ Rust core under its real user_id so that ``send_message(user_id, ...)``
474
+ can route back through the BLE peripheral.
475
+ """
476
+ with self._lock:
477
+ count = len(self._connected_centrals)
478
+ if count == 0:
479
+ return
480
+ if count != 1:
481
+ # With multiple centrals we can't attribute unambiguously.
482
+ logger.debug(
483
+ "resolve_sender_identity: %d centrals connected, skipping",
484
+ count,
485
+ )
486
+ return
487
+ central_uuid = next(iter(self._connected_centrals))
488
+ # Avoid redundant re-registration.
489
+ if self._central_to_user_id.get(central_uuid) == sender_user_id:
490
+ return
491
+ self._central_to_user_id[central_uuid] = sender_user_id
492
+
493
+ logger.info(
494
+ "Resolved central %s -> user_id %s — re-registering peer",
495
+ central_uuid, sender_user_id,
496
+ )
497
+
498
+ try:
499
+ self._protocol.ble_peer_discovered(
500
+ peer_id=sender_user_id, rssi=-50
501
+ )
502
+ except Exception:
503
+ logger.debug(
504
+ "ble_peer_discovered failed for resolved user_id %s",
505
+ sender_user_id,
506
+ )
507
+
508
+ # -- outgoing fragment handling -------------------------------------------
509
+
510
+ def on_fragments_available(self) -> None:
511
+ """Called by ``BleTransportCallback.on_fragments_available()``.
512
+
513
+ Drains outgoing fragments from the protocol core and sends them
514
+ to subscribed centrals via GATT notifications.
515
+
516
+ This is invoked from a Rust UniFFI callback thread, so we must use
517
+ ``call_soon_threadsafe`` to schedule work on the asyncio event loop.
518
+ """
519
+ loop = self._loop
520
+ if loop is not None and not loop.is_closed() and loop.is_running():
521
+ loop.call_soon_threadsafe(asyncio.ensure_future, self._drain_outgoing_fragments())
522
+
523
+ async def _drain_outgoing_fragments(self) -> None:
524
+ """Send all queued outgoing fragments as notifications."""
525
+ if self._server is None:
526
+ return
527
+ if self._draining:
528
+ return
529
+ self._draining = True
530
+ try:
531
+ await self._drain_outgoing_fragments_inner()
532
+ finally:
533
+ self._draining = False
534
+
535
+ async def _drain_outgoing_fragments_inner(self) -> None:
536
+ if self._server is None:
537
+ return
538
+
539
+ while True:
540
+ try:
541
+ frag = self._protocol.ble_get_next_fragment()
542
+ except (AttributeError, ReferenceError) as exc:
543
+ logger.error("Protocol instance invalid: %s", exc)
544
+ break
545
+ except Exception as exc:
546
+ logger.warning("Unexpected error getting next fragment: %s", exc)
547
+ break
548
+ if frag is None:
549
+ break
550
+
551
+ data = bytes(frag.data)
552
+ recipient = getattr(frag, 'recipient_id', None)
553
+ logger.info(
554
+ "OUTGOING fragment: %d bytes, recipient=%s",
555
+ len(data), recipient,
556
+ )
557
+
558
+ char = self._server.get_characteristic(MESSAGE_CHAR_UUID)
559
+ if char is not None:
560
+ char.value = data
561
+ self._server.update_value(SERVICE_UUID, MESSAGE_CHAR_UUID)
562
+ with self._lock:
563
+ self._bytes_sent += len(data)
564
+ self._fragments_sent += 1
565
+
566
+ # Inter-frame delay to avoid overwhelming the BLE stack
567
+ await asyncio.sleep(_INTER_FRAME_DELAY)
568
+
569
+ # Return fragment to pool regardless of send outcome
570
+ try:
571
+ self._protocol.ble_return_fragment()
572
+ except Exception:
573
+ logger.debug("ble_return_fragment failed", exc_info=True)
574
+
575
+ # -- background tasks -----------------------------------------------------
576
+
577
+ async def _peer_monitor_loop(self) -> None:
578
+ """Poll the bless delegate's subscription dict for changes.
579
+
580
+ When a central subscribes to the MESSAGE characteristic we treat it
581
+ as a peer connection; when it unsubscribes, a disconnection.
582
+ """
583
+ known: set[str] = set()
584
+ try:
585
+ while True:
586
+ await asyncio.sleep(_PEER_MONITOR_INTERVAL)
587
+
588
+ if self._server is None:
589
+ continue
590
+
591
+ try:
592
+ delegate = self._server.peripheral_manager_delegate
593
+ # NOTE: _central_subscriptions is a bless-internal dict.
594
+ # Validated against bless 0.3.x. If this attribute is
595
+ # missing after a bless upgrade, the except below logs a
596
+ # warning and the monitor degrades gracefully (no peer
597
+ # tracking, but data transfer still works).
598
+ current = set(delegate._central_subscriptions.keys())
599
+ except (AttributeError, TypeError):
600
+ logger.debug(
601
+ "Cannot read bless _central_subscriptions — "
602
+ "peer monitoring disabled (bless API may have changed)"
603
+ )
604
+ continue
605
+
606
+ # Classify under the lock (the delegate thread races us on
607
+ # _connected_centrals / _central_to_user_id). FFI + diagnostic
608
+ # notifications happen afterward, outside the lock.
609
+ now = time.monotonic()
610
+ added: list[str] = []
611
+ rejected: list[str] = []
612
+ removed: list[tuple[str, str | None]] = []
613
+
614
+ with self._lock:
615
+ capacity = self._max_connections
616
+ for central_uuid in current - known:
617
+ if len(self._connected_centrals) >= capacity:
618
+ rejected.append(central_uuid)
619
+ continue
620
+ self._connected_centrals[central_uuid] = now
621
+ added.append(central_uuid)
622
+
623
+ for central_uuid in known - current:
624
+ self._connected_centrals.pop(central_uuid, None)
625
+ resolved_uid = self._central_to_user_id.pop(
626
+ central_uuid, None
627
+ )
628
+ removed.append((central_uuid, resolved_uid))
629
+
630
+ for central_uuid in rejected:
631
+ self._emit_diagnostic(
632
+ "warning",
633
+ f"Max connections ({self._max_connections}) reached, "
634
+ f"ignoring {central_uuid}",
635
+ )
636
+
637
+ for central_uuid in added:
638
+ try:
639
+ self._protocol.ble_peer_discovered(
640
+ peer_id=central_uuid, rssi=-50
641
+ )
642
+ except Exception:
643
+ logger.debug("ble_peer_discovered failed for %s", central_uuid)
644
+ self._emit_diagnostic(
645
+ "info", "Central connected", {"central": central_uuid}
646
+ )
647
+
648
+ for central_uuid, resolved_uid in removed:
649
+ try:
650
+ self._protocol.ble_peer_lost(peer_id=central_uuid)
651
+ except Exception:
652
+ logger.debug("ble_peer_lost failed for %s", central_uuid)
653
+ if resolved_uid:
654
+ try:
655
+ self._protocol.ble_peer_lost(peer_id=resolved_uid)
656
+ except Exception:
657
+ logger.debug(
658
+ "ble_peer_lost failed for resolved %s", resolved_uid
659
+ )
660
+ self._emit_diagnostic(
661
+ "info", "Central disconnected", {"central": central_uuid}
662
+ )
663
+
664
+ known = current.copy()
665
+
666
+ # Update cached advertising state
667
+ try:
668
+ self._is_advertising = self._server.peripheral_manager_delegate.is_advertising()
669
+ except Exception:
670
+ pass
671
+
672
+ except asyncio.CancelledError:
673
+ return