鸿蒙Next蓝牙BLE开发指南

在鸿蒙Next上进行BLE开发时,如何正确配置GATT服务和特征值?遇到设备扫描不到或连接不稳定的问题该怎么排查?官方文档中提到的蓝牙权限和API调用有哪些注意事项?求分享具体的代码示例和调试经验。

2 回复

鸿蒙Next搞BLE开发?简单!先装个DevEco Studio,然后记住:

  1. 设备配网用@ohos.bluetooth
  2. 别忘在config.json里加权限,不然手机变砖(开玩笑的);
  3. 特征值读写记得加回调,不然数据会玩失踪。
    最后,祝你和蓝牙设备白头偕老,永不掉线!

更多关于鸿蒙Next蓝牙BLE开发指南的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


以下是鸿蒙Next(HarmonyOS NEXT)蓝牙BLE开发的关键步骤和示例代码,帮助你快速上手:


1. 权限配置

module.json5 中声明蓝牙权限:

{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.DISCOVER_BLUTOOTH",
        "reason": "扫描蓝牙设备"
      },
      {
        "name": "ohos.permission.MANAGE_BLUTOOTH",
        "reason": "管理蓝牙连接"
      },
      {
        "name": "ohos.permission.LOCATION",
        "reason": "获取设备位置(扫描必需)"
      }
    ]
  }
}

2. 初始化蓝牙适配器

import { bluetooth } from '@kit.ConnectivityKit';

// 检查蓝牙是否开启
async function enableBluetooth() {
  try {
    if (!bluetooth.getState()) {
      await bluetooth.enable();
      console.log('蓝牙已开启');
    }
  } catch (err) {
    console.error('开启蓝牙失败:', err.code);
  }
}

3. 扫描BLE设备

let scanner: bluetooth.BLEScanner;

// 开始扫描
async function startScan() {
  scanner = bluetooth.createBLEScanner();
  scanner.on('bluetoothDeviceFind', (devices: Array<bluetooth.BluetoothDevice>) => {
    devices.forEach(device => {
      console.log(`发现设备: ${device.deviceName}, MAC: ${device.deviceId}`);
    });
  });

  await scanner.startScan();
  console.log('开始扫描');
}

// 停止扫描
function stopScan() {
  scanner.stopScan();
}

4. 连接设备与发现服务

let device: bluetooth.BLEDevice;

async function connect(deviceId: string) {
  device = bluetooth.createBLE(deviceId);
  
  // 监听连接状态
  device.on('BLEConnectionStateChange', (state: boolean) => {
    console.log(state ? '设备已连接' : '设备断开');
  });

  await device.connect();
  const services = await device.getServices(); // 获取GATT服务
  console.log('发现服务数量:', services.length);
}

5. 读写特征值

// 读取特征值
async function readCharacteristic(serviceUuid: string, charUuid: string) {
  const value = await device.readCharacteristicValue(serviceUuid, charUuid);
  console.log(`特征值: ${value}`);
}

// 写入特征值(需确认设备支持写入)
async function writeCharacteristic(serviceUuid: string, charUuid: string, data: Uint8Array) {
  await device.writeCharacteristicValue(serviceUuid, charUuid, data);
}

// 订阅通知(监听设备数据推送)
async function subscribeNotify(serviceUuid: string, charUuid: string) {
  device.on('BLECharacteristicChange', (characteristic: bluetooth.BLECharacteristic) => {
    console.log('收到数据:', characteristic.value);
  });
  await device.setNotifyCharacteristicChanged(serviceUuid, charUuid, true);
}

6. 断开连接

function disconnect() {
  device.disconnect();
  device.off('BLEConnectionStateChange'); // 移除监听
}

关键注意事项

  1. 设备过滤:扫描时可通过 filters 按设备名或服务UUID过滤。
  2. 特征值权限:读写前检查特征的 properties 字段(如 readablewriteable)。
  3. 资源释放:页面销毁时需停止扫描并断开连接。
  4. 兼容性:鸿蒙Next API可能调整,请参考官方文档

通过以上代码,你可以实现BLE设备的扫描、连接、数据读写等核心功能。建议结合具体设备协议(如心率仪、传感器)调整业务逻辑。

回到顶部