bledev.cpble
CircuitPython backend, over _bleio. Both roles.
import bledev.cpble ble = bledev.cpble.get() # the board’s one radio, shared
Needs CircuitPython with _bleio (every nRF52, and every ESP32 with BLE
except the S2), and the asyncio library from the Adafruit bundle
(circup install asyncio, which brings adafruit_ticks).
_bleio is the model furthest from aioble’s. aioble hands you events;
_bleio hands you objects you poll: a connection’s connected flag,
a buffer a characteristic’s writes land in, a scan’s iterator. So this backend
turns each wait into a short poll of those objects (every
POLL_MS), and a few things work differently from the other backends:
Some calls block the event loop.
_bleiohas no async API. Connecting, service discovery, a read, a write with response and a subscription each wait inside_bleiountil the radio answers, usually one or two connection intervals, and nothing else in asyncio runs meanwhile. A scan runs in slices ofSCAN_SLICE_MSfor the same reason.Writes land in ring buffers that CircuitPython fills from the radio’s task. A characteristic you can notify on gets a
PacketBuffer, which keeps each write whole but only takes writes from the central that subscribed, after it subscribed. Any other writable characteristic gets aCharacteristicBuffer, a byte stream: withcapture=Trueeachwritten()returns whatever bytes arrived since the last, not one write. Both drop the oldest data when full and don’t say so, so read them promptly; the stream buffer’s fill is checked and a full one raises.One notification in flight per characteristic.
notify()raisesBusyErrorwhile the previous one is still waiting for the radio; every async sender (nus, midi) waits and tries again. That’s how this backend steps around a stall in CircuitPython 10.3’sPacketBuffer(see_CPServerCharacteristic._send), and it also keeps each notification whole, wherePacketBufferwould otherwise merge two into one.Setting a value notifies.
Characteristic.write(data)on a characteristic with notify or indicate sends it to every subscribed central, whateversend_updatesays, because that’s what_bleiodoes.Indications go out, but
indicate()returns once they’re queued:_bleiodoesn’t report the acknowledgement. A central here can’t receive indications at all (CircuitPython’s ESP32 port ignores them), socapabilities()["indicate"]is False.Pairing is “just works” only. CircuitPython’s ESP32 port has no passkey or numeric comparison (
authenticated=TrueraisesUnsupportedError), and it always bonds. Its MTU is fixed at build time (256 on the ESP32 port), soconfig(mtu=...)is unsupported; both sides exchange at connect.A peripheral doesn’t learn the central’s address.
_bleiodoesn’t expose it, soconnection.device.addressis"central".The GATT server allows ten characteristics per service and two descriptors per characteristic, on the ESP32 port.
A service stays served until the board reloads. Run a peripheral again from the REPL and its new objects take over the copy already served, as long as the characteristics match. Change them and
register_services()raises: press Ctrl-D first.
The _bleio objects are there when you need them: ble.raw is
_bleio.adapter and connection.native a _bleio.Connection.
- bledev.cpble.POLL_MS = 5
How often a wait looks at
_bleio’s objects, in milliseconds.
- bledev.cpble.RETRY_MS = 5000
How long, in milliseconds, a characteristic keeps retrying its last notification after sending it. See
_CPServerCharacteristic._send().
- bledev.cpble.SCAN_SLICE_MS = 100
How long one slice of a scan blocks the event loop, in milliseconds.
- class bledev.cpble.CPBLE(adapter=None, *, queue_limit=64, stream_buffer=32768)[source]
Bases:
BLEThe board’s radio,
_bleio.adapterunless you pass another.queue_limitbounds each notification and capture queue, and sizes the packet buffers_bleiofills.stream_bufferis the byte size of the buffer behind a write-only characteristic withcapture=True(nus’s RX): what arrives while your code doesn’t read. Preferget.- min_setup_ms = 12000
How long a profile’s setup after connecting may take here (see
bledev.connect_and_set_up). CircuitPython’s ESP32 port waits out its whole 2 s timeout on every read and every write with response, because it waits for a status to leave 0 and success is 0; making a subscription is such a write.
- 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.
- enable_bonding(store=None)[source]
CircuitPython always bonds and keeps the keys itself (in NVS on an ESP32), so this only accepts the call.
forget_bonds()erases them.
- register_services(*services)[source]
Serve
services._bleiocan’t take a service out of the GATT table until the board reloads, so each service is added once and kept. Register a service whose UUID is already served (a script run again from the REPL) and its characteristics take over the served copy: reads, writes and notifications go to them, and the earlier objects get nothing. That needs the same characteristics, in the same order, with the same flags and descriptors. If they differ, this raisesBLEError: reload the board (Ctrl-D) to serve the new layout. A service served before and left out here stays in the table, unbound, until then.
- 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.