ubluetooth — low-level Bluetooth ubluetooth — low-level 蓝牙 =========================================

This module provides an interface to a Bluetooth controller on a board. Currently this supports Bluetooth Low Energy (BLE) in Central, Peripheral, Broadcaster, and Observer roles, and a device may operate in multiple roles concurrently. 这个模块提供了一个接口到蓝牙控制器在一个板。 目前它支持蓝牙低能量(BLE)在中央,外设, 广播者,观察者角色,和一个设备可以在多个操作 同时角色。

This API is intended to match the low-level Bluetooth protocol and provide building-blocks for higher-level abstractions such as specific device types. 此API用于匹配低级蓝牙协议并提供 用于高级抽象(如特定设备类型)的构建块。


This module is still under development and its classes, functions, methods and constants are subject to change.




class BLE

Constructor 构造函数 ———–

class BLE

Returns the singleton BLE object. 返回singleton BLE对象。

Configuration 配置 ————-


Optionally changes the active state of the BLE radio, and returns the current state. 可选地更改BLE无线电台的活动状态,并返回 当前状态。

The radio must be made active before using any other methods on this class. 在使用这个类上的任何其他方法之前,必须使radio处于活动状态。

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

Get or set configuration values of the BLE interface. To get a value the parameter name should be quoted as a string, and just one parameter is queried at a time. To set values use the keyword syntax, and one ore more parameter can be set at a time. 获取或设置BLE接口的配置值。的值 参数名应该用引号括起来作为字符串,只有一个参数是 一次询问。要设置值,使用关键字语法,还有一个ore 参数可以一次设置。

Currently supported values are: 目前支持的值是:

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

  • 'mac': 返回设备的mac地址。如果设备有固定地址 (例如PYBD)然后它将被返回。否则(例如ESP32)是随机的 当BLE接口被激活时,地址将被生成。

  • 'rxbuf': Set the size in bytes of the internal buffer used to store incoming events. This buffer is global to the entire BLE driver and so handles incoming data for all events, including all characteristics. Increasing this allows better handling of bursty incoming data (for example scan results) and the ability for a central role to receive larger characteristic values.

  • 'rxbuf': 设置用于存储的内部缓冲区的字节大小 传入的事件。这个缓冲区对于整个BLE驱动程序是全局的 处理所有事件的传入数据,包括所有特征。 增加这个值可以更好地处理突然传入的数据 示例扫描结果)和中心角色接收的能力 较大的特征值。

Event Handling 事件处理 ————–

BLE.irq(handler, trigger=0xffff)

Registers a callback for events from the BLE stack. The handler takes two arguments, event (which will be one of the codes below) and data (which is an event-specific tuple of values). 为BLE堆栈中的事件注册一个回调。处理程序*需要两个 event``(这将是下面的代码之一)和``data (它是一个特定于事件的值元组)。

The optional trigger parameter allows you to set a mask of events that your program is interested in. The default is all events. 可选的*trigger*参数允许您设置事件的掩码 你的程序感兴趣。默认值是all events。

Note: the addr, adv_data and uuid entries in the tuples are references to data managed by the ubluetooth module (i.e. the same instance will be re-used across multiple calls to the event handler). If your program wants to use this data outside of the handler, then it must copy them first, e.g. by using bytes(addr) or bluetooth.UUID(uuid). 注意:元组中的``addr``, adv_datauuid``条目是 对:mod: `ubluetooth`模块管理的数据的引用 实例将在对事件处理程序的多个调用中重用)。如果 您的程序希望在处理程序之外使用这些数据,那么它必须这样做 首先复制它们,例如使用``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.
        # A中心已经连接到这个外设。
        conn_handle, addr_type, addr = data
    elif event == _IRQ_CENTRAL_DISCONNECT:
        # A central has disconnected from this peripheral.
        # A中心已与此外设断开连接。
        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. Note: this is a hard IRQ.
        # A 中央已经发布了公告。注意:这是一个硬IRQ。
        # Return None to deny the read.
        # 返回None以拒绝读取。
        # Note: This event is not supported on ESP32.
        # 注意:此活动在ESP32上不受支持。
        conn_handle, attr_handle = data
    elif event == _IRQ_SCAN_RESULT:
        # A single scan result.
        # 单一的扫描结果。
        addr_type, addr, connectable, rssi, adv_data = data
    elif event == _IRQ_SCAN_COMPLETE:
        # Scan duration finished or manually stopped.
        # 扫描持续时间已完成或手动停止。
    elif event == _IRQ_PERIPHERAL_CONNECT:
        # A successful gap_connect().
        # 一个成功的gap_connect ()。
        conn_handle, addr_type, addr = data
        # Connected peripheral has disconnected.
        # 已连接的外设已断开。
        conn_handle, addr_type, addr = data
    elif event == _IRQ_GATTC_SERVICE_RESULT:
        # Called for each service found by gattc_discover_services().
        # 对gattc_discover_services()找到的每个服务调用。
        conn_handle, start_handle, end_handle, uuid = data
        # Called for each characteristic found by gattc_discover_services().
        # 对gattc_discover_services()发现的每个特征调用。
        conn_handle, def_handle, value_handle, properties, uuid = data
        # Called for each descriptor found by gattc_discover_descriptors().
        # 对gattc_discover_descriptors()找到的每个描述符调用。
        conn_handle, dsc_handle, uuid = data
    elif event == _IRQ_GATTC_READ_RESULT:
        # A gattc_read() has completed.
        # 一个gattc_read()已经完成。
        conn_handle, value_handle, char_data = data
    elif event == _IRQ_GATTC_WRITE_STATUS:
        # A gattc_write() has completed.
        # gattc_write()已完成。
        conn_handle, value_handle, status = data
    elif event == _IRQ_GATTC_NOTIFY:
        # A peripheral has sent a notify request.
        # 外设发送了一个通知请求。
        conn_handle, value_handle, notify_data = data
    elif event == _IRQ_GATTC_INDICATE:
        # A peripheral has sent an indicate request.
        # 外设发送了指示请求。
        conn_handle, value_handle, notify_data = data

The event codes are:: 事件代码是:

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_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)

In order to save space in the firmware, these constants are not included on the ubluetooth module. Add the ones that you need from the list above to your program. 为了节省固件中的空间,这些常量不包括在固件中 国防部:`ubluetooth`模块。从上面的列表中添加您需要的到您的 程序。

Broadcaster Role (Advertiser)

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

Starts advertising at the specified interval (in microseconds). This interval will be rounded down to the nearest 625us. To stop advertising, set interval_us to None. 以指定的时间间隔(in microseconds)启动广告。这 interval将四舍五入到最接近的625us。停止广告,设置 * interval_us * None

adv_data and resp_data can be any type that implements the buffer protocol (e.g. bytes, bytearray, str). adv_data is included in all broadcasts, and resp_data is send in reply to an active scan. adv_data*和*resp_data*可以是实现缓冲区的任何类型 协议(e.g. ``bytes``, ``bytearray``, ``str``)。 adv_data * 在所有广播,和*resp_data*是在回应一个活动扫描发送。

Note: if adv_data (or resp_data) is None, then the data passed to the previous call to gap_advertise will be re-used. This allows a broadcaster to resume advertising with just gap_advertise(interval_us). To clear the advertising payload pass an empty bytes, i.e. b''. 注意:如果*adv_data* (or resp_data)是``None``,则数据被传递 对``gap_advertise``的调用将被重用。这允许一个 广播公司恢复仅使用``gap_advertise(interval_us)``的广告。 要清除广告有效负载,需要传递一个空的``bytes``, i.e. b''

Observer Role (Scanner)

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

Run a scan operation lasting for the specified duration (in milliseconds). 运行持续指定时间(以**毫**秒为单位)的扫描操作。

To scan indefinitely, set duration_ms to 0. 若要无限扫描,请将*duration_ms*设置为’ ‘ 0 ‘ ‘。

To stop scanning, set duration_ms to None. 若要停止扫描,请将*duration_ms*设置为“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 of duration_ms milliseconds. The default interval and window are 1.28 seconds and 11.25 milliseconds respectively (background scanning). 使用*interval_us*和*window_us*可选地配置负载周期。 扫描器将运行*window_us* micro秒每*interval_us* microseconds for a total of duration_ms milliseconds.默认的 间隔和窗口分别为1.28秒和11.25毫秒


For each scan result, the _IRQ_SCAN_RESULT event will be raised. 对于每个扫描结果,将引发``_IRQ_SCAN_RESULT``事件。

When scanning is stopped (either due to the duration finishing or when explicitly stopped), the _IRQ_SCAN_COMPLETE event will be raised. 扫描停止时(either due to the duration finishing or when explicitly stopped), the ``_IRQ_SCAN_COMPLETE``事件将被引发。

Peripheral Role (GATT Server)

A BLE peripheral has a set of registered services. Each service may contain characteristics, which each have a value. Characteristics can also contain descriptors, which themselves have values. 一个BLE外设有一组注册的服务。每个服务可能包含 特征,每个都有价值。特征还可以包含 描述符本身就有价值。

These values are stored locally, and are accessed by their “value handle” which is generated during service registration. They can also be read from or written to by a remote central device. Additionally, a peripheral can “notify” a characteristic to a connected central via a connection handle. 这些值存储在本地,并通过它们的”value handle”访问 在服务注册期间生成。它们也可以被读或写 通过一个远程的中央设备。此外,外设可以”notify”a 通过连接句柄连接的中心的特性。

Characteristics and descriptors have a default maximum size of 20 bytes. Anything written to them by a central will be truncated to this length. However, any local write will increase the maximum size, so if you want to allow larger writes from a central to a given characteristic, use gatts_write after registration. e.g. gatts_write(char_handle, bytes(100)). 特征和描述符的默认最大大小为20字节。 任何由中央写入的内容都会被截断到这个长度。然而, 任何本地写操作都将增加最大大小,所以如果您想允许更大 从一个中心写到一个给定的特征,使用 gatts_write<BLE.gatts_write>`注册后。 e.g. ``gatts_write(char_handle, bytes(100))`().


Configures the peripheral with the specified services, replacing any 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. services_definition 是一个**service**的列表,其中每个**service**是一个 包含UUID和特征列表的两元素元组。

Each characteristic is a two-or-three-element tuple containing a UUID, a flags value, and optionally a list of descriptors. 每个**characteristic**是一个包含UUID a的2 - 3元素元组 **flags**值和可选的*描述符列表*。

Each descriptor is a two-element tuple containing a UUID and a flags value. 每个**descriptor**是一个包含UUID和**标志的双元素元组价值。

The flags are a bitwise-OR combination of the ubluetooth.FLAG_READ, ubluetooth.FLAG_WRITE and ubluetooth.FLAG_NOTIFY values defined below. **flags**的位或组合 :数据:`ubluetooth.FLAG_READ`:数据:`ubluetooth.FLAG_WRITE`:数据:`ubluetooth.FLAG_NOTIFY`

The return value is a list (one element per service) of tuples (each element is a value handle). Characteristics and descriptor handles are flattened into the same tuple, in the order that they are defined. 返回值是元组(每个元素)的列表(每个服务一个元素) 是一个值句柄)。特征和描述符句柄是扁平的 按照其定义的顺序,将其转换为相同的元组。

The following example registers two services (Heart Rate, and Nordic UART):: 下面的示例注册了两个服务(心率和北欧UART):

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

The three value handles (hr, tx, rx) can be used with 可以使用三个值句柄(hr, tx, rx) gatts_read, gatts_write, and gatts_notify.

Note: Advertising must be stopped before registering services. 注意: 广告必须在注册服务前停止。


Reads the local value for this handle (which has either been written by gatts_write or by a remote central). 读取此句柄的本地值 (which has either been written by gatts_write or by a remote central).

BLE.gatts_write(value_handle, data)

Writes the local value for this handle, which can be read by a central. 写入此句柄的本地值,该值可由中央读取。

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

Notifies a connected central that this value has changed and that it should issue a read of the current value from this peripheral. 通知连接的中心该值已更改且应该更改 从此外设发出当前值的读取。

If data is specified, then the that value is sent to the central as part of the notification, avoiding the need for a separate read request. Note that this will not update the local value stored. 如果指定了*data*,那么该值将作为部分发送到中央 的通知,避免了需要一个单独的读请求。请注意 这将不会更新存储的本地值。

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

Sets the internal buffer size for a value in bytes. This will limit the largest possible write that can be received. The default is 20. 以字节为单位设置值的内部缓冲区大小。这将限制 可能收到的最大写操作。默认值是20。

Setting append to True will make all remote writes append to, rather than replace, the current value. At most len bytes can be buffered in this way. When you use gatts_read, the value will be cleared after reading. This feature is useful when implementing something like the Nordic UART Service. 将*append*设置为``True``将使所有远程写入追加到 比replace,当前值。最多*len*字节可以被缓冲进去 这种方式。当你使用:meth:gatts_read,值将 阅读后即可清除。这个特性在实现某些东西时非常有用 比如北欧UART服务。

Central Role (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 raised. 如果成功,将引发 _IRQ_PERIPHERAL_CONNECT 事件。


Disconnect the specified connection handle. 断开指定的连接句柄。

On success, the _IRQ_PERIPHERAL_DISCONNECT event will be raised. 成功时,将引发’ ‘ _IRQ_PERIPHERAL_DISCONNECT ‘ ‘事件。

Returns False if the connection handle wasn’t connected, and True otherwise. 如果连接句柄未连接,返回``False``,否则``True``。


Query a connected peripheral for its services. 查询已连接外设的服务。

For each service discovered, the _IRQ_GATTC_SERVICE_RESULT event will be raised. 对于发现的每个服务,``_IRQ_GATTC_SERVICE_RESULT``事件将为提高。

BLE.gattc_discover_characteristics(conn_handle, start_handle, end_handle)

Query a connected peripheral for characteristics in the specified range. 查询已连接的外设以获取指定范围内的特征。

For each characteristic discovered, the _IRQ_GATTC_CHARACTERISTIC_RESULT event will be raised. 对于发现的每个特征,``_IRQ_GATTC_CHARACTERISTIC_RESULT``事件将被引发。

BLE.gattc_discover_descriptors(conn_handle, start_handle, end_handle)

Query a connected peripheral for descriptors in the specified range. 查询指定范围内的连接外设的描述符。

For each descriptor discovered, the _IRQ_GATTC_DESCRIPTOR_RESULT event will be raised. 对于发现的每个描述符,``_IRQ_GATTC_DESCRIPTOR_RESULT``事件将会提高。

BLE.gattc_read(conn_handle, value_handle)

Issue a remote read to a connected peripheral for the specified characteristic or descriptor handle. 为指定的连接外设发出远程读取 特征句柄或描述符句柄。

On success, the _IRQ_GATTC_READ_RESULT event will be raised. 成功时,将引发``_IRQ_GATTC_READ_RESULT``事件。

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. 为指定的连接外设发出远程写操作 特征句柄或描述符句柄。

The argument mode specifies the write behaviour, with the currently supported values being: 参数*mode*指定写行为 支持的值:

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

  • ``mode=0``(默认)是写-无-响应:写将 被发送到远程外设,但不进行确认 返回,并且不会引发任何事件。

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

  • ``mode=1``是write-with-response:远程外设是 请求发送一个它收到的响应/确认数据。

If a response is received from the remote peripheral the _IRQ_GATTC_WRITE_STATUS event will be raised. 如果从远程外设接收到响应,则 ``_IRQ_GATTC_WRITE_STATUS``事件将被引发。

class UUID 类UUID ———-

Constructor 构造函数 ———–

class UUID(value)

Creates a UUID instance with the specified value. 创建具有指定**值**的UUID实例。

The value can be either: **值**可以是:

  • A 16-bit integer. e.g. 0x2908.

  • A 128-bit UUID string. e.g. '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'.

Constants 常量 ———