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 theFLAG_*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:
ServiceandCharacteristicdescribe a GATT server,ble.register_services()installs it, andawait ble.advertise()returns aConnectionwhen a central connects.The central side:
ble.scan()yieldsScanResult,ble.find()returns aDevice, andawait device.connect()returns aConnection, whose services and characteristics you discover asClientServiceandClientCharacteristic.
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 - 3bytes of value.
- bledev.ADDR_MODE_PUBLIC = 0
Which address this radio uses on the air, for
ble.config(addr_mode=...).ADDR_MODE_RPAis a resolvable private address: it changes every few minutes, and a phone that bonded with the board can still recognise it.
- exception bledev.UnsupportedError[source]
Bases:
BLEErrorThis backend cannot do that: a role it can’t take, or a missing feature.
- exception bledev.DisconnectedError[source]
Bases:
BLEErrorThe connection dropped, or was already closed, before the operation finished.
- exception bledev.BLETimeoutError[source]
Bases:
BLEErrorAn operation given
timeout_msdid not finish in time.
- exception bledev.BusyError[source]
Bases:
BLEErrorThe controller’s transmit buffers are full. Wait a moment and send again.
Only
Characteristic.notifyraises it, because it is synchronous; every async send waits for room instead.
- exception bledev.PairingError[source]
Bases:
BLEErrorPairing 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:
BLEErrorThe peer answered a GATT request with an error
status.
- async bledev.wait_ms(awaitable, timeout_ms, what='operation')[source]
Await
awaitable, raisingBLETimeoutErroraftertimeout_ms.timeout_ms=Nonewaits forever. Backends use this so every timeout in bledev is the same exception.
- class bledev.UUID(value)[source]
Bases:
objectA 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’sbluetooth.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.shortis the 16/32-bit value, orNone.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.
- 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.
manufactureris(company_id, data);service_datais 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.manufactureris 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:
objectOne 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 atadvertise()rather than doing nothing. Checkcapabilities()first when your app can take either role.- capabilities()[source]
A dict describing this backend. Keys every backend provides:
backend(its module name),centralandperipheral(which roles it can take),mtu(the ATT MTU it asks for),max_mtu,indicate,pairingandl2cap(bools),long_read: whether a read returns values longer than one packet (mtu - 1), andwrite_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_nameis the device name in the GAP service.addr_modeis 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) orADDR_MODE_NRPA. Set it before you advertise or scan. A setting the backend doesn’t have raisesUnsupportedError.
- register_services(*services)[source]
Install the GATT server. Replaces whatever was registered before.
Call it before
advertise(). EachCharacteristicis 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_datais a list of(uuid, data)(Improv uses it). RaisesBLETimeoutErrorif nobody connects withintimeout_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
nameand/orserviceappears.Returns its
Device, or raisesBLETimeoutError.
- class bledev.Service(uuid)[source]
Bases:
objectA 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:
objectA characteristic in a
Serviceyou serve.The flags are aioble’s.
max_lenis 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. Withcapture=True,written()returns every write as(connection, data), in order, instead of just the last writer.encrypted=Truerefuses a central that hasn’t paired (GattErrorwith statusINSUFFICIENT_ENCRYPTION) until it does;authenticated=Truealso 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
Descriptorobjects, in the order they were made.
- write(data, send_update=False)[source]
Set the local value.
send_updatealso notifies or indicates subscribers.
- notify(connection, data=None)[source]
Send
data(or the current value) toconnectionas a notification.Synchronous, like aioble.
datamust fit inconnection.mtu - 3bytes. RaisesBusyErrorwhen the transmit buffers are full; await a moment and send again (bledev.nusshows 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)withcapture=True. It serves every connection, so it does not end when one disconnects; passtimeout_msor cancel the task.
- class bledev.Descriptor(characteristic, uuid, initial=b'')[source]
Bases:
objectA read-only descriptor on a
Characteristicyou 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
notifyorindicate.
- class bledev.Device(ble, address, addr_type=0, name=None, native=None)[source]
Bases:
objectA peer found by a scan, or named by address.
connect()it.addressis 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).addrholds the six raw bytes where the backend knows them, elseNone.- 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_uson 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:
objectOne device’s advertisement, as aioble reports it.
name(),services()andmanufacturer()are methods, as in aioble.services()returns a list ofUUID.
- class bledev.Scanner(ble, duration_ms, active=False, interval_us=None, window_us=None)[source]
Bases:
objectWhat
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:
objectA live link to one peer, from either side.
roleis the role this side plays:"central"if it connected,"peripheral"if it advertised.mtuis the current ATT MTU; one notification or write carriesmtu - 3bytes. Useasync withto 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 - 3bytes of value.
- 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. Withoutpasskeythe pairing is “just works”, which is what a keyboard without a screen does. When the peer shows a passkey (a board with a display),passkeyis 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
PairingErrorwhen pairing fails (a wrong passkey, or a peer that lost its half of the bond), andUnsupportedErroron a backend without pairing.
- property authenticated
True when the link’s keys came from a passkey or numeric comparison.
- 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.
- class bledev.ClientService(connection, uuid)[source]
Bases:
objectA service on the peer, found by discovery.
- class bledev.ClientCharacteristic(service, uuid, properties)[source]
Bases:
objectA characteristic on the peer.
propertiesholds itsFLAG_*bits.Notifications and indications are queued in arrival order and never silently dropped: a backend whose queue overflows raises
BLEErrorfrom the nextnotified(). Callsubscribe()before you expect any to arrive.arrivalsays in what order the last notification came in, relative to the other characteristics’ (it isNoneon 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, orNoneif 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 mostconnection.mtu - 1bytes.
- 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
uuidon this characteristic, orNone.
- async write(data, response=None, timeout_ms=1000)[source]
Write
data(at mostconnection.mtu - 3bytes).response=Noneasks 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
DisconnectedErrorif the link drops.
- class bledev.ClientDescriptor(characteristic, uuid)[source]
Bases:
objectA descriptor on the peer, found by
ClientCharacteristic.descriptors.
- bledev.is_adapter(obj)[source]
True for a bledev
BLE; False for a rawbluetooth.BLEor anything else.
- async bledev.passkey_value(passkey)[source]
passkeyas an int: it may be an int, a string of digits, or a callable (plain or async) returning either.NonestaysNone.
- 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
setupfinishes, this disconnects and tries again, up toattemptstimes. 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_msbounds that wait.optionsgo todevice.connect(), exceptpair(pair beforesetup) andpasskey(forConnection.pair).