【HarmonyOS】鸿蒙应用低功耗蓝牙BLE的使用心得 (三)

【HarmonyOS】鸿蒙应用低功耗蓝牙BLE的使用心得 (三)

一、前言


目前鸿蒙最新系统,经过测试还有两个BLE相关Bug正在修复:

1.获取本地设备蓝牙名称,会为空,只有点击到设置蓝牙中查看后,该接口才能获取到值

2.建立BLE链接后,断开链接,返回的状态没有已断开,只有断开中

鸿蒙相对于Android和IOS而言,对于蓝牙接口的划分其实非常友好,使用也很简单。不需要你套娃一样生成多个对象,蓝牙操作对象,例如GATT都是单例的形式,直接调用即可,例如:

dart 复制代码
	// 通过ble就可以直接操作低功耗蓝牙相关接口
    this.gattClient = ble.createGattClientDevice(peerDevice);
    try {
      this.gattClient.connect(); 
    } catch (err) {
      console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }

三、BLE低功耗蓝牙DEMO项目示例参考:

HaronyOS+BLE蓝牙DEMO

实现了BLE蓝牙完整的交互过程:

1.管理蓝牙的开启和关闭

2.外围设备的服务创建,广播等

3.中央设备的扫描,链接,读取特征和描述等

ScanResultPage .ets

dart 复制代码
import { ArrayList, HashMap } from '@kit.ArkTS'
import { BleDeviceInfo } from '../bean/BleDeviceInfo'
import { promptAction } from '@kit.ArkUI';
import { EventHubUtils } from '../utils/EventHubUtils';
import { BLEMgr } from '../mgr/BLEMgr';

@Entry
@Component
struct ScanResultPage {

  private mBLEMgr: BLEMgr = new BLEMgr();
  private mCacheMap: HashMap<string, string> = new HashMap();
  @State connStr: string = "";
  @State optionSelect: number = -1;

  aboutToAppear(): void {
    EventHubUtils.getEventHub().on("ScanRes", this.onScanRes);
    EventHubUtils.getEventHub().on("ConnStateChange", this.onConnStateChange);

  }

  aboutToDisappear(): void {
    EventHubUtils.getEventHub().off("ScanRes", this.onScanRes);
    EventHubUtils.getEventHub().off("ConnStateChange", this.onConnStateChange);
  }

  onConnStateChange = (state: string)=>{
    if(state == "CONNECTING"){
      this.connStr = "连接中";
    }else if(state == "CONNECTED"){
      this.connStr = "已连接";
      // 进行设备的服务查询
      this.mBLEMgr.discoverServices();
    }else if(state == "DISCONNECTING"){
      this.connStr = "断开中";
    }else{
      this.connStr = "断开连接";
      setTimeout(()=>{
        this.optionSelect = -1;
      }, 2000);
    }
  }

  onScanRes = (info: BleDeviceInfo)=>{
    let deviceId: string = info.DeviceData?.deviceId ?? "";
    if(!this.mCacheMap.hasKey(deviceId)){
      this.mCacheMap.set(deviceId, deviceId);
      this.mListDeviceInfo.push(info);
    }
  }

  @State mListDeviceInfo: Array<BleDeviceInfo> = new Array();

  @Builder ListView(){
    List() {
      ForEach(this.mListDeviceInfo, (item: BleDeviceInfo, index: number) => {
        ListItem() {
          Column(){
            Text("设备ID: " + item.DeviceData?.deviceId).fontSize(px2fp(52)).fontColor(Color.White).width('100%')
            Text("设备名: " + item.DeviceData?.deviceName).fontSize(px2fp(52)).fontColor(Color.White).width('100%')
            Text("RSSI: " + item.DeviceData?.rssi).fontSize(px2fp(52)).fontColor(Color.White).width('100%')
            Text(item.DeviceData?.connectable ? "连接状态: 可连接" : "连接状态: 不可连接").fontSize(px2fp(52)).fontColor(Color.White).width('100%')
            if(this.optionSelect == index){
              Row(){
                Button(this.connStr).backgroundColor(Color.Yellow).fontColor(Color.Blue)
                  .onClick(()=>{
                    // 断开
                    AlertDialog.show({
                      title:"BLE断开",
                      message:"是否选择" + item.DeviceData?.deviceName + "进行BLE断开?",
                      autoCancel: true,
                      primaryButton: {
                        value:"确定",
                        action:()=>{
                          promptAction.showToast({ message: item.DeviceData?.deviceName + " 断开ing!"});
                          this.mBLEMgr.stopConnect();
                        }
                      },
                      secondaryButton: {
                        value:"取消",
                        action:()=>{
                          promptAction.showToast({ message: "取消!"});
                        }
                      },
                      cancel:()=>{
                        promptAction.showToast({ message: "取消!"});
                      }
                    });
                  })
                if(this.connStr == "已连接"){
                  Button("读取特征值").backgroundColor(Color.Yellow).fontColor(Color.Blue)
                    .onClick(()=>{
                      this.mBLEMgr.getClient().readCharacteristicValue();
                    }).margin({ left: px2vp(10) })

                  Button("读取描述").backgroundColor(Color.Yellow).fontColor(Color.Blue)
                    .onClick(()=>{
                      this.mBLEMgr.getClient().readDescriptorValue();
                    }).margin({ left: px2vp(10) })
                }
              }
              .width("100%")
            }
            Divider().height(px2vp(1)).width("100%")
          }
          .padding({
            left: px2vp(35),
            right: px2vp(35)
          })
          .width('100%')
          .height(px2vp(450))
          .justifyContent(FlexAlign.Start)
          .onClick(()=>{
            // 点击选择处理配对
            AlertDialog.show({
              title:"BLE连接",
              message:"是否选择" + item.DeviceData?.deviceName + "进行BLE连接?",
              autoCancel: true,
              primaryButton: {
                value:"确定",
                action:()=>{
                  promptAction.showToast({ message: item.DeviceData?.deviceName + " 连接ing!"});
                  this.mBLEMgr.startConnect(item.DeviceData?.deviceId);
                  this.optionSelect = index;
                }
              },
              secondaryButton: {
                value:"取消",
                action:()=>{
                  promptAction.showToast({ message: "取消!"});
                }
              },
              cancel:()=>{
                promptAction.showToast({ message: "取消!"});
              }
            });
          })
        }
      }, (item: string, index: number) => JSON.stringify(item) + index)
    }
    .width('100%')
  }

  build() {
    Column() {
      this.ListView()
    }
    .height('100%')
    .width('100%')
    .backgroundColor(Color.Blue)
  }
}

完整DEMO下载地址

相关推荐
问道飞鱼4 分钟前
【移动端知识】移动端多 WebView 互访方案:Android、iOS 与鸿蒙实现
android·ios·harmonyos·多webview互访
周胡杰1 小时前
鸿蒙加载预置数据库-关系型数据库-如何读取本地/预制数据库
数据库·华为·harmonyos·鸿蒙
脑子缺根弦2 小时前
融合优势:SIP 广播对讲联动华为会议 全场景沟通响应提速
华为·音视频·广播对讲系统
迷曳11 小时前
27、鸿蒙Harmony Next开发:ArkTS并发(Promise和async/await和多线程并发TaskPool和Worker的使用)
前端·华为·多线程·harmonyos
呆呆的小鳄鱼15 小时前
牛客:HJ24 合唱队[华为机考][最长递增子集][动态规划]
算法·华为·动态规划
迷曳16 小时前
24、鸿蒙Harmony Next开发:不依赖UI组件的全局自定义弹出框 (openCustomDialog)
dialog·前端·ui·harmonyos·鸿蒙
NoirSeeker16 小时前
在windows平台上基于OpenHarmony sdk编译三方库并暴露给ArkTS使用(详细)
c++·windows·arkts·鸿蒙·交叉编译
DC_BLOG17 小时前
OSPFv3中LSA参数
运维·服务器·华为·智能路由器·huawei
平谷一勺1 天前
鸿蒙状态栏操作
华为·harmonyos·沉浸式状态栏
博睿谷IT99_1 天前
入门华为人工智能,HCIA/HCIP/HCIE该怎么选?
人工智能·华为·华为认证