|
| 1 | +import asyncio |
| 2 | +from contextlib import asynccontextmanager |
| 3 | +from dataclasses import dataclass |
| 4 | +from functools import partial |
| 5 | + |
| 6 | +from anyio.abc import ObjectStream |
| 7 | +from bleak import BleakClient, BleakGATTCharacteristic |
| 8 | +from bleak.exc import BleakError |
| 9 | + |
| 10 | +from jumpstarter.driver import Driver, export, exportstream |
| 11 | + |
| 12 | + |
| 13 | +def _ble_notify_handler(_sender: BleakGATTCharacteristic, data: bytearray, data_queue: asyncio.Queue): |
| 14 | + """Notification handler that puts received data into a queue.""" |
| 15 | + try: |
| 16 | + data_queue.put_nowait(data) |
| 17 | + except asyncio.QueueFull: |
| 18 | + print("Warning: Data queue is full, dropping message") |
| 19 | + |
| 20 | + |
| 21 | +class AsyncBleConfig(): |
| 22 | + def __init__( |
| 23 | + self, |
| 24 | + address: str, |
| 25 | + service_uuid: str, |
| 26 | + write_char_uuid: str, |
| 27 | + notify_char_uuid: str, |
| 28 | + ): |
| 29 | + self.address = address |
| 30 | + self.service_uuid = service_uuid |
| 31 | + self.write_char_uuid = write_char_uuid |
| 32 | + self.notify_char_uuid = notify_char_uuid |
| 33 | + |
| 34 | + |
| 35 | +@dataclass(kw_only=True) |
| 36 | +class AsyncBleWrapper(ObjectStream): |
| 37 | + client: BleakClient |
| 38 | + config: AsyncBleConfig |
| 39 | + notify_queue: asyncio.Queue |
| 40 | + |
| 41 | + async def send(self, data: bytes): |
| 42 | + await self.client.write_gatt_char(self.config.write_char_uuid, data) |
| 43 | + |
| 44 | + async def receive(self): |
| 45 | + return bytes(await self.notify_queue.get()) |
| 46 | + |
| 47 | + async def send_eof(self): |
| 48 | + # BLE characteristics don't have an explicit EOF mechanism |
| 49 | + pass |
| 50 | + |
| 51 | + async def aclose(self): |
| 52 | + await self.client.disconnect() |
| 53 | + |
| 54 | + |
| 55 | +@dataclass(kw_only=True) |
| 56 | +class Ble(Driver): |
| 57 | + """Bluetooth Low Energy (BLE) driver for Jumpstarter""" |
| 58 | + |
| 59 | + address: str |
| 60 | + service_uuid: str |
| 61 | + write_char_uuid: str |
| 62 | + notify_char_uuid: str |
| 63 | + |
| 64 | + def __post_init__(self): |
| 65 | + if hasattr(super(), "__post_init__"): |
| 66 | + super().__post_init__() |
| 67 | + |
| 68 | + @classmethod |
| 69 | + def client(cls) -> str: |
| 70 | + return "jumpstarter_driver_ble.client.BleClient" |
| 71 | + |
| 72 | + @export |
| 73 | + async def info(self) -> str: |
| 74 | + return f"""Ble Driver connected to |
| 75 | +- Address: {self.address} |
| 76 | +- Service UUID: {self.service_uuid} |
| 77 | +- Write Char UUID: {self.write_char_uuid} |
| 78 | +- Notify Char UUID: {self.notify_char_uuid}""" |
| 79 | + |
| 80 | + async def _check_ble_characteristics(self, client: BleakClient): |
| 81 | + """Check if the required BLE service and characteristics are available.""" |
| 82 | + svcs = list(client.services) |
| 83 | + for svc in svcs: |
| 84 | + if svc.uuid == self.service_uuid: |
| 85 | + chars_uuid = [char.uuid for char in svc.characteristics] |
| 86 | + if self.write_char_uuid not in chars_uuid: |
| 87 | + raise BleakError( |
| 88 | + f"Write characteristic UUID {self.write_char_uuid} not found on device.") |
| 89 | + if self.notify_char_uuid not in chars_uuid: |
| 90 | + raise BleakError( |
| 91 | + f"Notify characteristic UUID {self.notify_char_uuid} not found on device.") |
| 92 | + return |
| 93 | + |
| 94 | + raise BleakError( |
| 95 | + f"Service UUID {self.service_uuid} not found on device.") |
| 96 | + |
| 97 | + @exportstream |
| 98 | + @asynccontextmanager |
| 99 | + async def connect(self): |
| 100 | + self.logger.info( |
| 101 | + "Connecting to BLE device at Address: %s", self.address) |
| 102 | + async with BleakClient(self.address) as client: |
| 103 | + try: |
| 104 | + if client.is_connected: |
| 105 | + notify_queue = asyncio.Queue(maxsize=1000) |
| 106 | + self.logger.info( |
| 107 | + "Connected to BLE device at Address: %s", self.address) |
| 108 | + |
| 109 | + # check if required characteristics are available |
| 110 | + await self._check_ble_characteristics(client) |
| 111 | + |
| 112 | + # register notification handler if notify_char_uuid is provided |
| 113 | + if self.notify_char_uuid: |
| 114 | + notify_handler = partial( |
| 115 | + _ble_notify_handler, data_queue=notify_queue) |
| 116 | + await client.start_notify(self.notify_char_uuid, notify_handler) |
| 117 | + self.logger.info( |
| 118 | + "Setting up notification handler for characteristic UUID: %s", self.notify_char_uuid) |
| 119 | + |
| 120 | + async with AsyncBleWrapper( |
| 121 | + client=client, |
| 122 | + notify_queue=notify_queue, |
| 123 | + config=AsyncBleConfig( |
| 124 | + address=self.address, |
| 125 | + service_uuid=self.service_uuid, |
| 126 | + write_char_uuid=self.write_char_uuid, |
| 127 | + # read_char_uuid=self.read_char_uuid, |
| 128 | + notify_char_uuid=self.notify_char_uuid, |
| 129 | + ), |
| 130 | + ) as stream: |
| 131 | + yield stream |
| 132 | + self.logger.info( |
| 133 | + "Disconnecting from BLE device at Address: %s", self.address) |
| 134 | + |
| 135 | + else: |
| 136 | + self.logger.error( |
| 137 | + "Failed to connect to BLE device at Address: %s", self.address) |
| 138 | + raise BleakError( |
| 139 | + f"Failed to connect to BLE device at Address: {self.address}") |
| 140 | + |
| 141 | + except BleakError as e: |
| 142 | + self.logger.error("Failed to connect to BLE device: %s", e) |
| 143 | + raise |
0 commit comments