HarmonyOS 鸿蒙Next中求BLE示例代码

HarmonyOS 鸿蒙Next中求BLE示例代码 有没有比较完整的例子,可以展示ble功能的。目前是发现监听notify好像需要延时很久才能回。写也没有得到写的结果。有个心率的那个例子,感觉也并不完整。

6 回复

以下是一个相对完整的BLE功能使用示例,展示了如何创建GATT客户端、发现服务、使能通知并监听特征值变化(即Notify功能)。

完整BLE功能示例(包含Notify监听)

import { ble } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';

// 1. 创建GATT客户端设备
let device: ble.GattClientDevice;
try {
  device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); // 替换为目标设备地址
} catch (err) {
  console.error(`Create GATT client failed: ${(err as BusinessError).message}`);
}

// 2. 连接设备并发现服务
try {
  // 获取所有服务
  let services = await device.getServices();
  let targetService = services.find(srv => srv.serviceUuid === '0000180D-0000-1000-8000-00805F9B34FB'); // 例如:心率服务

  if (!targetService) {
    console.error('Target service not found');
    return;
  }

  // 查找目标特征(支持Notify的特征)
  let targetCharacteristic = targetService.characteristics.find(char =>
    char.characteristicUuid === '00002A37-0000-1000-8000-00805F9B34FB' // 例如:心率测量特征
  );

  if (!targetCharacteristic) {
    console.error('Target characteristic not found');
    return;
  }

  // 3. 订阅特征值变化事件(Notify监听)
  device.on('BLECharacteristicChange', (characteristic: ble.BLECharacteristic) => {
    if (characteristic.characteristicUuid === targetCharacteristic.characteristicUuid) {
      let value = new Uint8Array(characteristic.characteristicValue);
      console.info(`Notify received: ${value}`);
      // 处理接收到的数据(例如:更新UI)
    }
  });

  // 4. 启用通知(使能Notify)
  try {
    await device.setCharacteristicChangeNotification(targetCharacteristic, true);
    console.info('Notify enabled successfully');
  } catch (err) {
    console.error(`Enable notify failed: ${(err as BusinessError).message}`);
  }
} catch (err) {
  console.error(`Discover services failed: ${(err as BusinessError).message}`);
}

以下因素可能影响响应速度:

  1. 设备端适配:从设备(Server)的Notify发送频率或硬件处理速度可能较慢。
  2. 系统调度:操作系统对蓝牙栈的调度优先级或电源管理策略可能导致延迟。
  3. API调用顺序:需确保在连接设备、发现服务及特征后再启用Notify(如示例所示)。
  4. 权限与配置:检查是否已申请ohos.permission.ACCESS_BLUETOOTH权限,并确认设备是否支持Notify。
import { bluetooth } from '@kit.ConnectivityKit';
import { BusinessError } from '@ohos.base';

// 定义心率服务UUID
const HEART_RATE_SERVICE = '0000180D-0000-1000-8000-00805F9B34FB';
const HEART_RATE_MEASUREMENT = '00002A37-0000-1000-8000-00805F9B34FB';

class BLEClient {
  private gattClient: bluetooth.GattClientDevice | null = null;

  // 连接设备
  async connectDevice(deviceId: string) {
    try {
      this.gattClient = bluetooth.createGattClientDevice(deviceId);
      await this.gattClient.connect();
      this.registerNotifyListener();
    } catch (err) {
      console.error(`连接失败: ${JSON.stringify(err as BusinessError)}`);
    }
  }

  // 注册Notify监听
  private registerNotifyListener() {
    this.gattClient?.on('BLECharacteristicChange', (characteristic) => {
      if (characteristic.characteristicUuid === HEART_RATE_MEASUREMENT) {
        const heartRate = characteristic.value; // 解析心率数据
        console.log(`实时心率: ${heartRate} bpm`);
      }
    });
  }

  // 写入数据(示例)
  async writeData(serviceUuid: string, charUuid: string, data: Uint8Array) {
    if (!this.gattClient) return;
    
    const characteristic: bluetooth.BLECharacteristic = {
      serviceUuid,
      characteristicUuid: charUuid,
      value: data,
      writeType: bluetooth.WriteType.WRITE_TYPE_DEFAULT
    };

    try {
      await this.gattClient.writeCharacteristicValue(characteristic);
      console.log('写入成功');
    } catch (err) {
      console.error(`写入失败: ${JSON.stringify(err as BusinessError)}`);
    }
  }
}

官方提供的demo

https://gitee.com/harmonyos_samples/BluetoothLowEnergy

官方提供的解决方案

https://developer.huawei.com/consumer/cn/doc/architecture-guides/bluetooth_spp-0000002318232397

HarmonyOS Next的BLE开发示例可在官方资源获取:

  1. DevEco Studio模板创建项目时选择"Empty Ability",在模块级build-profile.json5的module标签内添加"ohos.hardware.bluetooth"权限。

  2. 关键BLE操作代码示例:

// 初始化蓝牙适配器
import bluetooth from '@ohos.bluetooth';
let adapter = bluetooth.getDefaultAdapter();

// 开启蓝牙
adapter.enableBt();

// 扫描设备
let scanFilter = {deviceId: "XX:XX:XX:XX:XX:XX"};
adapter.startBluetoothDiscovery(scanFilter);

// 连接GATT服务
import connectedTag from '@ohos.connectedTag';
let gattClient = connectedTag.createGattClientDevice(deviceId);
gattClient.connect();
  1. 完整示例需参考官方文档中Bluetooth GATT客户端操作流程,包含服务发现、特征值读写等实现。

可以参考HarmonyOS Next官方Sample中的BLE相关示例:

  1. BLE Central示例(ohos.samples.blecentral)展示了完整的BLE客户端操作流程:
  • 设备扫描与过滤
  • 服务/特征值发现
  • 读写特征值操作
  • Notify/Indicate通知监听
  1. 关键代码片段
// 启用Notify监听
characteristic.on('characteristicValueChange', (value: number[]) => {
  // 实时处理心率数据
  console.info('HRM value: ' + value[1]);
});
await ble.startNotifications(characteristic);

// 写入操作需检查写入结果回调
await ble.writeCharacteristicValue(characteristic, value, (result: number) => {
  if (result === 0) {
    console.info('Write success');
  }
});
  1. 延迟问题解决方案
  • 确保在连接建立后等待服务发现完成(约200-500ms)
  • 使用异步队列顺序执行BLE操作
  • 检查设备端的通知间隔设置

建议直接运行官方Sample工程观察完整交互流程,注意BLE操作需要BLUETOOTH权限和运行时授权。

回到顶部