bledev

Portable Bluetooth Low Energy: the contract every bledev backend implements.

You write a BLE program once against this module, and it runs on a board (bledev.mpble), on a laptop (bledev.bleak), in a browser (bledev.webble), or against the in-process loopback in tests (bledev.fake). The guide is docs/guides/bluetooth-le.md.

The shape is aioble’s, and it is async throughout. The pieces:

  • UUID, the errors, and the FLAG_* property bits.

  • BLE, the adapter. A backend subclasses it. capabilities() says which roles it can take, because roles aren’t symmetric: bleak and Web Bluetooth are central only, and a board can be either.

  • The peripheral side: Service and Characteristic describe a GATT server, ble.register_services() installs it, and await ble.advertise() returns a Connection when a central connects.

  • The central side: ble.scan() yields ScanResult, ble.find() returns a Device, and await device.connect() returns a Connection, whose services and characteristics you discover as ClientService and ClientCharacteristic.

Nothing here imports a backend, and nothing here imports bledev.auto.

bledev.DEFAULT_MTU = 23

Every connection starts at this ATT MTU. One ATT packet carries mtu - 3 bytes of value.

bledev.ADDR_MODE_PUBLIC = 0

Which address this radio uses on the air, for ble.config(addr_mode=...). ADDR_MODE_RPA is a resolvable private address: it changes every few minutes, and a phone that bonded with the board can still recognise it.

exception bledev.BLEError[source]

Bases: Exception

Base of every error bledev raises.

exception bledev.UnsupportedError[source]

Bases: BLEError

This backend cannot do that: a role it can’t take, or a missing feature.

exception bledev.DisconnectedError[source]

Bases: BLEError

The connection dropped, or was already closed, before the operation finished.

exception bledev.BLETimeoutError[source]

Bases: BLEError

An operation given timeout_ms did not finish in time.

exception bledev.BusyError[source]

Bases: BLEError

The controller’s transmit buffers are full. Wait a moment and send again.

Only Characteristic.notify raises it, because it is synchronous; every async send waits for room instead.

bledev.INSUFFICIENT_AUTHENTICATION = 5

ATT error codes a GattError can carry that apps act on.

exception bledev.PairingError[source]

Bases: BLEError

Pairing failed: a wrong passkey, a refusal, or a peer that lost its keys.

bledev.STALE_BOND = "the board refused this host's keys: it has probably lost its bond (a chip erase, or bledev.security.forget()). Unpair it on this host (bledev.bleak.unpair(address), or Settings > Bluetooth > Remove device) and pair again"

What to tell someone whose host kept a bond the board no longer has.

bledev.NEEDS_PAIRING = (5, 15)

The GATT statuses that mean “pair first”.

exception bledev.GattError(status, message=None)[source]

Bases: BLEError

The peer answered a GATT request with an error status.

async bledev.sleep_ms(ms)[source]

asyncio.sleep_ms on every interpreter.

async bledev.wait_ms(awaitable, timeout_ms, what='operation')[source]

Await awaitable, raising BLETimeoutError after timeout_ms.

timeout_ms=None waits forever. Backends use this so every timeout in bledev is the same exception.

class bledev.UUID(value)[source]

Bases: object

A Bluetooth UUID, the same value on every host.

Accepts a 16- or 32-bit int (UUID(0x180F)), a string in any of the usual spellings ("180f", "0x180F", "6e400001-b5a3-f393-e0a9-e50e24dcca9e"), another UUID, MicroPython’s bluetooth.UUID, or 2, 4 or 16 bytes in Bluetooth’s little-endian wire order. A short UUID equals its 128-bit expansion.

str() is always the 128-bit lowercase form, which is what bleak and Web Bluetooth use. short is the 16/32-bit value, or None. to_bytes() is the wire form, shortest first.

property short

The 16- or 32-bit value when this is a Bluetooth-base UUID, else None.

to_bytes()[source]

Little-endian wire bytes: 2 for a 16-bit UUID, 4 for 32-bit, else 16.

bledev.pack_advertisement(name=None, services=None, appearance=0, manufacturer=None, service_data=None)[source]

Build (adv_data, resp_data), in aioble’s field order.

Fields go into the 31-byte advertisement in this order (flags, services, service data, name, appearance, manufacturer) and overflow into the scan response, which only an active scan sees. That is why a long name can be invisible to a passive scan. The fake backend and mpble both advertise what this returns, so tests see what a board sends. manufacturer is (company_id, data); service_data is a list of (uuid, data).

bledev.decode_fields(*payloads)[source]

Yield (adv_type, value) for every field in the given payloads.

bledev.decode_advertisement(*payloads)[source]

(name, services, appearance, manufacturer) from raw payloads.

manufacturer is a list of (company_id, data).

bledev.decode_service_data(*payloads)[source]

[(UUID, data), ...] from the service-data fields of raw payloads.

class bledev.BLE[source]

Bases: object

One radio. Backends subclass this; apps receive one from a board config.

Methods a backend can’t support raise UnsupportedError, so a central-only host fails loudly at advertise() rather than doing nothing. Check capabilities() first when your app can take either role.

capabilities()[source]

A dict describing this backend. Keys every backend provides:

backend (its module name), central and peripheral (which roles it can take), mtu (the ATT MTU it asks for), max_mtu, indicate, pairing and l2cap (bools), long_read: whether a read returns values longer than one packet (mtu - 1), and write_notifies: whether setting a served characteristic’s value already notifies its subscribers (CircuitPython’s _bleio).

config(*names, **settings)[source]

Read or set adapter settings, like bluetooth.BLE.config.

config(mtu=247) sets the ATT MTU this side asks for; config("mtu") reads it. gap_name is the device name in the GAP service. addr_mode is the address the radio uses on the air: ADDR_MODE_PUBLIC, ADDR_MODE_RANDOM, ADDR_MODE_RPA (a resolvable private address that rotates, so a phone can’t follow the board except through a bond) or ADDR_MODE_NRPA. Set it before you advertise or scan. A setting the backend doesn’t have raises UnsupportedError.

close()[source]

Stop advertising and scanning, drop connections, and turn the radio off.

register_services(*services)[source]

Install the GATT server. Replaces whatever was registered before.

Call it before advertise(). Each Characteristic is bound to this adapter from here on.

async advertise(interval_us=100000, *, name=None, services=None, appearance=0, manufacturer=None, connectable=True, timeout_ms=None, service_data=None)[source]

Advertise until a central connects, and return that Connection.

service_data is a list of (uuid, data) (Improv uses it). Raises BLETimeoutError if nobody connects within timeout_ms. Cancelling the task stops advertising. Advertising stops when a central connects; call again to accept another.

scan(duration_ms, *, active=False, interval_us=None, window_us=None)[source]

Scan for duration_ms. Use as:

async with ble.scan(5000, active=True) as scanner:
    async for result in scanner:
        ...

A device can be yielded more than once as its data arrives. An active scan also asks for scan responses, which is where a long name ends up.

async find(name=None, service=None, *, timeout_ms=10000, active=True)[source]

Scan until a device matching name and/or service appears.

Returns its Device, or raises BLETimeoutError.

class bledev.Service(uuid)[source]

Bases: object

A GATT service you serve. Add characteristics by constructing them with it.

class bledev.Characteristic(service, uuid, read=False, write=False, write_no_response=False, notify=False, indicate=False, initial=None, capture=False, max_len=20, encrypted=False, authenticated=False)[source]

Bases: object

A characteristic in a Service you serve.

The flags are aioble’s. max_len is the largest value a central may write; MicroPython’s default buffer is 20 bytes, so raise it for anything that takes whole MTU-sized writes. With capture=True, written() returns every write as (connection, data), in order, instead of just the last writer. encrypted=True refuses a central that hasn’t paired (GattError with status INSUFFICIENT_ENCRYPTION) until it does; authenticated=True also refuses one that paired without a passkey (INSUFFICIENT_AUTHENTICATION).

encrypted

True when a central must pair (an encrypted link) before it may read, write or subscribe. HID keyboards serve their reports this way.

authenticated

True when only a link paired with a passkey (or numeric comparison) may use it: “just works” isn’t enough.

descriptors

Descriptor objects, in the order they were made.

read()[source]

The local value, as bytes.

write(data, send_update=False)[source]

Set the local value. send_update also notifies or indicates subscribers.

notify(connection, data=None)[source]

Send data (or the current value) to connection as a notification.

Synchronous, like aioble. data must fit in connection.mtu - 3 bytes. Raises BusyError when the transmit buffers are full; await a moment and send again (bledev.nus shows the loop).

async indicate(connection, data=None, timeout_ms=1000)[source]

Send an indication and wait for the central to acknowledge it.

async written(timeout_ms=None)[source]

Wait for a central to write this characteristic.

Returns the writer’s Connection, or (connection, data) with capture=True. It serves every connection, so it does not end when one disconnects; pass timeout_ms or cancel the task.

class bledev.Descriptor(characteristic, uuid, initial=b'')[source]

Bases: object

A read-only descriptor on a Characteristic you serve.

HID uses these: each Report characteristic carries a Report Reference (0x2908) saying which report it is. The value is fixed once registered. Don’t make a CCCD (0x2902); every backend adds that itself for a characteristic with notify or indicate.

class bledev.Device(ble, address, addr_type=0, name=None, native=None)[source]

Bases: object

A peer found by a scan, or named by address. connect() it.

address is a string: "aa:bb:cc:dd:ee:ff" on a board, and whatever the OS uses on a host (macOS and browsers hide real addresses). addr holds the six raw bytes where the backend knows them, else None.

native

The backend’s own object for this device (aioble Device, bleak BLEDevice, …).

async connect(timeout_ms=10000, **options)[source]

Connect as central and return the Connection.

Options a backend understands (min_conn_interval_us, max_conn_interval_us on a board) pass through; others are ignored.

class bledev.ScanResult(device, rssi=None, name=None, services=(), appearance=0, manufacturer=(), connectable=True, service_data=())[source]

Bases: object

One device’s advertisement, as aioble reports it.

name(), services() and manufacturer() are methods, as in aioble. services() returns a list of UUID.

service_data(uuid=None)[source]

[(UUID, data), ...], optionally only for uuid.

class bledev.Scanner(ble, duration_ms, active=False, interval_us=None, window_us=None)[source]

Bases: object

What ble.scan() returns: an async context manager and async iterator.

A backend either subclasses this and overrides the three hooks, or pushes results into it with _push() and _finish() from the event loop.

class bledev.Connection(ble, device, role)[source]

Bases: object

A live link to one peer, from either side.

role is the role this side plays: "central" if it connected, "peripheral" if it advertised. mtu is the current ATT MTU; one notification or write carries mtu - 3 bytes. Use async with to disconnect on exit.

Service discovery works from either role, but in practice only the central uses it.

property mtu

The current ATT MTU. One packet carries mtu - 3 bytes of value.

async disconnect(timeout_ms=2000)[source]

Drop the link and wait for it to be gone.

async disconnected(timeout_ms=None)[source]

Wait until the link drops, from either side.

property encrypted

True once the link is encrypted (after pair, or a bonded reconnect).

async pair(bond=True, timeout_ms=30000, passkey=None)[source]

Pair with the peer and encrypt the link; with bond, keep the keys.

Either side may call it; in practice the central does, when a read fails with INSUFFICIENT_ENCRYPTION. Without passkey the pairing is “just works”, which is what a keyboard without a screen does. When the peer shows a passkey (a board with a display), passkey is what to type in: an int, a string of six digits, or a callable (plain or async) that returns one when asked, such as one that prompts a person. A bonded peer reconnects without pairing again, for as long as both sides keep their keys; pairing a bonded peer just encrypts the link with the stored keys.

Raises PairingError when pairing fails (a wrong passkey, or a peer that lost its half of the bond), and UnsupportedError on a backend without pairing.

property authenticated

True when the link’s keys came from a passkey or numeric comparison.

async unpair()[source]

Forget this peer’s keys on this side (and, on a laptop, the OS’s pairing).

async exchange_mtu(mtu=None, timeout_ms=1000)[source]

Negotiate a larger ATT MTU and return the result.

Hosts that negotiate on their own (bleak, browsers) just return the current value.

services(uuid=None, timeout_ms=2000)[source]

Async-iterate the peer’s services, optionally only uuid.

async service(uuid, timeout_ms=2000)[source]

The peer’s service uuid, or None if it has none.

class bledev.ClientService(connection, uuid)[source]

Bases: object

A service on the peer, found by discovery.

async characteristic(uuid, timeout_ms=2000)[source]

The characteristic uuid in this service, or None.

class bledev.ClientCharacteristic(service, uuid, properties)[source]

Bases: object

A characteristic on the peer. properties holds its FLAG_* bits.

Notifications and indications are queued in arrival order and never silently dropped: a backend whose queue overflows raises BLEError from the next notified(). Call subscribe() before you expect any to arrive.

arrival says in what order the last notification came in, relative to the other characteristics’ (it is None on a backend that doesn’t number them). Each queue is in order on its own, but waiting on two characteristics at once wakes them in no particular order; the number is taken when the radio receives the notification, so you can put them back.

arrival = None

After notified() returns, an integer that grows with every notification the radio receives, whichever characteristic it is on, or None if the backend doesn’t number them.

async read(timeout_ms=1000)[source]

The value. A backend without long reads (capabilities()["long_read"] is False: MicroPython) returns at most connection.mtu - 1 bytes.

descriptors(uuid=None, timeout_ms=2000)[source]

Async-iterate this characteristic’s descriptors, optionally only uuid.

async descriptor(uuid, timeout_ms=2000)[source]

The descriptor uuid on this characteristic, or None.

async write(data, response=None, timeout_ms=1000)[source]

Write data (at most connection.mtu - 3 bytes).

response=None asks for a response only when the characteristic doesn’t allow writing without one. A write without response waits for buffer room rather than failing.

async notified(timeout_ms=None)[source]

The next notification’s data. Raises DisconnectedError if the link drops.

class bledev.ClientDescriptor(characteristic, uuid)[source]

Bases: object

A descriptor on the peer, found by ClientCharacteristic.descriptors.

bledev.is_adapter(obj)[source]

True for a bledev BLE; False for a raw bluetooth.BLE or anything else.

async bledev.passkey_value(passkey)[source]

passkey as an int: it may be an int, a string of digits, or a callable (plain or async) returning either. None stays None.

async bledev.connect_and_set_up(ble, setup, *, name=None, service=None, device=None, timeout_ms=10000, attempts=3, setup_timeout_ms=4000, **options)[source]

Find a device, connect, and run await setup(connection); returns (connection, what setup returned).

If the link drops or stalls before setup finishes, this disconnects and tries again, up to attempts times. Profiles use it (nus, midi), because a link can come up dead: about one reconnect in fifty from Windows, the OS reports a connection the peripheral never saw, and the first GATT operation on it hangs until Windows gives up nine seconds later. setup_timeout_ms bounds that wait. options go to device.connect(), except pair (pair before setup) and passkey (for Connection.pair).