Async BLE interface implementing the SerialInterface protocol. Adapts Bleak BLE GATT operations to the same async interface that PySerialAdapter and FbuildSerialAdapter provide.
| 27 | |
| 28 | |
| 29 | class BleInterface: |
| 30 | """Async BLE interface implementing the SerialInterface protocol. |
| 31 | |
| 32 | Adapts Bleak BLE GATT operations to the same async interface that |
| 33 | PySerialAdapter and FbuildSerialAdapter provide. |
| 34 | """ |
| 35 | |
| 36 | def __init__( |
| 37 | self, |
| 38 | device_name: str = "FastLED-C6", |
| 39 | scan_timeout: float = 15.0, |
| 40 | ) -> None: |
| 41 | self._device_name = device_name |
| 42 | self._scan_timeout = scan_timeout |
| 43 | self._client: BleakClient | None = None |
| 44 | self._rx_queue: asyncio.Queue[str] = asyncio.Queue() |
| 45 | |
| 46 | def _notification_handler( |
| 47 | self, _sender: BleakGATTCharacteristic, data: bytearray |
| 48 | ) -> None: |
| 49 | """Callback invoked by Bleak when device sends a NOTIFY on TX char.""" |
| 50 | text = data.decode("utf-8", errors="replace").strip() |
| 51 | if text: |
| 52 | self._rx_queue.put_nowait(text) |
| 53 | |
| 54 | async def connect(self) -> None: |
| 55 | """Scan for device by name, connect, and subscribe to TX notifications.""" |
| 56 | print(f" [BLE] Scanning for '{self._device_name}'...") |
| 57 | device = await BleakScanner.find_device_by_name( |
| 58 | self._device_name, timeout=self._scan_timeout |
| 59 | ) |
| 60 | if device is None: |
| 61 | raise RuntimeError( |
| 62 | f"BLE device '{self._device_name}' not found within {self._scan_timeout}s" |
| 63 | ) |
| 64 | print(f" [BLE] Found device: {device.name} ({device.address})") |
| 65 | |
| 66 | client = BleakClient(device, timeout=30.0) |
| 67 | await client.connect() |
| 68 | self._client = client |
| 69 | print(f" [BLE] Connected to {device.address}") |
| 70 | |
| 71 | # Subscribe to NOTIFY on TX characteristic |
| 72 | await client.start_notify(BLE_CHAR_TX_UUID, self._notification_handler) |
| 73 | print(f" [BLE] Subscribed to TX notifications") |
| 74 | |
| 75 | async def close(self) -> None: |
| 76 | """Disconnect from BLE device.""" |
| 77 | if self._client and self._client.is_connected: |
| 78 | try: |
| 79 | await self._client.stop_notify(BLE_CHAR_TX_UUID) |
| 80 | except KeyboardInterrupt: |
| 81 | import _thread |
| 82 | |
| 83 | _thread.interrupt_main() |
| 84 | raise |
| 85 | except Exception: |
| 86 | pass |
no outgoing calls
no test coverage detected