Section 16.14

Bleak

Full name: Bluetooth Low Energy platform Agnostic Klient; the spelling Klient, with a K, belongs to the name.

Definition

Bleak is a Python §12.23 library with which a program on a computer acts as a GATT §7.10 client of BLE §7.1 devices. BLE (Bluetooth Low Energy) is the low-power form of Bluetooth. GATT (Generic Attribute Profile) organizes a BLE device’s data into small values called characteristics, which a client reads, writes and subscribes to. Bleak offers one interface on Windows, Linux, Apple’s macOS and Android and hands each request to the operating system’s own Bluetooth software, called the backend. Its operations are asynchronous: a program awaits them with Python’s standard asyncio framework.

The idea

A test script writes a command to a device, awaits the write, records the time and reports that the device applied the command after 4 ms. What did the await wait for? Separate events follow a write: the backend accepts the request; the radio sends it; the device’s BLE software receives it and replies at the protocol level; the device’s application finishes acting on it, for example by storing new settings; and the host learns of that. A timestamp taken after the await marks only the event that the operation’s documented contract names.

Ordering a parcel is a fair picture. “Accepted”, “shipped”, “delivered” and “assembled and working” are four milestones, and “delivered” says nothing about the fourth. Only the recipient can report the fourth, and the report helps only if it names the order it is about. The picture stops there: a parcel service prints the order number on every message, while a BLE application must design its acknowledgment to carry one.

How it works

A Bleak session has five steps:

  1. device = await BleakScanner.find_device_by_address(addr) finds the device by its Bluetooth address.

  2. async with BleakClient(device) as client: connects, discovers the device’s services and characteristics, and disconnects when the block ends.

  3. await client.write_gatt_char(char, data, response=True) writes data to the characteristic char.

  4. await client.read_gatt_char(char) reads the current value.

  5. await client.start_notify(char, callback) subscribes to notifications, values that the device sends when it chooses. Bleak then runs callback(characteristic, data) on its event loop §14.23 for each one.

Bleak’s documentation states what each write mode waits for:

The device’s ATT layer sends a Write Response once it has accepted the value. The response reports nothing that the device’s application does with the value afterwards.

When a result needs the device’s application to have finished, the host needs application confirmation §5.42, and the application must say so in its own acknowledgment, bound to the request:

  1. The host gives each transfer a sequence number, one more than the previous transfer’s, and sends it inside the request.

  2. When the application reaches a terminal status for that transfer, a final outcome such as “committed” or “rejected, with a reason”, it stores the sequence number and the status in a status characteristic and sends both as a notification.

  3. The device seals the record: it never changes the status of that sequence number again, and it answers a repeated request with the same number by returning the stored status, which makes the request idempotent §8.31.

  4. The host accepts the notification only if its sequence number is the one it awaits and its status is terminal, then reads the status characteristic and requires the same sequence number and status.

Worked example

This timeline is invented to show the arithmetic. Assume the device and host events are placed on one time axis. The host can see its own calls and replies. Observing when the device acts would require a device timestamp aligned to that axis. At 0 ms the host calls write_gatt_char with response=True for transfer 8. At 4 ms the Write Response arrives and the await ends. At 10 ms the device’s application finishes storing and activating the transfer. At 12 ms the notification (8, committed) arrives and the callback §14.22 runs. At 19 ms the host’s read returns (8, committed).

Now let the acknowledgment of transfer 7 be delayed until 3 ms into transfer 8. A host that accepts any one-byte “OK” records 3 ms for transfer 8, whose protocol response has not even arrived, and reports success even if transfer 8 later fails. A host that checks sequence numbers sees 7, ignores that notification and keeps waiting for 8.

Stated precisely

As Bleak documents them, the write operations promise this:

Let ss be a transfer’s sequence number and σ\sigma a terminal status. Application completion of transfer ss is established when the host has received a notification (s,σ)(s, \sigma) and a later read has returned the same (s,σ)(s, \sigma). The rule assumes that sequence numbers are not reused while an old acknowledgment may still arrive, which needs enough bits and, across device restarts, a boot epoch §15.36, a number that names each run of the counter; that the device seals terminal records; and that the read returns the device’s current value, not a copy cached by the host. The latency to an event EE is tE−t0t_E - t_0, where t0t_0 is the submission time; the measurement names EE, its timing endpoint §18.1.6.

The double check rules out three errors: a leftover notification from an earlier transfer, which carries the wrong ss; a lost notification, after which the read still shows the status; and a device that notified and then lost the result, for example by restarting before storing it, which the read exposes.

Limits and common mistakes

Backends differ: each operating system’s Bluetooth software implements the operations in its own way. Record the Bleak version, the backend and the operating system version with each measurement.

A Write Response confirms acceptance by the device’s ATT layer, not by its application. At the ATT level a notification gets no confirmation from the client, while an indication does; neither shows a lasting effect on the device.

Write Without Response gives the sending application no delivery report. The radio link retransmits lost packets while the connection lasts, but a device with no room may discard the write, and a dropped connection loses queued data. One such write must fit into one ATT packet: at most the ATT MTU §7.14 (maximum transmission unit) minus 3 bytes.

A one-byte acknowledgment cannot be matched to a transfer, so a delayed, repeated or leftover acknowledgment is credited to the wrong transfer.

Callbacks run on the event loop. If other work occupies the loop, a callback runs late, and so does any timestamp taken inside it. With use_cached=True, some backends answer read_gatt_char from a cached value, so a confirming read must not use it.

Success of an operation says nothing about who sent the data or whether the device should act on it. Origin and authorization §1.7 need their own mechanisms, such as a message authentication code §5.7 over the request.

Questions answered

Does a completed write await a protocol response, callback, or only backend submission?

It depends on the write mode. With response=True, a completed Bleak write_gatt_char has awaited a protocol response: the device’s ATT (Attribute Protocol) Write Response, which says that the device’s BLE software accepted the value. With response=False, it has awaited only submission: the operating system’s Bluetooth backend took the data, and nothing is known about delivery. In neither mode has it awaited a callback, a notification or any sign that the device’s application finished acting on the value.

When a claim needs the application’s result, the device must send its own acknowledgment, and the host must bind that acknowledgment to the request. The acknowledgment carries the transfer’s sequence number and a terminal status; the device never changes that status afterwards; and the host accepts it only when a notification and a following read agree on the same sequence number and status. A measured interval must name the event that ends it.

Related entries: MTU and fragmentation (§7.14), Channel confidentiality versus object authenticity (§7.34), BlueZ (§12.21), D-Bus (§12.22), Staging versus commit versus activation (§8.22), Key confirmation versus application confirmation (§5.42), Write request versus write command (§7.13), Notification versus indication (§7.12), Asynchronous completion (§9.28), Event epoch and sequence identity (§15.36). Further reading: [63].