File: run_gatt_with_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 (430 lines) | stat: -rw-r--r-- 16,021 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
# 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.

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

import asyncio
import dataclasses
import enum
import functools
import random
import struct
import sys
from typing import Any

import bumble.logging
from bumble import core, gatt, gatt_adapters, gatt_client, hci, transport
from bumble.device import Device, Peer

# -----------------------------------------------------------------------------
SERVICE_UUID = core.UUID("50DB505C-8AC4-4738-8448-3B1D9CC09CC5")
CHARACTERISTIC_UUID_BASE = "D901B45B-4916-412E-ACCA-0000000000"

DEFAULT_CLIENT_ADDRESS = "F0:F1:F2:F3:F4:F5"
DEFAULT_SERVER_ADDRESS = "F1:F2:F3:F4:F5:F6"


# -----------------------------------------------------------------------------
@dataclasses.dataclass
class CustomSerializableClass:
    x: int
    y: int

    @classmethod
    def from_bytes(cls, data: bytes) -> CustomSerializableClass:
        return cls(*struct.unpack(">II", data))

    def __bytes__(self) -> bytes:
        return struct.pack(">II", self.x, self.y)


# -----------------------------------------------------------------------------
@dataclasses.dataclass
class CustomClass:
    a: int
    b: int

    @classmethod
    def decode(cls, data: bytes) -> CustomClass:
        return cls(*struct.unpack(">II", data))

    def encode(self) -> bytes:
        return struct.pack(">II", self.a, self.b)


# -----------------------------------------------------------------------------
class CustomEnum(enum.IntEnum):
    FOO = 1234
    BAR = 5678


# -----------------------------------------------------------------------------
async def client(device: Device, address: hci.Address) -> None:
    print(f'=== Connecting to {address}...')
    connection = await device.connect(address)
    print('=== Connected')

    # Discover all characteristics.
    peer = Peer(connection)
    print("*** Discovering services and characteristics...")
    await peer.discover_all()
    print("*** Discovery complete")

    service = peer.get_services_by_uuid(SERVICE_UUID)[0]
    characteristics: list[gatt_client.CharacteristicProxy] = []
    for index in range(1, 10):
        characteristics.append(
            service.get_characteristics_by_uuid(
                core.UUID(CHARACTERISTIC_UUID_BASE + f"{index:02X}")
            )[0]
        )

    # Read all characteristics as raw bytes.
    for characteristic in characteristics:
        value = await characteristic.read_value()
        print(f"### {characteristic} = {value!r} ({value.hex()})")

    # Subscribe to all characteristics as a raw bytes listener.
    def on_raw_characteristic_update(characteristic, value):
        print(f"^^^ Update[RAW] {characteristic.uuid} value = {value.hex()}")

    for characteristic in characteristics:
        await characteristic.subscribe(
            functools.partial(on_raw_characteristic_update, characteristic)
        )

    # Function to subscribe to adapted characteristics
    def on_adapted_characteristic_update(characteristic, value):
        print(
            f"^^^ Update[ADAPTED] {characteristic.uuid} value = {value!r}, "
            f"type={type(value)}"
        )

    # Static characteristic with a bytes value.
    c1 = characteristics[0]
    c1_value = await c1.read_value()
    print(f"@@@ C1 {c1} value = {c1_value!r} (type={type(c1_value)})")
    await c1.write_value("happy π day".encode())
    await c1.subscribe(functools.partial(on_adapted_characteristic_update, c1))

    # Static characteristic with a string value.
    c2 = gatt_adapters.UTF8CharacteristicProxyAdapter(characteristics[1])
    c2_value = await c2.read_value()
    print(f"@@@ C2 {c2} value = {c2_value} (type={type(c2_value)})")
    await c2.write_value("happy π day")
    await c2.subscribe(functools.partial(on_adapted_characteristic_update, c2))

    # Static characteristic with a tuple value.
    c3 = gatt_adapters.PackedCharacteristicProxyAdapter(characteristics[2], ">III")
    c3_value = await c3.read_value()
    print(f"@@@ C3 {c3} value = {c3_value} (type={type(c3_value)})")
    await c3.write_value((2001, 2002, 2003))
    await c3.subscribe(functools.partial(on_adapted_characteristic_update, c3))

    # Static characteristic with a named tuple value.
    c4 = gatt_adapters.MappedCharacteristicProxyAdapter(
        characteristics[3], ">III", ["f1", "f2", "f3"]
    )
    c4_value = await c4.read_value()
    print(f"@@@ C4 {c4} value = {c4_value} (type={type(c4_value)})")
    await c4.write_value({"f1": 4001, "f2": 4002, "f3": 4003})
    await c4.subscribe(functools.partial(on_adapted_characteristic_update, c4))

    # Static characteristic with a serializable value.
    c5 = gatt_adapters.SerializableCharacteristicProxyAdapter(
        characteristics[4], CustomSerializableClass
    )
    c5_value = await c5.read_value()
    print(f"@@@ C5 {c5} value = {c5_value} (type={type(c5_value)})")
    await c5.write_value(CustomSerializableClass(56, 57))
    await c5.subscribe(functools.partial(on_adapted_characteristic_update, c5))

    # Static characteristic with a delegated value.
    c6 = gatt_adapters.DelegatedCharacteristicProxyAdapter(
        characteristics[5], encode=CustomClass.encode, decode=CustomClass.decode
    )
    c6_value = await c6.read_value()
    print(f"@@@ C6 {c6} value = {c6_value} (type={type(c6_value)})")
    await c6.write_value(CustomClass(6, 7))
    await c6.subscribe(functools.partial(on_adapted_characteristic_update, c6))

    # Dynamic characteristic with a bytes value.
    c7 = characteristics[6]
    c7_value = await c7.read_value()
    print(f"@@@ C7 {c7} value = {c7_value!r} (type={type(c7_value)})")
    await c7.write_value(bytes.fromhex("01020304"))
    await c7.subscribe(functools.partial(on_adapted_characteristic_update, c7))

    # Dynamic characteristic with a string value.
    c8 = gatt_adapters.UTF8CharacteristicProxyAdapter(characteristics[7])
    c8_value = await c8.read_value()
    print(f"@@@ C8 {c8} value = {c8_value} (type={type(c8_value)})")
    await c8.write_value("howdy")
    await c8.subscribe(functools.partial(on_adapted_characteristic_update, c8))

    # Static characteristic with an enum value
    c9 = gatt_adapters.EnumCharacteristicProxyAdapter(
        characteristics[8], CustomEnum, 3, 'big'
    )
    c9_value = await c9.read_value()
    print(f"@@@ C9 {c9} value = {c9_value.name} (type={type(c9_value)})")
    await c9.write_value(CustomEnum.BAR)
    await c9.subscribe(functools.partial(on_adapted_characteristic_update, c9))


# -----------------------------------------------------------------------------
def dynamic_read(selector: str) -> bytes | str:
    if selector == "bytes":
        print("$$$ Returning random bytes")
        return random.randbytes(7)
    elif selector == "string":
        print("$$$ Returning random string")
        return random.randbytes(7).hex()

    raise ValueError("invalid selector")


# -----------------------------------------------------------------------------
def dynamic_write(selector: str, value: Any) -> None:
    print(f"$$$ Received[{selector}]: {value} (type={type(value)})")


# -----------------------------------------------------------------------------
def on_characteristic_read(characteristic: gatt.Characteristic, value: Any) -> None:
    """Event listener invoked when a characteristic is read."""
    print(f"<<< READ: {characteristic} -> {value} ({type(value)})")


# -----------------------------------------------------------------------------
def on_characteristic_write(characteristic: gatt.Characteristic, value: Any) -> None:
    """Event listener invoked when a characteristic is written."""
    print(f"<<< WRITE: {characteristic} <- {value}  ({type(value)})")


# -----------------------------------------------------------------------------
async def server(device: Device) -> None:
    # Static characteristic with a bytes value.
    c1 = gatt.Characteristic(
        CHARACTERISTIC_UUID_BASE + "01",
        gatt.Characteristic.Properties.READ
        | gatt.Characteristic.Properties.WRITE
        | gatt.Characteristic.Properties.NOTIFY,
        gatt.Characteristic.READABLE | gatt.Characteristic.WRITEABLE,
        b'hello',
    )

    # Static characteristic with a string value.
    c2 = gatt_adapters.UTF8CharacteristicAdapter(
        gatt.Characteristic(
            CHARACTERISTIC_UUID_BASE + "02",
            gatt.Characteristic.Properties.READ
            | gatt.Characteristic.Properties.WRITE
            | gatt.Characteristic.Properties.NOTIFY,
            gatt.Characteristic.READABLE | gatt.Characteristic.WRITEABLE,
            'hello',
        )
    )

    # Static characteristic with a tuple value.
    c3 = gatt_adapters.PackedCharacteristicAdapter(
        gatt.Characteristic(
            CHARACTERISTIC_UUID_BASE + "03",
            gatt.Characteristic.Properties.READ
            | gatt.Characteristic.Properties.WRITE
            | gatt.Characteristic.Properties.NOTIFY,
            gatt.Characteristic.READABLE | gatt.Characteristic.WRITEABLE,
            (1007, 1008, 1009),
        ),
        ">III",
    )

    # Static characteristic with a named tuple value.
    c4 = gatt_adapters.MappedCharacteristicAdapter(
        gatt.Characteristic(
            CHARACTERISTIC_UUID_BASE + "04",
            gatt.Characteristic.Properties.READ
            | gatt.Characteristic.Properties.WRITE
            | gatt.Characteristic.Properties.NOTIFY,
            gatt.Characteristic.READABLE | gatt.Characteristic.WRITEABLE,
            {"f1": 3007, "f2": 3008, "f3": 3009},
        ),
        ">III",
        ["f1", "f2", "f3"],
    )

    # Static characteristic with a serializable value.
    c5 = gatt_adapters.SerializableCharacteristicAdapter(
        gatt.Characteristic(
            CHARACTERISTIC_UUID_BASE + "05",
            gatt.Characteristic.Properties.READ
            | gatt.Characteristic.Properties.WRITE
            | gatt.Characteristic.Properties.NOTIFY,
            gatt.Characteristic.READABLE | gatt.Characteristic.WRITEABLE,
            CustomSerializableClass(11, 12),
        ),
        CustomSerializableClass,
    )

    # Static characteristic with a delegated value.
    c6 = gatt_adapters.DelegatedCharacteristicAdapter(
        gatt.Characteristic(
            CHARACTERISTIC_UUID_BASE + "06",
            gatt.Characteristic.Properties.READ
            | gatt.Characteristic.Properties.WRITE
            | gatt.Characteristic.Properties.NOTIFY,
            gatt.Characteristic.READABLE | gatt.Characteristic.WRITEABLE,
            CustomClass(1, 2),
        ),
        encode=CustomClass.encode,
        decode=CustomClass.decode,
    )

    # Dynamic characteristic with a bytes value.
    c7 = gatt.Characteristic(
        CHARACTERISTIC_UUID_BASE + "07",
        gatt.Characteristic.Properties.READ
        | gatt.Characteristic.Properties.WRITE
        | gatt.Characteristic.Properties.NOTIFY,
        gatt.Characteristic.READABLE | gatt.Characteristic.WRITEABLE,
        gatt.CharacteristicValue(
            read=lambda connection: dynamic_read("bytes"),
            write=lambda connection, value: dynamic_write("bytes", value),
        ),
    )

    # Dynamic characteristic with a string value.
    c8 = gatt_adapters.UTF8CharacteristicAdapter(
        gatt.Characteristic(
            CHARACTERISTIC_UUID_BASE + "08",
            gatt.Characteristic.Properties.READ
            | gatt.Characteristic.Properties.WRITE
            | gatt.Characteristic.Properties.NOTIFY,
            gatt.Characteristic.READABLE | gatt.Characteristic.WRITEABLE,
            gatt.CharacteristicValue(
                read=lambda connection: dynamic_read("string"),
                write=lambda connection, value: dynamic_write("string", value),
            ),
        )
    )

    # Static characteristic with an enum value
    c9 = gatt_adapters.EnumCharacteristicAdapter(
        gatt.Characteristic(
            CHARACTERISTIC_UUID_BASE + "09",
            gatt.Characteristic.Properties.READ
            | gatt.Characteristic.Properties.WRITE
            | gatt.Characteristic.Properties.NOTIFY,
            gatt.Characteristic.READABLE | gatt.Characteristic.WRITEABLE,
            CustomEnum.FOO,
        ),
        cls=CustomEnum,
        length=3,
        byteorder='big',
    )

    characteristics: list[gatt.Characteristic] = [
        c1,
        c2,
        c3,
        c4,
        c5,
        c6,
        c7,
        c8,
        c9,
    ]

    # Listen for read and write events.
    for characteristic in characteristics:
        characteristic.on(
            "read",
            lambda _, value, c=characteristic: on_characteristic_read(c, value),
        )
        characteristic.on(
            "write",
            lambda _, value, c=characteristic: on_characteristic_write(c, value),
        )

    device.add_service(gatt.Service(SERVICE_UUID, characteristics))

    # Notify every 3 seconds
    i = 0
    while True:
        await asyncio.sleep(3)

        # Notifying can be done with the characteristic's current value, or
        # by explicitly passing a value to notify with. Both variants are used
        # here: for c1..c4 we set the value and then notify, for c4..c9 we notify
        # with an explicit value.
        c1.value = f'hello c1 {i}'.encode()
        await device.notify_subscribers(c1)
        c2.value = f'hello c2 {i}'
        await device.notify_subscribers(c2)
        c3.value = (1000 + i, 2000 + i, 3000 + i)
        await device.notify_subscribers(c3)
        c4.value = {"f1": 4000 + i, "f2": 5000 + i, "f3": 6000 + i}
        await device.notify_subscribers(c4)
        await device.notify_subscribers(c5, CustomSerializableClass(1000 + i, 2000 + i))
        await device.notify_subscribers(c6, CustomClass(3000 + i, 4000 + i))
        await device.notify_subscribers(c7, bytes([1, 2, 3, i % 256]))
        await device.notify_subscribers(c8, f'hello c8 {i}')
        await device.notify_subscribers(
            c9, CustomEnum.FOO if i % 2 == 0 else CustomEnum.BAR
        )

        i += 1


# -----------------------------------------------------------------------------
async def main() -> None:
    if len(sys.argv) < 2:
        print("Usage: run_gatt_with_adapters.py <transport-spec> client|server")
        print("example: run_gatt_with_adapters.py usb:0 F0:F1:F2:F3:F4:F5")
        return

    async with await transport.open_transport(sys.argv[1]) as hci_transport:
        is_client = sys.argv[2] == "client"

        # Create a device to manage the host
        device = Device.with_hci(
            "Bumble",
            hci.Address(
                DEFAULT_CLIENT_ADDRESS if is_client else DEFAULT_SERVER_ADDRESS
            ),
            hci_transport.source,
            hci_transport.sink,
        )

        # Get things going
        await device.power_on()

        if is_client:
            # Connect a client to a peer
            await client(device, hci.Address(DEFAULT_SERVER_ADDRESS))
        else:
            # Advertise so a peer can connect
            await device.start_advertising(auto_restart=True)

            # Setup a server
            await server(device)

        await hci_transport.source.terminated


# -----------------------------------------------------------------------------
bumble.logging.setup_basic_logging('DEBUG')
asyncio.run(main())