OpenHarmony BLE蓝牙连接教程

openharmony 蓝牙模块提供了基础的传统蓝牙能力以及 ble 的扫描、广播等功能。
这里将介绍如何通过 openharmony 提供的 @ohos.bluetooth (蓝牙接口)打开当前设备的蓝牙,关闭蓝牙,以及连接 ble 蓝牙设备。
设备与环境:
设备:九联 s905l3a 机顶盒、开鸿智谷学生卡 ble 蓝牙设备
系统:openharmony 3.2 beta2
sdk:9
逻辑流程
首先机顶盒在开始的时候获取蓝牙相关权限,然后通过 openharmony 提供的蓝牙接口打开蓝牙。
接着订阅发现 ble 设备发现事件,然后通过 openharmony 提供的蓝牙接口开启 ble 设备扫描。
当发现到了 ble 蓝牙设备后,进行上报,ble 设备发现事件触发,获取到来自 ble 设备的广播信息包,然后进行 ble 蓝牙连接。
实现过程
①获取蓝牙相关权限
在使用蓝牙接口之前,首先要让设备获取一下权限:
ohos.permission.use_bluetooth //:允许应用查看蓝牙的配置。
ohos.permission.discover_bluetooth //:允许应用配置本地蓝牙,查找远端设备且与之配对连接。
ohos.permission.location //:允许应用获取设备位置信息。
ohos.permission.manage_bluetooth //:允许应用配对蓝牙设备,并对设备的电话簿或消息进行访问。
打开 deveco studio 3.1.0.200,创建新的 stage 项目,在项目中的 module.json 文件中添加相关权限:
requestpermissions: [      {        name: ohos.permission.use_bluetooth,        reason: $string:grant_use_bluetooth,        usedscene: {          abilities: [            mainability          ],          when: inuse        }      },      {        name: ohos.permission.discover_bluetooth,        reason: $string:grant_discovery_bluetooth,        usedscene: {          abilities: [            mainability          ],          when: inuse        }      },      {        name: ohos.permission.location,        reason: $string:grant_location,        usedscene: {          abilities: [            mainability          ],          when: inuse        }      },      {        name: ohos.permission.manage_bluetooth,        reason: $string:grant_manage_bluetooth,        usedscene: {          abilities: [            mainability          ],          when: inuse        }      }    ]  
②打开设备的蓝牙
首先,通过调用 bluetooth.getstate() 蓝牙接口来获取当前设备蓝牙是否打开,并设置蓝牙开关的标识位 ison。
async abouttoappear() {    // 等待获取蓝牙权限    await globalthis.abilitycontext.requestpermissionsfromuser(['ohos.permission.use_bluetooth', 'ohos.permission.discover_bluetooth', 'ohos.permission.location', 'ohos.permission.manage_bluetooth'])    logger.info(tag, `获取权限  grantpermission,requestpermissionsfromuser,permissionrequestresult`)    // 获取蓝牙状态    let state = bluetooth.getstate()    // 判断当前设备蓝牙是否打开    if (state === bluetooth.bluetoothstate.state_on) {      this.ison = true    }    if (state === bluetooth.bluetoothstate.state_off) {      this.ison = false    }  }     
如果当前设备蓝牙未打开,则通过调用 bluetooth.enablebluetooth() 蓝牙接口来打开蓝牙。
// 打开蓝牙函数  initbluetooth() {     this.enable = bluetooth.enablebluetooth()    // 判断蓝牙是否成功打开    if(this.enable==true){      prompt.showtoast({        message: 'open bluetooth  ' + this.enable,        duration: 2000,      });    }  }     
③注册发现 ble 设备监听器
在设备打开蓝牙之后,通过调用 bluetooth.ble.on('bledevicefind') 蓝牙接口来订阅 ble 设备发现上报事件。 该接口参数如下:
通过注册发现 ble 设备监听器,可以得到发现设备的集合,ble 设备的广播包、地址、信号强度 rssi。
在这里发现获取连接 ble 设备名字的接口 getdevicename 无法成功调用,所以自己通过解析广播包来获取设备名字。
// 订阅ble设备发现上报事件    // 获取到的data包括ble设备的广播包、地址、信号强度rssi    bluetooth.ble.on('bledevicefind', (data) => {      logger.info(tag, `enter on bluetoothbledevicefind`)      logger.info(rgytl 开始扫描设备地址!  1)      if (data !== null && data.length > 0) {        logger.info(rgytl 开始扫描设备地址!  2)        if (this.discoveryblelist.indexof(data[0]) === -1) {          // 把发现的设备地址存入列表          this.discoveryblelist.push(data[0].deviceid)          logger.info(rgytl ---- discoveryblelist = +json.stringify(this.discoveryblelist))          // 读取广播包,解析广播包,得到设备名字,并存入设备列表          var i = 0;          var x = data[0].data[i]          var y = data[0].data[i + 1]          while(y!=0x09 && i+x+2 注意,gattclientdevice 实例只需要创建一个就可以。
// 连接蓝牙let bleconnect = this.bledevice.connect()// 如果连接成功,则把ble设备存入连接成功列表if(bleconnect){    this.deviceblelist.push(item)}  
⑥结尾处理
当不连接 ble 设备的时候,要记得关闭 ble 设备扫描,取消订阅设备发现事件。
取消 ble 设备连接,通过之前创建的 gattclientdevice 实例 bledevice 调用 disconnect() 方法断开连接 ble 设备。
button(断开)              .alignself(itemalign.center)              .onclick(() => {                alertdialog.show({                  title: $r('app.string.disconnect'),                  message: '此操作将会断开该设备的连接',                  primarybutton: {                    value: $r('app.string.cancel'),                    action: () => {                    }                  },                  secondarybutton: {                    value: $r('app.string.confirm'),                    action: () => {                      // 断开连接ble设备                      let bledisconnect = this.bledevice.disconnect()                      if(bledisconnect){                        logger.info(`connectstate bledisconnect = ${json.stringify(bledisconnect)},断开连接`)                        // 移出ble设备连接列表                        this.deviceblelist.pop(item)                      }                    }                  }                })              })    在断开连接、关闭蓝牙之后,可以通过 off(‘connectstatechange’) 取消订阅 ble 连接状态变化事件、bluetooth.ble.stopblescan 停止 ble 扫描、以及  bluetooth.ble.off(‘bledevicefind’) 取消订阅 ble 设备发现上报事件。  
最后通过 bluetooth.disablebluetooth() 关闭蓝牙:
.onchange((ison: boolean) => {             if (ison) {               this.ison = true               this.initbluetooth()             } else {               this.ison = false               bluetooth.ble.off('bledevicefind',()=>{                 logger.info(rgytl 取消ble设备发现订阅!)             })             bluetooth.ble.stopblescan()             this.disable = bluetooth.disablebluetooth()             this.discoverylist = []             this.bleinfo = []             this.blerssi = []             if(this.disable==true){               prompt.showtoast({                 message: 'close bluetooth  ' + this.disable,                 duration: 2000,               });             }           }         })


基于ATmegal6单片机实现SD2200L的TWI接口设计
华为云发布十大新服务
借助 Google 无障碍功能提供更有温度的服务 | Android 开发者故事
中兴通讯将发布三款搭载骁龙888的智能手机
三星新款MiniLED电视曝光
OpenHarmony BLE蓝牙连接教程
3G移动通信对射频电缆的需求详解
虹科案例 | FAS和AFF存储阵列解决方案
河北联通“沃+速”及MBB商务舱解决方案加快5G普及和释放网络价值
英创信息技术国家电网智能电力终端标准显示接口的实现
极客黑科技 与无人机完全不同的飞行体验
物联网水资源监测系统在商业建筑中的4种应用
线性电源LDO基础知识(一):压降Dropout Voltage
估值高达400亿美元的中国铁塔主要的业务范围有哪些?
软开关的基本特性和类型
负电源和正电源电路设计
APEX减速机是哪国品牌?一文快速了解APEX减速机
插电式混合动力的基本概念
德州仪器捐赠100万元,支援四川抗震救灾工作
基于OMAP 4平台的移动开源软件的设计