ubluepy — Bluetooth LE peripheral and central¶
The ubluepy module is the legacy Bluetooth LE API shipped with the
MicroPython nRF port. It is loosely modelled on the Linux
bluepy Python library and
sits directly on top of the Nordic SoftDevice — there is no portable
back-end, so the module is only available on Nordic targets (the
Arduino Nano 33 BLE Sense in OpenMV’s lineup). The newer
bluetooth / aioble APIs are not
enabled in this build, so ubluepy is the only way to drive the
on-die radio.
The available feature set depends on the SoftDevice flashed by the firmware:
s140 (Nano 33 BLE Sense) — both peripheral and central (scanner) roles. This is what the OpenMV firmware ships.
s132 — both peripheral and central.
s110 — peripheral only; scanner / connect methods are compiled out.
Peripheral example¶
Advertise as a Bluetooth LE peripheral with a single environmental sensing service and notify a temperature characteristic on every write to its Client Characteristic Configuration Descriptor (CCCD):
from ubluepy import Service, Characteristic, UUID, Peripheral, constants
from machine import LED
notif_enabled = False
def event_handler(event_id, handle, data):
global notif_enabled
if event_id == constants.EVT_GAP_CONNECTED:
LED("LED_GREEN").on()
elif event_id == constants.EVT_GAP_DISCONNECTED:
LED("LED_GREEN").off()
periph.advertise(device_name="Nano 33", services=[svc])
elif event_id == constants.EVT_GATTS_WRITE:
notif_enabled = bool(data[0])
svc = Service(UUID("181A")) # Environmental Sensing
char = Characteristic(UUID("2A6E"),
props=Characteristic.PROP_NOTIFY | Characteristic.PROP_READ,
attrs=Characteristic.ATTR_CCCD)
svc.addCharacteristic(char)
periph = Peripheral()
periph.addService(svc)
periph.setConnectionHandler(event_handler)
periph.advertise(device_name="Nano 33", services=[svc])
Central example¶
Scan for nearby advertising devices for 100 ms and decode each
ScanEntry’s advertisement data:
from ubluepy import Scanner, constants
s = Scanner()
for entry in s.scan(100):
print(entry.addr(), entry.rssi(), "dBm")
for ad_type, name, value in entry.getScanData():
print(" ", ad_type, name, bytes(value))
Module contents¶
Classes¶
- class ubluepy.UUID(value)¶
Construct a 16- or 128-bit Bluetooth UUID.
valueOne of:
int— a 16-bit numeric UUID (UUID(0x180A)).6-character
"0xXXXX"string — a 16-bit UUID, e.g.UUID("0x181A").36-character
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"string — a full 128-bit UUID. The vendor-specific portion is registered with the SoftDevice on construction.Another
UUIDinstance — performs a copy.
Any other length raises
ValueError("Invalid UUID string length").
- class ubluepy.Service(uuid: UUID, type: int = Service.PRIMARY)¶
Define a GATT service that will be registered with the SoftDevice when added to a
Peripheral.uuidA
UUIDinstance. Passing a non-UUID object raisesValueError.typeEither
Service.PRIMARY(default) orService.SECONDARY. Other values raiseValueError.
- addCharacteristic(characteristic: Characteristic) None¶
Register a
Characteristicwith the service. The characteristic’s GATT handle is assigned during this call.
- getCharacteristic(uuid: UUID) Characteristic | None¶
Look up a previously added
Characteristicby UUID. Returns the characteristic instance, orNoneif no match is found.
- class ubluepy.Characteristic(uuid: UUID, *, props: int = PROP_READ | PROP_WRITE, attrs: int = 0)¶
Define a GATT characteristic. Add it to a
ServicewithService.addCharacteristic()before the parentPeripheralstarts advertising.uuidA
UUIDinstance.props(keyword-only)Bitmask of one or more
Characteristic.PROP_*values describing what operations the characteristic supports.attrs(keyword-only)Bitmask of additional GATT attributes. Use
Characteristic.ATTR_CCCDto attach a Client Characteristic Configuration Descriptor — required to makePROP_NOTIFY/PROP_INDICATEcharacteristics work.
- read() bytearray¶
Central role only. Read the characteristic’s value from the connected peer. Returns a
bytearraywith the latest value. On a peripheral this is a no-op and returnsNone.
- write(data, *, with_response: bool = False) None¶
Write to the characteristic.
On a peripheral, if
PROP_NOTIFYis set in the characteristic’s properties the value is sent as a GATT notification to the connected central; otherwise the local attribute value is updated.On a central, the value is written to the remote peer. Set
with_response=Trueto issue a write request and wait for the peer’s acknowledgement instead of a write command.
datais any buffer-protocol object (bytes,bytearray,memoryview).
- class ubluepy.Descriptor(uuid: UUID)¶
Stub class for representing GATT descriptors. The current implementation only stores the UUID and exposes no methods — it is provided for forward compatibility with future revisions of the module.
- class ubluepy.Peripheral¶
The local Bluetooth LE device. The same class is used for both peripheral and central roles; the role is selected by which methods you call (
advertise()selects peripheral,connect()selects central).- addService(service: Service) None¶
Register a
Service(and all its previously added characteristics) with the local GATT server.
- getServices() list¶
Return the list of services currently registered with this
Peripheral.
- advertise(*, device_name: str | None = None, services: list | None = None, data: bytes | None = None, connectable: bool = True) None¶
Start advertising in peripheral role.
device_nameComplete local name advertised in the GAP payload.
servicesList of
Serviceinstances to advertise. Each service’s UUID is included in the advertisement.dataOptional raw advertisement payload (
bytes/bytearray) appended to the auto-generated header. Use this for vendor-specific or beacon payloads such as Eddystone.connectableWhen
True(default), advertise as a connectable device and register GAP / GATTS event handlers so the configuredsetConnectionHandler()callback fires on connect, disconnect, and CCCD writes. WhenFalse, advertise as a beacon — no handlers are attached and the device cannot be connected to.
- setConnectionHandler(func) None¶
Register a callback invoked on GAP and GATTS events. The callback is called as
func(event_id, conn_handle, data)whereevent_idis one of theconstants.EVT_GAP_CONNECTED,constants.EVT_GAP_DISCONNECTED, orconstants.EVT_GATTS_WRITEvalues,conn_handleis the SoftDevice connection handle (or attribute handle for GATTS writes), anddatais the raw event payload as abytearray(orNonefor connect / disconnect).
- setNotificationHandler(func) None¶
Register a callback for notification events received in central role.
- withDelegate(delegate: DefaultDelegate) None¶
Attach a
DefaultDelegateinstance to receive decoded GATT events.
- connect(addr, *, addr_type: int = constants.ADDR_TYPE_PUBLIC) None¶
Central role only. Connect to the peer with the given address and synchronously discover its primary services and characteristics. Blocks until the connection is established and discovery completes; the discovered services are then available via
getServices().addrPeer address as a 17-character
"xx:xx:xx:xx:xx:xx"string (e.g. taken fromScanEntry.addr()).addr_type(keyword-only)Either
constants.ADDR_TYPE_PUBLIC(default) orconstants.ADDR_TYPE_RANDOM_STATIC.
- class ubluepy.Scanner¶
GAP observer for discovering nearby advertising devices. Available only when the firmware is built against a SoftDevice with central support (s132 / s140).
- class ubluepy.ScanEntry¶
A single advertisement report captured by
Scanner.scan(). Instances are returned from the scanner — there is no public constructor.- addr_type() int¶
Return the peer address type (
constants.ADDR_TYPE_PUBLICorconstants.ADDR_TYPE_RANDOM_STATIC).
- getScanData() list¶
Decode the advertisement payload into a list of
(ad_type, description, value)tuples.ad_typeis the numeric AD type byte (seeconstants.ad_types),descriptionis the matching constant’s name as a string (orNoneif the type is unknown), andvalueis the AD record body as abytearray.
- class ubluepy.DefaultDelegate¶
Base class for objects passed to
Peripheral.withDelegate(). Subclass it and overridehandleConnection()/handleNotification()to react to GATT events.
Constants¶
The constants attribute of the module is a namespace
containing GAP/GATT event identifiers, address-type values, and
the nested ad_types namespace.
- constants.EVT_GAP_CONNECTED: int¶
Peripheralconnection handlerevent_idvalue for GAP connect (16).
- constants.EVT_GAP_DISCONNECTED: int¶
Peripheralconnection handlerevent_idvalue for GAP disconnect (17).
- constants.EVT_GATTS_WRITE: int¶
Peripheralconnection handlerevent_idvalue for a write to a local GATT attribute, including writes to a CCCD that enable/disable notifications (80).
- constants.UUID_CCCD: int¶
Standard Bluetooth UUID for the Client Characteristic Configuration Descriptor (
0x2902).
- constants.ad_types: type¶
Namespace of advertising-data AD-type constants from the Bluetooth Core Specification Supplement. Each name maps to the corresponding 1-byte AD type:
Name
Value
AD_TYPE_FLAGS0x01AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE0x02AD_TYPE_16BIT_SERVICE_UUID_COMPLETE0x03AD_TYPE_32BIT_SERVICE_UUID_MORE_AVAILABLE0x04AD_TYPE_32BIT_SERVICE_UUID_COMPLETE0x05AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE0x06AD_TYPE_128BIT_SERVICE_UUID_COMPLETE0x07AD_TYPE_SHORT_LOCAL_NAME0x08AD_TYPE_COMPLETE_LOCAL_NAME0x09AD_TYPE_TX_POWER_LEVEL0x0AAD_TYPE_CLASS_OF_DEVICE0x0DAD_TYPE_SIMPLE_PAIRING_HASH_C0x0EAD_TYPE_SIMPLE_PAIRING_RANDOMIZER_R0x0FAD_TYPE_SECURITY_MANAGER_TK_VALUE0x10AD_TYPE_SECURITY_MANAGER_OOB_FLAGS0x11AD_TYPE_SLAVE_CONNECTION_INTERVAL_RANGE0x12AD_TYPE_SOLICITED_SERVICE_UUIDS_16BIT0x14AD_TYPE_SOLICITED_SERVICE_UUIDS_128BIT0x15AD_TYPE_SERVICE_DATA0x16AD_TYPE_PUBLIC_TARGET_ADDRESS0x17AD_TYPE_RANDOM_TARGET_ADDRESS0x18AD_TYPE_APPEARANCE0x19AD_TYPE_ADVERTISING_INTERVAL0x1AAD_TYPE_LE_BLUETOOTH_DEVICE_ADDRESS0x1BAD_TYPE_LE_ROLE0x1CAD_TYPE_SIMPLE_PAIRING_HASH_C2560x1DAD_TYPE_SIMPLE_PAIRING_RANDOMIZER_R2560x1EAD_TYPE_SERVICE_DATA_32BIT_UUID0x20AD_TYPE_SERVICE_DATA_128BIT_UUID0x21AD_TYPE_URI0x24AD_TYPE_3D_INFORMATION_DATA0x3DAD_TYPE_MANUFACTURER_SPECIFIC_DATA0xFF