ubluetooth — Bluetooth Low Energy

This module provides a Bluetooth Low Energy control interface. Currently, it supports Bluetooth Low Energy (BLE) in the central, peripheral, broadcaster and observer roles, and a device can operate in multiple roles simultaneously.

This API is designed to match the Bluetooth Low Energy protocol and to provide building blocks for higher-level abstractions (such as specific device types).

Note

This module is still under development; its classes, functions, methods and constants may change.

BLE Class

Constructors

class ubluetooth.BLE

Return a BLE object.

Configuration

BLE.active([active])

(Optionally) change the active state of the BLE radio, and return the current state.

The radio must be made active before using any other methods of this class.

BLE.config('param')
BLE.config(param=value, ...)

Get or set the configuration values of the BLE interface. To get a value, the parameter name should be quoted as a string, and only one parameter is queried at a time. To set values, use the keyword syntax, and one or more parameters can be set at a time.

The currently supported values are:

  • 'mac': return the MAC address of the device. If the device has a fixed address (e.g. PYBD), it will be returned. Otherwise (e.g. ESP32), a random address will be generated when the BLE interface is active.

  • 'rxbuf': set the size (in bytes) of the internal buffer used to store incoming events. This buffer is a global buffer for the entire BLE driver, so it can handle incoming data for all events (including all characteristics). Increasing this value can better handle bursts of incoming data (e.g. scan results) and allows the central device to receive larger characteristic values.

Event handling

BLE.irq(handler, trigger=0xffff)

Register a callback for events in the BLE stack. The handler receives two arguments, event (see the event codes below) and data (which is an event-specific tuple of values).

The optional trigger parameter allows you to set a mask of the events the program is interested in. The default is all events.

Note: the items in the addr, adv_data and uuid tuples are reference data managed by the ubluetooth module (i.e. the same instance will be reused across multiple calls to the event handler). If your program wants to use this data outside the handler, it must first copy them, for example using bytes(addr) or bluetooth.UUID(uuid).

An event handler showing all possible events:

def bt_irq(event, data):
    if event == _IRQ_CENTRAL_CONNECT:
        # A central has connected to this peripheral
        conn_handle, addr_type, addr = data
    elif event == _IRQ_CENTRAL_DISCONNECT:
        # A central has disconnected from this peripheral
        conn_handle, addr_type, addr = data
    elif event == _IRQ_GATTS_WRITE:
        # A central has written to this characteristic or descriptor
        conn_handle, attr_handle = data
    elif event == _IRQ_GATTS_READ_REQUEST:
        # A central has issued a read request. Note: this is a hardware IRQ
        # Return None to deny the read operation
        # Note: this event is not supported on ESP32.
        conn_handle, attr_handle = data
    elif event == _IRQ_SCAN_RESULT:
        # The result of a scan
        addr_type, addr, connectable, rssi, adv_data = data
    elif event == _IRQ_SCAN_COMPLETE:
        # The scan duration finished or was manually stopped
        pass
    elif event == _IRQ_PERIPHERAL_CONNECT:
        #  gap_connect() connection succeeded
        conn_handle, addr_type, addr = data
    elif event == _IRQ_PERIPHERAL_DISCONNECT:
        # A connected peripheral has disconnected
        conn_handle, addr_type, addr = data
    elif event == _IRQ_GATTC_SERVICE_RESULT:
        # Each service found by calling gattc_discover_services()
        conn_handle, start_handle, end_handle, uuid = data
    elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
        # Each characteristic found by calling gattc_discover_services()
        conn_handle, def_handle, value_handle, properties, uuid = data
    elif event == _IRQ_GATTC_DESCRIPTOR_RESULT:
        # Each descriptor found by calling gattc_discover_descriptors()
        conn_handle, dsc_handle, uuid = data
    elif event == _IRQ_GATTC_READ_RESULT:
        # gattc_read() has completed
        conn_handle, value_handle, char_data = data
    elif event == _IRQ_GATTC_WRITE_STATUS:
        # gattc_write() has completed
        conn_handle, value_handle, status = data
    elif event == _IRQ_GATTC_NOTIFY:
        # A peripheral has issued a notify request
        conn_handle, value_handle, notify_data = data
    elif event == _IRQ_GATTC_INDICATE:
        # A peripheral has issued an indicate request
        conn_handle, value_handle, notify_data = data

Event codes:

from micropython import const
_IRQ_CENTRAL_CONNECT                 = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT              = const(1 << 1)
_IRQ_GATTS_WRITE                     = const(1 << 2)
_IRQ_GATTS_READ_REQUEST              = const(1 << 3)
_IRQ_SCAN_RESULT                     = const(1 << 4)
_IRQ_SCAN_COMPLETE                   = const(1 << 5)
_IRQ_PERIPHERAL_CONNECT              = const(1 << 6)
_IRQ_PERIPHERAL_DISCONNECT           = const(1 << 7)
_IRQ_GATTC_SERVICE_RESULT            = const(1 << 8)
_IRQ_GATTC_CHARACTERISTIC_RESULT     = const(1 << 9)
_IRQ_GATTC_DESCRIPTOR_RESULT         = const(1 << 10)
_IRQ_GATTC_READ_RESULT               = const(1 << 11)
_IRQ_GATTC_WRITE_STATUS              = const(1 << 12)
_IRQ_GATTC_NOTIFY                    = const(1 << 13)
_IRQ_GATTC_INDICATE                  = const(1 << 14)

To save space in the firmware, these constants are not included in ubluetooth. Add the ones you need from the list above to your program.

Advertiser

BLE.gap_advertise(interval_us, adv_data=None, resp_data=None, connectable=True)

Start advertising at the specified interval (in microseconds). The interval will be rounded to the nearest 625 microseconds. To stop advertising, set interval_us to None.

adv_data and resp_data can be any buffer type (e.g. bytes, bytearray, str). adv_data is included in all advertisements, and resp_data is sent in response to an active scan.

Note: if adv_data (or resp_data) is None, the data passed to the previous gap_advertise call will be reused. This way, the advertiser can resume advertising using gap_advertise(interval_us). To clear the advertising payload, pass an empty bytes, i.e. b’’.

Scanner

BLE.gap_scan(duration_ms[, interval_us][, window_us])

Run a scan operation that lasts for the specified duration (in milliseconds).

To scan indefinitely, set duration_ms to 0. To stop scanning, set duration_ms to None.

Use interval_us and window_us to optionally configure the duty cycle. The scanner will run for window_us microseconds every interval_us microseconds, for a total duration of duration_ms milliseconds. The default interval and window are 1.28 seconds and 11.25 milliseconds respectively.

For each scan result, the _IRQ_SCAN_RESULT event will be raised.

When scanning stops (due to the duration ending or an explicit stop), the _IRQ_SCAN_COMPLETE event will be raised.

Peripheral (GATT Server)

A BLE peripheral has a set of registered services. Each service may contain characteristics, and each characteristic has a value. Characteristics can also contain descriptors, which themselves have values.

These values are stored locally and accessed via a “value handle” generated during service registration. They can also be read or written by a remote central device. In addition, a peripheral can “notify” a characteristic to a connected central device via the connection handle.

The default maximum for characteristics and descriptors is 20 bytes. Anything written to them by a central device will be truncated to this length. However, any local write operation will increase the maximum size, so if you want to write longer data, use gatts_write after registration. For example, gatts_write(char_handle, bytes(100))

BLE.gatts_register_services(services_definition)

Configure the peripheral with the specified services, replacing all existing services.

services_definition is a list of services, where each service is a two-element tuple containing a UUID and a list of characteristics.

Each characteristic is a 2- or 3-element tuple containing a UUID, a flags value, and an optional list of descriptors.

Each descriptor is a two-element tuple containing a UUID and a flags value.

flags is a bitwise OR combination of ubluetooth.FLAG_READ, ubluetooth.FLAG_WRITE and ubluetooth.FLAG_NOTIFY. The values are defined as follows:

The return value is a list of tuples (one element per service) (each element is a value handle). The characteristic and descriptor handles are flattened into the same tuple in the order they are defined.

The following example registers two services (Heart Rate, and Nordic UART):

HR_UUID = ubluetooth.UUID(0x180D)
HR_CHAR = (ubluetooth.UUID(0x2A37), ubluetooth.FLAG_READ | ubluetooth.FLAG_NOTIFY,)
HR_SERVICE = (HR_UUID, (HR_CHAR,),)
UART_UUID = ubluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')
UART_TX = (ubluetooth.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'), ubluetooth.FLAG_READ | ubluetooth.FLAG_NOTIFY,)
UART_RX = (ubluetooth.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'), ubluetooth.FLAG_WRITE,)
UART_SERVICE = (UART_UUID, (UART_TX, UART_RX,),)
SERVICES = (HR_SERVICE, UART_SERVICE,)
( (hr,), (tx, rx,), ) = bt.gatts_register_services(SERVICES)

These three value handles (hr, tx, rx) can be used with gatts_read, gatts_write, and gatts_notify.

Note: advertising must be stopped before registering services.

BLE.gatts_read(value_handle)

Read the local value handle (the value is written by gatts_write or by a remote central device).

BLE.gatts_write(value_handle, data)

Write the local value handle; the value can be read by a central device.

BLE.gatts_notify(conn_handle, value_handle[, data])

Notify a connected central device that this value has changed, and that it should issue a read of the current value of this peripheral.

If data is specified, the value is sent to the central device as part of the notification, thus avoiding the need for a separate read request. Note that this does not update the stored local value.

BLE.gatts_set_buffer(value_handle, len, append=False)

Set the internal buffer size (in bytes). This limits the maximum value that can be received. The default is 20. Setting append to True will append all remote writes to the current value instead of replacing it. This allows buffering up to len bytes. When using gatts_read, the value will be cleared after reading. This feature is useful when implementing things like the Nordic UART service.

Central (GATT Client)

BLE.gap_connect(addr_type, addr, scan_duration_ms=2000)

Connect to a peripheral. On success, the _IRQ_PERIPHERAL_CONNECT event will be triggered.

BLE.gap_disconnect(conn_handle)

Disconnect the specified connection handle. On success, the _IRQ_PERIPHERAL_DISCONNECT event will be triggered. Return False if the connection handle is not connected, otherwise return True.

BLE.gattc_discover_services(conn_handle)

Query the services of a connected peripheral.

For each service discovered, the _IRQ_GATTC_SERVICE_RESULT event will be triggered.

BLE.gattc_discover_characteristics(conn_handle, start_handle, end_handle)

Query the characteristics within the specified range on a connected peripheral. For each characteristic discovered, the _IRQ_GATTC_CHARACTERISTIC_RESULT event will be triggered.

BLE.gattc_discover_descriptors(conn_handle, start_handle, end_handle)

Query the descriptors within the specified range on a connected peripheral.

For each descriptor discovered, the _IRQ_GATTC_DESCRIPTOR_RESULT event will be triggered.

BLE.gattc_read(conn_handle, value_handle)

Issue a remote read to a connected peripheral to obtain the specified characteristic or descriptor handle.

On success, the _IRQ_GATTC_READ_RESULT event will be triggered.

BLE.gattc_write(conn_handle, value_handle, data, mode=0)

Issue a remote write to a connected peripheral for the specified characteristic or descriptor handle.

  • mode

    • mode=0 (default) is a write-without-response operation: the write will be sent to the remote peripheral, but no acknowledgment is returned and no event is raised.

    • mode=1 is a write-with-response: it requests the remote peripheral to send a response/acknowledgment that it has received the data.

If a response is received from the remote peripheral, the _IRQ_GATTC_WRITE_STATUS event will be triggered.

UUID Class

Constructors

class ubluetooth.UUID(value)

Create a UUID instance with the specified value.

The value can be:

  • A 16-bit integer. For example 0x2908.

  • A 128-bit UUID string. For example '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'.

Constants

ubluetooth.FLAG_READ
ubluetooth.FLAG_WRITE
ubluetooth.FLAG_NOTIFY
ble_advertising.py (BLE advertising)
 1# Helpers for generating BLE advertising payloads.
 2
 3from micropython import const
 4import struct
 5import bluetooth
 6
 7# Advertising payloads are repeated packets of the following form:
 8#   1 byte data length (N + 1)
 9#   1 byte type (see constants below)
10#   N bytes type-specific data
11
12_ADV_TYPE_FLAGS = const(0x01)
13_ADV_TYPE_NAME = const(0x09)
14_ADV_TYPE_UUID16_COMPLETE = const(0x3)
15_ADV_TYPE_UUID32_COMPLETE = const(0x5)
16_ADV_TYPE_UUID128_COMPLETE = const(0x7)
17_ADV_TYPE_UUID16_MORE = const(0x2)
18_ADV_TYPE_UUID32_MORE = const(0x4)
19_ADV_TYPE_UUID128_MORE = const(0x6)
20_ADV_TYPE_APPEARANCE = const(0x19)
21
22
23# Generate a payload to be passed to gap_advertise(adv_data=...).
24def advertising_payload(limited_disc=False, br_edr=False, name=None, services=None, appearance=0):
25    payload = bytearray()
26
27    def _append(adv_type, value):
28        nonlocal payload
29        payload += struct.pack('BB', len(value) + 1, adv_type) + value
30
31    _append(_ADV_TYPE_FLAGS, struct.pack('B', (0x01 if limited_disc else 0x02) + (0x00 if br_edr else 0x04)))
32
33    if name:
34        _append(_ADV_TYPE_NAME, name)
35
36    if services:
37        for uuid in services:
38            b = bytes(uuid)
39            if len(b) == 2:
40                _append(_ADV_TYPE_UUID16_COMPLETE, b)
41            elif len(b) == 4:
42                _append(_ADV_TYPE_UUID32_COMPLETE, b)
43            elif len(b) == 16:
44                _append(_ADV_TYPE_UUID128_COMPLETE, b)
45
46    # See org.bluetooth.characteristic.gap.appearance.xml
47    _append(_ADV_TYPE_APPEARANCE, struct.pack('<h', appearance))
48
49    return payload
50
51
52def decode_field(payload, adv_type):
53    i = 0
54    result = []
55    while i + 1 < len(payload):
56        if payload[i + 1] == adv_type:
57            result.append(payload[i + 2:i + payload[i] + 1])
58        i += 1 + payload[i]
59    return result
60
61
62def decode_name(payload):
63    n = decode_field(payload, _ADV_TYPE_NAME)
64    return str(n[0], 'utf-8') if n else ''
65
66
67def decode_services(payload):
68    services = []
69    for u in decode_field(payload, _ADV_TYPE_UUID16_COMPLETE):
70        services.append(bluetooth.UUID(struct.unpack('<h', u)[0]))
71    for u in decode_field(payload, _ADV_TYPE_UUID32_COMPLETE):
72        services.append(bluetooth.UUID(struct.unpack('<d', u)[0]))
73    for u in decode_field(payload, _ADV_TYPE_UUID128_COMPLETE):
74        services.append(bluetooth.UUID(u))
75    return services
76
77
78def demo():
79    payload = advertising_payload(name='micropython', services=[bluetooth.UUID(0x181A), bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')])
80    print(payload)
81    print(decode_name(payload))
82    print(decode_services(payload))
83
84if __name__ == '__main__':
85    demo()
This example demonstrates a simple temperature sensor peripheral
 1# This example demonstrates a simple temperature sensor peripheral.
 2#
 3# The sensor's local value updates every second, and it will notify
 4# any connected central every 10 seconds.
 5
 6import bluetooth
 7import random
 8import struct
 9import time
10from ble_advertising import advertising_payload
11
12from micropython import const
13_IRQ_CENTRAL_CONNECT                 = const(1 << 0)
14_IRQ_CENTRAL_DISCONNECT              = const(1 << 1)
15
16# org.bluetooth.service.environmental_sensing
17_ENV_SENSE_UUID = bluetooth.UUID(0x181A)
18# org.bluetooth.characteristic.temperature
19_TEMP_CHAR = (bluetooth.UUID(0x2A6E), bluetooth.FLAG_READ|bluetooth.FLAG_NOTIFY,)
20_ENV_SENSE_SERVICE = (_ENV_SENSE_UUID, (_TEMP_CHAR,),)
21
22# org.bluetooth.characteristic.gap.appearance.xml
23_ADV_APPEARANCE_GENERIC_THERMOMETER = const(768)
24
25class BLETemperature:
26    def __init__(self, ble, name='mpy-temp'):
27        self._ble = ble
28        self._ble.active(True)
29        self._ble.irq(handler=self._irq)
30        ((self._handle,),) = self._ble.gatts_register_services((_ENV_SENSE_SERVICE,))
31        self._connections = set()
32        self._payload = advertising_payload(name=name, services=[_ENV_SENSE_UUID], appearance=_ADV_APPEARANCE_GENERIC_THERMOMETER)
33        self._advertise()
34
35    def _irq(self, event, data):
36        # Track connections so we can send notifications.
37        if event == _IRQ_CENTRAL_CONNECT:
38            conn_handle, _, _, = data
39            self._connections.add(conn_handle)
40        elif event == _IRQ_CENTRAL_DISCONNECT:
41            conn_handle, _, _, = data
42            self._connections.remove(conn_handle)
43            # Start advertising again to allow a new connection.
44            self._advertise()
45
46    def set_temperature(self, temp_deg_c, notify=False):
47        # Data is sint16 in degrees Celsius with a resolution of 0.01 degrees Celsius.
48        # Write the local value, ready for a central to read.
49        self._ble.gatts_write(self._handle, struct.pack('<h', int(temp_deg_c * 100)))
50        if notify:
51            for conn_handle in self._connections:
52                # Notify connected centrals to issue a read.
53                self._ble.gatts_notify(conn_handle, self._handle)
54
55    def _advertise(self, interval_us=500000):
56        self._ble.gap_advertise(interval_us, adv_data=self._payload)
57
58
59def demo():
60    ble = bluetooth.BLE()
61    temp = BLETemperature(ble)
62
63    t = 25
64    i = 0
65
66    while True:
67        # Write every second, notify every 10 seconds.
68        i = (i + 1) % 10
69        temp.set_temperature(t, notify=i == 0)
70        # Random walk the temperature.
71        t += random.uniform(-0.5, 0.5)
72        time.sleep_ms(1000)
73
74
75if __name__ == '__main__':
76    demo()