File: gatt_adapters.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 (365 lines) | stat: -rw-r--r-- 13,163 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
# Copyright 2025 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.

# -----------------------------------------------------------------------------
# GATT - Type Adapters
# -----------------------------------------------------------------------------

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

import struct
from collections.abc import Callable, Iterable
from typing import Any, Generic, Literal, TypeVar

from bumble import utils
from bumble.core import InvalidOperationError
from bumble.gatt import Characteristic
from bumble.gatt_client import CharacteristicProxy

# -----------------------------------------------------------------------------
# Typing
# -----------------------------------------------------------------------------
_T = TypeVar('_T')
_T2 = TypeVar('_T2', bound=utils.ByteSerializable)
_T3 = TypeVar('_T3', bound=utils.IntConvertible)


# -----------------------------------------------------------------------------
class CharacteristicAdapter(Characteristic, Generic[_T]):
    '''Base class for GATT Characteristic adapters.'''

    def __init__(self, characteristic: Characteristic) -> None:
        super().__init__(
            characteristic.uuid,
            characteristic.properties,
            characteristic.permissions,
            characteristic.value,
            characteristic.descriptors,
        )


# -----------------------------------------------------------------------------
class CharacteristicProxyAdapter(CharacteristicProxy[_T]):
    '''Base class for GATT CharacteristicProxy adapters.'''

    def __init__(self, characteristic_proxy: CharacteristicProxy):
        super().__init__(
            characteristic_proxy.client,
            characteristic_proxy.handle,
            characteristic_proxy.end_group_handle,
            characteristic_proxy.uuid,
            characteristic_proxy.properties,
        )


# -----------------------------------------------------------------------------
class DelegatedCharacteristicAdapter(CharacteristicAdapter[_T]):
    '''
    Adapter that converts bytes values using an encode and/or a decode function.
    '''

    def __init__(
        self,
        characteristic: Characteristic,
        encode: Callable[[_T], bytes] | None = None,
        decode: Callable[[bytes], _T] | None = None,
    ):
        super().__init__(characteristic)
        self.encode = encode
        self.decode = decode

    def encode_value(self, value: _T) -> bytes:
        if self.encode is None:
            raise InvalidOperationError('delegated adapter does not have an encoder')
        return self.encode(value)

    def decode_value(self, value: bytes) -> _T:
        if self.decode is None:
            raise InvalidOperationError('delegate adapter does not have a decoder')
        return self.decode(value)


# -----------------------------------------------------------------------------
class DelegatedCharacteristicProxyAdapter(CharacteristicProxyAdapter[_T]):
    '''
    Adapter that converts bytes values using an encode and a decode function.
    '''

    def __init__(
        self,
        characteristic_proxy: CharacteristicProxy,
        encode: Callable[[_T], bytes] | None = None,
        decode: Callable[[bytes], _T] | None = None,
    ):
        super().__init__(characteristic_proxy)
        self.encode = encode
        self.decode = decode

    def encode_value(self, value: _T) -> bytes:
        if self.encode is None:
            raise InvalidOperationError('delegated adapter does not have an encoder')
        return self.encode(value)

    def decode_value(self, value: bytes) -> _T:
        if self.decode is None:
            raise InvalidOperationError('delegate adapter does not have a decoder')
        return self.decode(value)


# -----------------------------------------------------------------------------
class PackedCharacteristicAdapter(CharacteristicAdapter):
    '''
    Adapter that packs/unpacks characteristic values according to a standard
    Python `struct` format.
    For formats with a single value, the adapted `read_value` and `write_value`
    methods return/accept single values. For formats with multiple values,
    they return/accept a tuple with the same number of elements as is required for
    the format.
    '''

    def __init__(self, characteristic: Characteristic, pack_format: str) -> None:
        super().__init__(characteristic)
        self.struct = struct.Struct(pack_format)

    def pack(self, *values) -> bytes:
        return self.struct.pack(*values)

    def unpack(self, buffer: bytes) -> tuple:
        return self.struct.unpack(buffer)

    def encode_value(self, value: Any) -> bytes:
        return self.pack(*value if isinstance(value, tuple) else (value,))

    def decode_value(self, value: bytes) -> Any:
        unpacked = self.unpack(value)
        return unpacked[0] if len(unpacked) == 1 else unpacked


# -----------------------------------------------------------------------------
class PackedCharacteristicProxyAdapter(CharacteristicProxyAdapter):
    '''
    Adapter that packs/unpacks characteristic values according to a standard
    Python `struct` format.
    For formats with a single value, the adapted `read_value` and `write_value`
    methods return/accept single values. For formats with multiple values,
    they return/accept a tuple with the same number of elements as is required for
    the format.
    '''

    def __init__(self, characteristic_proxy, pack_format):
        super().__init__(characteristic_proxy)
        self.struct = struct.Struct(pack_format)

    def pack(self, *values) -> bytes:
        return self.struct.pack(*values)

    def unpack(self, buffer: bytes) -> tuple:
        return self.struct.unpack(buffer)

    def encode_value(self, value: Any) -> bytes:
        return self.pack(*value if isinstance(value, tuple) else (value,))

    def decode_value(self, value: bytes) -> Any:
        unpacked = self.unpack(value)
        return unpacked[0] if len(unpacked) == 1 else unpacked


# -----------------------------------------------------------------------------
class MappedCharacteristicAdapter(PackedCharacteristicAdapter):
    '''
    Adapter that packs/unpacks characteristic values according to a standard
    Python `struct` format.
    The adapted `read_value` and `write_value` methods return/accept a dictionary which
    is packed/unpacked according to format, with the arguments extracted from the
    dictionary by key, in the same order as they occur in the `keys` parameter.
    '''

    def __init__(
        self, characteristic: Characteristic, pack_format: str, keys: Iterable[str]
    ) -> None:
        super().__init__(characteristic, pack_format)
        self.keys = keys

    # pylint: disable=arguments-differ
    def pack(self, values) -> bytes:
        return super().pack(*(values[key] for key in self.keys))

    def unpack(self, buffer: bytes) -> Any:
        return dict(zip(self.keys, super().unpack(buffer)))


# -----------------------------------------------------------------------------
class MappedCharacteristicProxyAdapter(PackedCharacteristicProxyAdapter):
    '''
    Adapter that packs/unpacks characteristic values according to a standard
    Python `struct` format.
    The adapted `read_value` and `write_value` methods return/accept a dictionary which
    is packed/unpacked according to format, with the arguments extracted from the
    dictionary by key, in the same order as they occur in the `keys` parameter.
    '''

    def __init__(
        self,
        characteristic_proxy: CharacteristicProxy,
        pack_format: str,
        keys: Iterable[str],
    ) -> None:
        super().__init__(characteristic_proxy, pack_format)
        self.keys = keys

    # pylint: disable=arguments-differ
    def pack(self, values) -> bytes:
        return super().pack(*(values[key] for key in self.keys))

    def unpack(self, buffer: bytes) -> Any:
        return dict(zip(self.keys, super().unpack(buffer)))


# -----------------------------------------------------------------------------
class UTF8CharacteristicAdapter(CharacteristicAdapter[str]):
    '''
    Adapter that converts strings to/from bytes using UTF-8 encoding
    '''

    def encode_value(self, value: str) -> bytes:
        return value.encode('utf-8')

    def decode_value(self, value: bytes) -> str:
        return value.decode('utf-8')


# -----------------------------------------------------------------------------
class UTF8CharacteristicProxyAdapter(CharacteristicProxyAdapter[str]):
    '''
    Adapter that converts strings to/from bytes using UTF-8 encoding
    '''

    def encode_value(self, value: str) -> bytes:
        return value.encode('utf-8')

    def decode_value(self, value: bytes) -> str:
        return value.decode('utf-8')


# -----------------------------------------------------------------------------
class SerializableCharacteristicAdapter(CharacteristicAdapter[_T2]):
    '''
    Adapter that converts any class to/from bytes using the class'
    `to_bytes` and `__bytes__` methods, respectively.
    '''

    def __init__(self, characteristic: Characteristic, cls: type[_T2]) -> None:
        super().__init__(characteristic)
        self.cls = cls

    def encode_value(self, value: _T2) -> bytes:
        return bytes(value)

    def decode_value(self, value: bytes) -> _T2:
        return self.cls.from_bytes(value)


# -----------------------------------------------------------------------------
class SerializableCharacteristicProxyAdapter(CharacteristicProxyAdapter[_T2]):
    '''
    Adapter that converts any class to/from bytes using the class'
    `to_bytes` and `__bytes__` methods, respectively.
    '''

    def __init__(
        self, characteristic_proxy: CharacteristicProxy, cls: type[_T2]
    ) -> None:
        super().__init__(characteristic_proxy)
        self.cls = cls

    def encode_value(self, value: _T2) -> bytes:
        return bytes(value)

    def decode_value(self, value: bytes) -> _T2:
        return self.cls.from_bytes(value)


# -----------------------------------------------------------------------------
class EnumCharacteristicAdapter(CharacteristicAdapter[_T3]):
    '''
    Adapter that converts int-enum-like classes to/from bytes using the class'
    `int().to_bytes()` and `from_bytes()` methods, respectively.
    '''

    def __init__(
        self,
        characteristic: Characteristic,
        cls: type[_T3],
        length: int,
        byteorder: Literal['little', 'big'] = 'little',
    ):
        """
        Initialize an instance.

        Params:
          characteristic: the Characteristic to adapt to/from
          cls: the class to/from which to convert integer values
          length: number of bytes used to represent integer values
          byteorder: byte order of the byte representation of integers.
        """
        super().__init__(characteristic)
        self.cls = cls
        self.length = length
        self.byteorder = byteorder

    def encode_value(self, value: _T3) -> bytes:
        return int(value).to_bytes(self.length, self.byteorder)

    def decode_value(self, value: bytes) -> _T3:
        int_value = int.from_bytes(value, self.byteorder)
        return self.cls(int_value)


# -----------------------------------------------------------------------------
class EnumCharacteristicProxyAdapter(CharacteristicProxyAdapter[_T3]):
    '''
    Adapter that converts int-enum-like classes to/from bytes using the class'
    `int().to_bytes()` and `from_bytes()` methods, respectively.
    '''

    def __init__(
        self,
        characteristic_proxy: CharacteristicProxy,
        cls: type[_T3],
        length: int,
        byteorder: Literal['little', 'big'] = 'little',
    ):
        """
        Initialize an instance.

        Params:
          characteristic_proxy: the CharacteristicProxy to adapt to/from
          cls: the class to/from which to convert integer values
          length: number of bytes used to represent integer values
          byteorder: byte order of the byte representation of integers.
        """
        super().__init__(characteristic_proxy)
        self.cls = cls
        self.length = length
        self.byteorder = byteorder

    def encode_value(self, value: _T3) -> bytes:
        return int(value).to_bytes(self.length, self.byteorder)

    def decode_value(self, value: bytes) -> _T3:
        int_value = int.from_bytes(value, self.byteorder)
        return self.cls(int_value)