You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RN CLI连接Pi Pico W时BLE特征UUID缺失问题求助

问题描述

我想用BLE将Pi Pico W连接到React Native CLI应用,原生端使用BLE-PLX库。Pi Pico W上采用了网上常见的BLE示例代码,但在RN应用扫描设备后,无法获取用于收发数据的characteristicUUID。查看ble_simple_peripheral库后发现其中没有配置characteristicUUID的代码,尝试添加自定义UUID但未成功,请问该如何解决?

Pi Pico W端原代码:

# Import necessary modules
from machine import Pin 
import bluetooth
from ble_simple_peripheral import BLESimplePeripheral

# Create a Bluetooth Low Energy (BLE) object
ble = bluetooth.BLE()
# Create an instance of the BLESimplePeripheral class with the BLE object
sp = BLESimplePeripheral(ble,"PICO W")
# Create a Pin object for the onboard LED, configure it as an output
led = Pin("LED", Pin.OUT)
# Initialize the LED state to 0 (off)
led_state = 0

# Define a callback function to handle received data
def on_rx(data):
    print("Data received: ", data)  # Print the received data
    global led_state  # Access the global variable led_state
    if data == b'toggle\r\n':  # Check if the received data is "toggle"
        led.value(not led_state)  # Toggle the LED state (on/off)
        led_state = 1 - led_state  # Update the LED state

# Start an infinite loop
while True:
    if sp.is_connected():  # Check if a BLE connection is established
        sp.on_write(on_rx)  # Set the callback function for data reception

解决步骤

1. 修改ble_simple_peripheral.py库,配置自定义UUID

原库默认使用通用UUID,需要替换为自定义的服务和特征UUID,确保RN端能精准识别。找到库中的UUID定义和服务注册部分,修改如下:

import bluetooth

# 自定义服务和特征UUID(可自行替换为符合规范的128位UUID)
_UUID_SERVICE = bluetooth.UUID("0000FFE0-0000-1000-8000-00805F9B34FB")
_UUID_CHAR = bluetooth.UUID("0000FFE1-0000-1000-8000-00805F9B34FB")

class BLESimplePeripheral:
    def __init__(self, ble, name="PICO"):
        self._ble = ble
        self._ble.active(True)
        self._ble.irq(self._irq)
        # 注册自定义服务
        self._service = self._ble.gatts_register_service(_UUID_SERVICE)
        # 添加自定义特征,配置可写+可通知属性
        self._char = self._ble.gatts_add_char(self._service, _UUID_CHAR,
                                              properties=bluetooth.FLAG_WRITE | bluetooth.FLAG_NOTIFY,
                                              value=b'')
        self._connections = set()
        self._write_callback = None
        # 设置设备广播名称
        self._ble.gap_advertise(100_000, adv_data=self._advertise_payload(name))
    
    # 保留原库中其他方法(_irq、_advertise_payload、is_connected、on_write、send等)

2. 保持Pi Pico W主代码不变

原主代码逻辑无需修改,确保能正常加载修改后的ble_simple_peripheral库即可。

3. React Native端指定UUID进行连接通信

在RN代码中,扫描时指定自定义的服务UUID,连接后直接使用对应的特征UUID进行数据收发:

import { BleManager } from 'react-native-ble-plx';

const bleManager = new BleManager();

// 扫描指定服务UUID的设备
bleManager.startDeviceScan(
  ['0000FFE0-0000-1000-8000-00805F9B34FB'], // 与Pico端一致的服务UUID
  null,
  (error, device) => {
    if (error) {
      console.error('扫描出错:', error);
      return;
    }
    // 匹配目标设备
    if (device.name === 'PICO W') {
      bleManager.stopDeviceScan();
      // 连接设备并发现服务特征
      device.connect()
        .then(connectedDevice => connectedDevice.discoverAllServicesAndCharacteristics())
        .then(device => {
          // 向指定特征写入控制指令
          return device.writeCharacteristicWithResponseForService(
            '0000FFE0-0000-1000-8000-00805F9B34FB', // 服务UUID
            '0000FFE1-0000-1000-8000-00805F9B34FB', // 特征UUID
            Buffer.from('toggle\r\n').toString('base64')
          );
        })
        .catch(err => console.error('连接/通信出错:', err));
    }
  }
);

核心注意点

  • 两端UUID必须完全一致,建议使用标准128位UUID格式
  • 特征属性需包含FLAG_WRITE(支持RN端写入)和FLAG_NOTIFY(支持Pico主动推送数据)
  • 若修改库后仍无法识别,可重启Pi Pico W并清除RN应用的BLE缓存

内容的提问来源于stack exchange,提问作者Aman Goyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 05:55:26