File: common.py

package info (click to toggle)
python-bumble 0.0.225-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 9,464 kB
  • sloc: python: 75,258; java: 3,782; javascript: 823; xml: 203; sh: 172; makefile: 8
file content (505 lines) | stat: -rw-r--r-- 16,885 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# Copyright 2021-2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from __future__ import annotations

import asyncio
import contextlib
import io
import logging
import struct
from collections.abc import Awaitable, Callable
from typing import Any, Protocol

from bumble import core, hci
from bumble.colors import color
from bumble.snoop import Snooper

# -----------------------------------------------------------------------------
# Logging
# -----------------------------------------------------------------------------
logger = logging.getLogger(__name__)

# -----------------------------------------------------------------------------
# Information needed to parse HCI packets with a generic parser:
# For each packet type, the info represents:
# (length-size, length-offset, unpack-type)
HCI_PACKET_INFO: dict[int, tuple[int, int, str]] = {
    hci.HCI_COMMAND_PACKET: (1, 2, 'B'),
    hci.HCI_ACL_DATA_PACKET: (2, 2, 'H'),
    hci.HCI_SYNCHRONOUS_DATA_PACKET: (1, 2, 'B'),
    hci.HCI_EVENT_PACKET: (1, 1, 'B'),
    hci.HCI_ISO_DATA_PACKET: (2, 2, 'H'),
}


# -----------------------------------------------------------------------------
# Errors
# -----------------------------------------------------------------------------
class TransportLostError(core.BaseBumbleError, RuntimeError):
    """The Transport has been lost/disconnected."""


class TransportInitError(core.BaseBumbleError, RuntimeError):
    """Error raised when the transport cannot be initialized."""


class TransportSpecError(core.BaseBumbleError, ValueError):
    """Error raised when the transport spec is invalid."""


# -----------------------------------------------------------------------------
# Typing Protocols
# -----------------------------------------------------------------------------
class TransportSink(Protocol):
    def on_packet(self, packet: bytes) -> None: ...


class TransportSource(Protocol):
    terminated: asyncio.Future[None]

    def set_packet_sink(self, sink: TransportSink) -> None: ...


# -----------------------------------------------------------------------------
class PacketPump:
    """
    Pump HCI packets from a reader to a sink.
    """

    def __init__(self, reader: AsyncPacketReader, sink: TransportSink) -> None:
        self.reader = reader
        self.sink = sink

    async def run(self) -> None:
        while True:
            try:
                # Deliver the packet to the sink
                self.sink.on_packet(await self.reader.next_packet())
            except Exception:
                logger.exception('!!!')


# -----------------------------------------------------------------------------
class PacketParser:
    """
    In-line parser that accepts data and emits 'on_packet' when a full packet has been
    parsed.
    """

    # pylint: disable=attribute-defined-outside-init

    NEED_TYPE = 0
    NEED_LENGTH = 1
    NEED_BODY = 2

    sink: TransportSink | None
    extended_packet_info: dict[int, tuple[int, int, str]]
    packet_info: tuple[int, int, str] | None = None

    def __init__(self, sink: TransportSink | None = None) -> None:
        self.sink = sink
        self.extended_packet_info = {}
        self.reset()

    def reset(self) -> None:
        self.state = PacketParser.NEED_TYPE
        self.bytes_needed = 1
        self.packet = bytearray()
        self.packet_info = None

    def feed_data(self, data: bytes) -> None:
        data_offset = 0
        data_left = len(data)
        while data_left and self.bytes_needed:
            consumed = min(self.bytes_needed, data_left)
            self.packet.extend(data[data_offset : data_offset + consumed])
            data_offset += consumed
            data_left -= consumed
            self.bytes_needed -= consumed

            if self.bytes_needed == 0:
                if self.state == PacketParser.NEED_TYPE:
                    packet_type = self.packet[0]
                    self.packet_info = HCI_PACKET_INFO.get(
                        packet_type
                    ) or self.extended_packet_info.get(packet_type)
                    if self.packet_info is None:
                        self.reset()
                        raise core.InvalidPacketError(
                            f'invalid packet type {packet_type}'
                        )
                    self.state = PacketParser.NEED_LENGTH
                    self.bytes_needed = self.packet_info[0] + self.packet_info[1]
                elif self.state == PacketParser.NEED_LENGTH:
                    assert self.packet_info is not None
                    body_length = struct.unpack_from(
                        self.packet_info[2], self.packet, 1 + self.packet_info[1]
                    )[0]
                    self.bytes_needed = body_length
                    self.state = PacketParser.NEED_BODY

                # Emit a packet if one is complete
                if self.state == PacketParser.NEED_BODY and not self.bytes_needed:
                    if self.sink:
                        try:
                            self.sink.on_packet(bytes(self.packet))
                        except Exception:
                            logger.exception(color('!!! Exception in on_packet', 'red'))
                    self.reset()

    def set_packet_sink(self, sink: TransportSink) -> None:
        self.sink = sink


# -----------------------------------------------------------------------------
class PacketReader:
    """
    Reader that reads HCI packets from a sync source.
    """

    def __init__(self, source: io.BufferedReader) -> None:
        self.source = source
        self.at_end = False

    def next_packet(self) -> bytes | None:
        # Get the packet type
        packet_type = self.source.read(1)
        if len(packet_type) != 1:
            self.at_end = True
            return None

        # Get the packet info based on its type
        packet_info = HCI_PACKET_INFO.get(packet_type[0])
        if packet_info is None:
            raise core.InvalidPacketError(f'invalid packet type {packet_type[0]} found')

        # Read the header (that includes the length)
        header_size = packet_info[0] + packet_info[1]
        header = self.source.read(header_size)
        if len(header) != header_size:
            raise core.InvalidPacketError('packet too short')

        # Read the body
        body_length = struct.unpack_from(packet_info[2], header, packet_info[1])[0]
        body = self.source.read(body_length)
        if len(body) != body_length:
            raise core.InvalidPacketError('packet too short')

        return packet_type + header + body


# -----------------------------------------------------------------------------
class AsyncPacketReader:
    """
    Reader that reads HCI packets from an async source.
    """

    def __init__(self, source: asyncio.StreamReader) -> None:
        self.source = source

    async def next_packet(self) -> bytes:
        # Get the packet type
        packet_type = await self.source.readexactly(1)

        # Get the packet info based on its type
        packet_info = HCI_PACKET_INFO.get(packet_type[0])
        if packet_info is None:
            raise core.InvalidPacketError(f'invalid packet type {packet_type[0]} found')

        # Read the header (that includes the length)
        header_size = packet_info[0] + packet_info[1]
        header = await self.source.readexactly(header_size)

        # Read the body
        body_length = struct.unpack_from(packet_info[2], header, packet_info[1])[0]
        body = await self.source.readexactly(body_length)

        return packet_type + header + body


# -----------------------------------------------------------------------------
class AsyncPipeSink:
    """
    Sink that forwards packets asynchronously to another sink.
    """

    def __init__(self, sink: TransportSink) -> None:
        self.sink = sink
        self.loop = asyncio.get_running_loop()

    def on_packet(self, packet: bytes) -> None:
        self.loop.call_soon(self.sink.on_packet, packet)


# -----------------------------------------------------------------------------
class BaseSource:
    """
    Base class designed to be subclassed by transport-specific source classes
    """

    terminated: asyncio.Future[None]
    sink: TransportSink | None

    def __init__(self) -> None:
        self.terminated = asyncio.get_running_loop().create_future()
        self.sink = None

    def set_packet_sink(self, sink: TransportSink) -> None:
        self.sink = sink

    def on_transport_lost(self) -> None:
        if not self.terminated.done():
            self.terminated.set_result(None)

        if self.sink:
            if hasattr(self.sink, 'on_transport_lost'):
                self.sink.on_transport_lost()

    async def wait_for_termination(self) -> None:
        """
        Convenience method for backward compatibility. Prefer using the `terminated`
        attribute instead.
        """
        return await self.terminated

    def close(self) -> None:
        pass


# -----------------------------------------------------------------------------
class ParserSource(BaseSource):
    """
    Base class for sources that use an HCI parser.
    """

    parser: PacketParser

    def __init__(self) -> None:
        super().__init__()
        self.parser = PacketParser()

    def set_packet_sink(self, sink: TransportSink) -> None:
        super().set_packet_sink(sink)
        self.parser.set_packet_sink(sink)


# -----------------------------------------------------------------------------
class StreamPacketSource(asyncio.Protocol, ParserSource):
    def data_received(self, data: bytes) -> None:
        try:
            self.parser.feed_data(data)
        except core.InvalidPacketError:
            logger.warning("invalid packet, ignoring data")


# -----------------------------------------------------------------------------
class StreamPacketSink:
    def __init__(self, transport: asyncio.WriteTransport) -> None:
        self.transport = transport

    def on_packet(self, packet: bytes) -> None:
        self.transport.write(packet)

    def close(self) -> None:
        self.transport.close()


# -----------------------------------------------------------------------------
class Transport:
    """
    Base class for all transports.

    A Transport represents a source and a sink together.
    An instance must be closed by calling close() when no longer used. Instances
    implement the ContextManager protocol so that they may be used in a `async with`
    statement.
    An instance is iterable. The iterator yields, in order, its source and sink, so
    that it may be used with a convenient call syntax like:

    async with create_transport() as (source, sink):
        ...
    """

    def __init__(self, source: TransportSource, sink: TransportSink) -> None:
        self.source = source
        self.sink = sink

    async def __aenter__(self):
        return self

    async def __aexit__(self, *args):
        await self.close()

    def __iter__(self):
        return iter((self.source, self.sink))

    async def close(self) -> None:
        if hasattr(self.source, 'close'):
            self.source.close()
        if hasattr(self.sink, 'close'):
            self.sink.close()


# -----------------------------------------------------------------------------
class PumpedPacketSource(ParserSource):
    pump_task: asyncio.Task[None] | None

    def __init__(self, receive) -> None:
        super().__init__()
        self.receive_function = receive
        self.pump_task = None

    def start(self) -> None:
        async def pump_packets() -> None:
            while True:
                try:
                    packet = await self.receive_function()
                    self.parser.feed_data(packet)
                except asyncio.CancelledError:
                    logger.debug('source pump task done')
                    if not self.terminated.done():
                        self.terminated.set_result(None)
                    break
                except Exception as error:
                    logger.exception('exception while waiting for packet')
                    if not self.terminated.done():
                        self.terminated.set_exception(error)
                    break

        self.pump_task = asyncio.create_task(pump_packets())

    def close(self) -> None:
        if self.pump_task:
            self.pump_task.cancel()


# -----------------------------------------------------------------------------
class PumpedPacketSink:
    pump_task: asyncio.Task[None] | None

    def __init__(self, send: Callable[[bytes], Awaitable[Any]]):
        self.send_function = send
        self.packet_queue = asyncio.Queue[bytes]()
        self.pump_task = None

    def on_packet(self, packet: bytes) -> None:
        self.packet_queue.put_nowait(packet)

    def start(self) -> None:
        async def pump_packets():
            while True:
                try:
                    packet = await self.packet_queue.get()
                    await self.send_function(packet)
                except asyncio.CancelledError:
                    logger.debug('sink pump task done')
                    break
                except Exception:
                    logger.exception('exception while sending packet')
                    break

        self.pump_task = asyncio.create_task(pump_packets())

    def close(self):
        if self.pump_task:
            self.pump_task.cancel()


# -----------------------------------------------------------------------------
class PumpedTransport(Transport):
    source: PumpedPacketSource
    sink: PumpedPacketSink

    def __init__(
        self,
        source: PumpedPacketSource,
        sink: PumpedPacketSink,
    ) -> None:
        super().__init__(source, sink)

    def start(self) -> None:
        self.source.start()
        self.sink.start()


# -----------------------------------------------------------------------------
class SnoopingTransport(Transport):
    """Transport wrapper that snoops on packets to/from a wrapped transport."""

    @staticmethod
    def create_with(
        transport: Transport, snooper: contextlib.AbstractContextManager[Snooper]
    ) -> SnoopingTransport:
        """
        Create an instance given a snooper that works as as context manager.

        The returned instance will exit the snooper context when it is closed.
        """
        with contextlib.ExitStack() as exit_stack:
            return SnoopingTransport(
                transport, exit_stack.enter_context(snooper), exit_stack.pop_all().close
            )
        raise core.UnreachableError()  # Satisfy the type checker

    class Source:
        sink: TransportSink

        @property
        def metadata(self) -> dict[str, Any]:
            return getattr(self.source, 'metadata', {})

        def __init__(self, source: TransportSource, snooper: Snooper):
            self.source = source
            self.snooper = snooper
            self.terminated = source.terminated

        def set_packet_sink(self, sink: TransportSink) -> None:
            self.sink = sink
            self.source.set_packet_sink(self)

        def on_packet(self, packet: bytes) -> None:
            self.snooper.snoop(packet, Snooper.Direction.CONTROLLER_TO_HOST)
            if self.sink:
                self.sink.on_packet(packet)

    class Sink:
        def __init__(self, sink: TransportSink, snooper: Snooper) -> None:
            self.sink = sink
            self.snooper = snooper

        def on_packet(self, packet: bytes) -> None:
            self.snooper.snoop(packet, Snooper.Direction.HOST_TO_CONTROLLER)
            if self.sink:
                self.sink.on_packet(packet)

    def __init__(
        self,
        transport: Transport,
        snooper: Snooper,
        close_snooper=None,
    ) -> None:
        super().__init__(
            self.Source(transport.source, snooper), self.Sink(transport.sink, snooper)
        )
        self.transport = transport
        self.close_snooper = close_snooper

    async def close(self):
        await self.transport.close()
        if self.close_snooper:
            self.close_snooper()