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

[复制链接]
发表于 2025-12-9 18:01:16 | 显示全部楼层 |阅读模式
【HarmonyOS NEXT】鸿蒙应用低功耗蓝牙BLE的利专心得 (三)

一、媒介



如今鸿蒙最新体系,颠末测试另有两个BLE相干Bug正在修复:
1.获取当地装备蓝牙名称,会为空,只有点击到设置蓝牙中查察后,该接谈锋能获取到值
2.创建BLE链接后,断开链接,返回的状态没有已断开,只有断开中
鸿蒙相对于Android和IOS而言,对于蓝牙接口的分别着实非常友好,利用也很简单。不必要你套娃一样天生多个对象,蓝牙操尴尬刁难象,比方GATT都是单例的情势,直接调用即可,比方:
  1.         // 通过ble就可以直接操作低功耗蓝牙相关接口
  2.     this.gattClient = ble.createGattClientDevice(peerDevice);
  3.     try {
  4.       this.gattClient.connect();
  5.     } catch (err) {
  6.       console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
  7.     }
复制代码
三、BLE低功耗蓝牙DEMO项目示例参考:

HaronyOS+BLE蓝牙DEMO
实现了BLE蓝牙完备的交互过程:
1.管理蓝牙的开启和关闭
2.外围装备的服务创建,广播等
3.中央装备的扫描,链接,读取特性和形貌等
ScanResultPage .ets
  1. import { ArrayList, HashMap } from '@kit.ArkTS'
  2. import { BleDeviceInfo } from '../bean/BleDeviceInfo'
  3. import { promptAction } from '@kit.ArkUI';
  4. import { EventHubUtils } from '../utils/EventHubUtils';
  5. import { BLEMgr } from '../mgr/BLEMgr';
  6. @Entry
  7. @Component
  8. struct ScanResultPage {
  9.   private mBLEMgr: BLEMgr = new BLEMgr();
  10.   private mCacheMap: HashMap<string, string> = new HashMap();
  11.   @State connStr: string = "";
  12.   @State optionSelect: number = -1;
  13.   aboutToAppear(): void {
  14.     EventHubUtils.getEventHub().on("ScanRes", this.onScanRes);
  15.     EventHubUtils.getEventHub().on("ConnStateChange", this.onConnStateChange);
  16.   }
  17.   aboutToDisappear(): void {
  18.     EventHubUtils.getEventHub().off("ScanRes", this.onScanRes);
  19.     EventHubUtils.getEventHub().off("ConnStateChange", this.onConnStateChange);
  20.   }
  21.   onConnStateChange = (state: string)=>{
  22.     if(state == "CONNECTING"){
  23.       this.connStr = "连接中";
  24.     }else if(state == "CONNECTED"){
  25.       this.connStr = "已连接";
  26.       // 进行设备的服务查询
  27.       this.mBLEMgr.discoverServices();
  28.     }else if(state == "DISCONNECTING"){
  29.       this.connStr = "断开中";
  30.     }else{
  31.       this.connStr = "断开连接";
  32.       setTimeout(()=>{
  33.         this.optionSelect = -1;
  34.       }, 2000);
  35.     }
  36.   }
  37.   onScanRes = (info: BleDeviceInfo)=>{
  38.     let deviceId: string = info.DeviceData?.deviceId ?? "";
  39.     if(!this.mCacheMap.hasKey(deviceId)){
  40.       this.mCacheMap.set(deviceId, deviceId);
  41.       this.mListDeviceInfo.push(info);
  42.     }
  43.   }
  44.   @State mListDeviceInfo: Array<BleDeviceInfo> = new Array();
  45.   @Builder ListView(){
  46.     List() {
  47.       ForEach(this.mListDeviceInfo, (item: BleDeviceInfo, index: number) => {
  48.         ListItem() {
  49.           Column(){
  50.             Text("设备ID: " + item.DeviceData?.deviceId).fontSize(px2fp(52)).fontColor(Color.White).width('100%')
  51.             Text("设备名: " + item.DeviceData?.deviceName).fontSize(px2fp(52)).fontColor(Color.White).width('100%')
  52.             Text("RSSI: " + item.DeviceData?.rssi).fontSize(px2fp(52)).fontColor(Color.White).width('100%')
  53.             Text(item.DeviceData?.connectable ? "连接状态: 可连接" : "连接状态: 不可连接").fontSize(px2fp(52)).fontColor(Color.White).width('100%')
  54.             if(this.optionSelect == index){
  55.               Row(){
  56.                 Button(this.connStr).backgroundColor(Color.Yellow).fontColor(Color.Blue)
  57.                   .onClick(()=>{
  58.                     // 断开
  59.                     AlertDialog.show({
  60.                       title:"BLE断开",
  61.                       message:"是否选择" + item.DeviceData?.deviceName + "进行BLE断开?",
  62.                       autoCancel: true,
  63.                       primaryButton: {
  64.                         value:"确定",
  65.                         action:()=>{
  66.                           promptAction.showToast({ message: item.DeviceData?.deviceName + " 断开ing!"});
  67.                           this.mBLEMgr.stopConnect();
  68.                         }
  69.                       },
  70.                       secondaryButton: {
  71.                         value:"取消",
  72.                         action:()=>{
  73.                           promptAction.showToast({ message: "取消!"});
  74.                         }
  75.                       },
  76.                       cancel:()=>{
  77.                         promptAction.showToast({ message: "取消!"});
  78.                       }
  79.                     });
  80.                   })
  81.                 if(this.connStr == "已连接"){
  82.                   Button("读取特征值").backgroundColor(Color.Yellow).fontColor(Color.Blue)
  83.                     .onClick(()=>{
  84.                       this.mBLEMgr.getClient().readCharacteristicValue();
  85.                     }).margin({ left: px2vp(10) })
  86.                   Button("读取描述").backgroundColor(Color.Yellow).fontColor(Color.Blue)
  87.                     .onClick(()=>{
  88.                       this.mBLEMgr.getClient().readDescriptorValue();
  89.                     }).margin({ left: px2vp(10) })
  90.                 }
  91.               }
  92.               .width("100%")
  93.             }
  94.             Divider().height(px2vp(1)).width("100%")
  95.           }
  96.           .padding({
  97.             left: px2vp(35),
  98.             right: px2vp(35)
  99.           })
  100.           .width('100%')
  101.           .height(px2vp(450))
  102.           .justifyContent(FlexAlign.Start)
  103.           .onClick(()=>{
  104.             // 点击选择处理配对
  105.             AlertDialog.show({
  106.               title:"BLE连接",
  107.               message:"是否选择" + item.DeviceData?.deviceName + "进行BLE连接?",
  108.               autoCancel: true,
  109.               primaryButton: {
  110.                 value:"确定",
  111.                 action:()=>{
  112.                   promptAction.showToast({ message: item.DeviceData?.deviceName + " 连接ing!"});
  113.                   this.mBLEMgr.startConnect(item.DeviceData?.deviceId);
  114.                   this.optionSelect = index;
  115.                 }
  116.               },
  117.               secondaryButton: {
  118.                 value:"取消",
  119.                 action:()=>{
  120.                   promptAction.showToast({ message: "取消!"});
  121.                 }
  122.               },
  123.               cancel:()=>{
  124.                 promptAction.showToast({ message: "取消!"});
  125.               }
  126.             });
  127.           })
  128.         }
  129.       }, (item: string, index: number) => JSON.stringify(item) + index)
  130.     }
  131.     .width('100%')
  132.   }
  133.   build() {
  134.     Column() {
  135.       this.ListView()
  136.     }
  137.     .height('100%')
  138.     .width('100%')
  139.     .backgroundColor(Color.Blue)
  140.   }
  141. }
复制代码
完备DEMO下载所在


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表