1""" 2 Copyright (c) 2024, The OpenThread Authors. 3 All rights reserved. 4 5 Redistribution and use in source and binary forms, with or without 6 modification, are permitted provided that the following conditions are met: 7 1. Redistributions of source code must retain the above copyright 8 notice, this list of conditions and the following disclaimer. 9 2. Redistributions in binary form must reproduce the above copyright 10 notice, this list of conditions and the following disclaimer in the 11 documentation and/or other materials provided with the distribution. 12 3. Neither the name of the copyright holder nor the 13 names of its contributors may be used to endorse or promote products 14 derived from this software without specific prior written permission. 15 16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 20 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 POSSIBILITY OF SUCH DAMAGE. 27""" 28 29from itertools import count, takewhile 30from typing import Iterator, Union 31import logging 32import time 33from asyncio import sleep 34 35from bleak import BleakClient 36from bleak.backends.device import BLEDevice 37from bleak.backends.characteristic import BleakGATTCharacteristic 38 39logger = logging.getLogger(__name__) 40 41 42class BleStream: 43 44 def __init__(self, client, service_uuid, tx_char_uuid, rx_char_uuid): 45 self.__receive_buffer = b'' 46 self.__last_recv_time = None 47 self.client = client 48 self.service_uuid = service_uuid 49 self.tx_char_uuid = tx_char_uuid 50 self.rx_char_uuid = rx_char_uuid 51 52 async def __aenter__(self): 53 return self 54 55 async def __aexit__(self, exc_type, exc_value, traceback): 56 if self.client.is_connected: 57 await self.client.disconnect() 58 59 def __handle_rx(self, _: BleakGATTCharacteristic, data: bytearray): 60 logger.debug(f'received {len(data)} bytes') 61 self.__receive_buffer += data 62 self.__last_recv_time = time.time() 63 64 @staticmethod 65 def __sliced(data: bytes, n: int) -> Iterator[bytes]: 66 return takewhile(len, (data[i:i + n] for i in count(0, n))) 67 68 @classmethod 69 async def create(cls, address_or_ble_device: Union[BLEDevice, str], service_uuid, tx_char_uuid, rx_char_uuid): 70 client = BleakClient(address_or_ble_device) 71 await client.connect() 72 self = cls(client, service_uuid, tx_char_uuid, rx_char_uuid) 73 await client.start_notify(self.tx_char_uuid, self.__handle_rx) 74 return self 75 76 async def send(self, data): 77 logger.debug(f'sending {data}') 78 services = self.client.services.get_service(self.service_uuid) 79 rx_char = services.get_characteristic(self.rx_char_uuid) 80 for s in BleStream.__sliced(data, rx_char.max_write_without_response_size): 81 await self.client.write_gatt_char(rx_char, s) 82 return len(data) 83 84 async def recv(self, bufsize, recv_timeout=0.2): 85 if not self.__receive_buffer: 86 return b'' 87 88 while time.time() - self.__last_recv_time <= recv_timeout: 89 await sleep(0.1) 90 91 message = self.__receive_buffer[:bufsize] 92 self.__receive_buffer = self.__receive_buffer[bufsize:] 93 logger.debug(f'retrieved {message}') 94 return message 95 96 async def disconnect(self): 97 if self.client.is_connected: 98 await self.client.disconnect() 99