File: mtu_size.py

package info (click to toggle)
bleak 2.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,828 kB
  • sloc: python: 10,660; makefile: 165; java: 105
file content (45 lines) | stat: -rw-r--r-- 1,447 bytes parent folder | download
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
"""
Example showing how to use BleakClient.mtu_size
"""

import asyncio

from bleak import BleakBackend, BleakClient, BleakScanner
from bleak.backends.scanner import AdvertisementData, BLEDevice

# replace with real characteristic UUID
CHAR_UUID = "00000000-0000-0000-0000-000000000000"


async def main() -> None:
    queue: asyncio.Queue[BLEDevice] = asyncio.Queue()

    def callback(device: BLEDevice, adv: AdvertisementData) -> None:
        # can use advertising data to filter here
        queue.put_nowait(device)

    async with BleakScanner(callback):
        # get the first matching device
        device = await queue.get()

    async with BleakClient(device) as client:
        # BlueZ doesn't have a proper way to get the MTU, so we have this hack.
        # If this doesn't work for you, you can set the client._mtu_size attribute
        # to override the value instead.
        if client.backend_id == BleakBackend.BLUEZ_DBUS:
            await client._backend._acquire_mtu()  # type: ignore

        print("MTU:", client.mtu_size)

        # Write without response is limited to MTU - 3 bytes

        data = bytes(1000)  # replace with real data
        chunk_size = client.mtu_size - 3
        for chunk in (
            data[i : i + chunk_size] for i in range(0, len(data), chunk_size)
        ):
            await client.write_gatt_char(CHAR_UUID, chunk, response=False)


if __name__ == "__main__":
    asyncio.run(main())