bledev.nus

Nordic UART Service: a two-way byte stream over BLE.

The board advertises and the other side connects:

import bledev.nus as nus

link = await nus.serve(ble, name="rack")    # on the board
link = await nus.connect(ble, name="rack")  # on the laptop, phone or another board

Both return a Link, which reads like an asyncio stream:

await link.write(b"hello\n")
line = await link.readline()
async for line in link:        # lines until the link closes
    ...
await link.close()

The UUIDs are Nordic’s, so nRF Connect, Web Bluetooth serial terminals and Workbench’s Bluetooth transport all speak to it. RX is what the central writes; TX is what the peripheral notifies.

ble is a bledev adapter. A raw MicroPython bluetooth.BLE is wrapped in bledev.mpble.MPBLE for you.

bledev.nus.MTU = 247

The ATT MTU both sides ask for. 247 fills one data-length-extended link packet (251 bytes), so a notification carries 244 bytes.

Bases: object

One end of a NUS byte stream. Made by serve or connect.

read() returns b"" once the link has closed and everything that arrived before has been read. bytes_in and bytes_out count payload bytes.

property closed

True once the link is down and nothing is left to read.

async read(n=-1)[source]

Up to n bytes (all that’s buffered when n < 0), waiting for at least one.

async readexactly(n)[source]

Exactly n bytes. Raises DisconnectedError if the link closes first.

async readline()[source]

Bytes up to and including b"\n"; at end of stream, whatever is left.

async write(data)[source]

Send all of data, split to the link’s MTU. Returns when the stack has it.

async drain()[source]

For asyncio-stream compatibility; write() already waited.

async close()[source]

Disconnect. Anything already received stays readable.

async bledev.nus.serve(ble, name=None, *, timeout_ms=None, interval_us=100000, mtu=247)[source]

Advertise the Nordic UART service as name (default: the board’s name, boarddev.name()) and return a Link when a central connects.

Call it again for the next connection; the service is registered once per adapter, so don’t register other services on the same adapter afterwards.

async bledev.nus.connect(ble, name=None, *, device=None, timeout_ms=10000, mtu=247, **connect_options)[source]

Find a NUS peripheral (by name, or the first one advertising the service), connect, and return a Link.

Pass device to skip the scan. connect_options go to device.connect(); on a board, min_conn_interval_us and max_conn_interval_us trade power for throughput.