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
31import logging
32import time
33from asyncio import sleep
34
35from bleak import BleakClient
36from bleak.backends.characteristic import BleakGATTCharacteristic
37
38logger = logging.getLogger(__name__)
39
40
41class BleStream:
42
43    def __init__(self, client, service_uuid, tx_char_uuid, rx_char_uuid):
44        self.__receive_buffer = b''
45        self.__last_recv_time = None
46        self.client = client
47        self.service_uuid = service_uuid
48        self.tx_char_uuid = tx_char_uuid
49        self.rx_char_uuid = rx_char_uuid
50
51    async def __aenter__(self):
52        return self
53
54    async def __aexit__(self, exc_type, exc_value, traceback):
55        if self.client.is_connected:
56            await self.client.disconnect()
57
58    def __handle_rx(self, _: BleakGATTCharacteristic, data: bytearray):
59        logger.debug(f'received {len(data)} bytes')
60        self.__receive_buffer += data
61        self.__last_recv_time = time.time()
62
63    @staticmethod
64    def __sliced(data: bytes, n: int) -> Iterator[bytes]:
65        return takewhile(len, (data[i:i + n] for i in count(0, n)))
66
67    @classmethod
68    async def create(cls, address, service_uuid, tx_char_uuid, rx_char_uuid):
69        client = BleakClient(address)
70        await client.connect()
71        self = cls(client, service_uuid, tx_char_uuid, rx_char_uuid)
72        await client.start_notify(self.tx_char_uuid, self.__handle_rx)
73        return self
74
75    async def send(self, data):
76        logger.debug(f'sending {data}')
77        services = self.client.services.get_service(self.service_uuid)
78        rx_char = services.get_characteristic(self.rx_char_uuid)
79        for s in BleStream.__sliced(data, rx_char.max_write_without_response_size):
80            await self.client.write_gatt_char(rx_char, s)
81        return len(data)
82
83    async def recv(self, bufsize, recv_timeout=0.2):
84        if not self.__receive_buffer:
85            return b''
86
87        while time.time() - self.__last_recv_time <= recv_timeout:
88            await sleep(0.1)
89
90        message = self.__receive_buffer[:bufsize]
91        self.__receive_buffer = self.__receive_buffer[bufsize:]
92        logger.debug(f'retrieved {message}')
93        return message
94
95    async def disconnect(self):
96        if self.client.is_connected:
97            await self.client.disconnect()
98