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. _bleio has no async API. Connecting, service discovery, a read, a write with response and a subscription each wait inside _bleio until the radio answers, usually one or two connection intervals, and nothing else in asyncio runs meanwhile. A scan runs in slices of SCAN_SLICE_MS for 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 a CharacteristicBuffer, a byte stream: with capture=True each written() 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() raises BusyError while 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’s PacketBuffer (see _CPServerCharacteristic._send), and it also keeps each notification whole, where PacketBuffer would 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, whatever send_update says, because that’s what _bleio does.

  • Indications go out, but indicate() returns once they’re queued: _bleio doesn’t report the acknowledgement. A central here can’t receive indications at all (CircuitPython’s ESP32 port ignores them), so capabilities()["indicate"] is False.

  • Pairing is “just works” only. CircuitPython’s ESP32 port has no passkey or numeric comparison (authenticated=True raises UnsupportedError), and it always bonds. Its MTU is fixed at build time (256 on the ESP32 port), so config(mtu=...) is unsupported; both sides exchange at connect.

  • A peripheral doesn’t learn the central’s address. _bleio doesn’t expose it, so connection.device.address is "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.

bledev.cpble.get(adapter=None)[source]

The shared CPBLE for this board’s radio, made on first use.

class bledev.cpble.CPBLE(adapter=None, *, queue_limit=64, stream_buffer=32768)[source]

Bases: BLE

The board’s radio, _bleio.adapter unless you pass another.

queue_limit bounds each notification and capture queue, and sizes the packet buffers _bleio fills. stream_buffer is the byte size of the buffer behind a write-only characteristic with capture=True (nus’s RX): what arrives while your code doesn’t read. Prefer get.

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), 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.

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.

forget_bonds()[source]

Erase every bond this board holds (_bleio.adapter.erase_bonding()).

register_services(*services)[source]

Serve services.

_bleio can’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 raises BLEError: 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_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.