:mod:`ubluetooth` --- Bluetooth Low Energy =========================================== .. module:: ubluetooth :synopsis: Bluetooth Low Energy radio functionality 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:: BLE() Return a BLE object. Configuration ------------- .. method:: 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. .. method:: 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 -------------- .. method:: 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 :mod:`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 :mod:`ubluetooth`. Add the ones you need from the list above to your program. Advertiser ----------------------------- .. method:: 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 ----------------------- .. method:: 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)) .. method:: 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 :data:`ubluetooth.FLAG_READ`, :data:`ubluetooth.FLAG_WRITE` and :data:`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 :meth:`gatts_read `, :meth:`gatts_write `, and :meth:`gatts_notify `. Note: advertising must be stopped before registering services. .. method:: BLE.gatts_read(value_handle) Read the local value handle (the value is written by :meth:`gatts_write ` or by a remote central device). .. method:: BLE.gatts_write(value_handle, data) Write the local value handle; the value can be read by a central device. .. method:: 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. .. method:: 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 :meth:`gatts_read `, the value will be cleared after reading. This feature is useful when implementing things like the Nordic UART service. Central (GATT Client) -------------------------- .. method:: BLE.gap_connect(addr_type, addr, scan_duration_ms=2000) Connect to a peripheral. On success, the ``_IRQ_PERIPHERAL_CONNECT`` event will be triggered. .. method:: 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``. .. method:: 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. .. method:: 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. .. method:: 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. .. method:: 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. .. method:: 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:: 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 --------- .. data:: ubluetooth.FLAG_READ ubluetooth.FLAG_WRITE ubluetooth.FLAG_NOTIFY .. literalinclude:: /_static/products/mpython-s3/_static/examples/ble/ble_advertising.py :caption: ble_advertising.py (BLE advertising) :linenos: .. literalinclude:: /_static/products/mpython-s3/_static/examples/ble/ble_temperature.py :caption: This example demonstrates a simple temperature sensor peripheral :linenos: