likes
comments
collection
share

原生微信小程序使用蓝牙协议读取硬件数据

作者站长头像
站长
· 阅读数 19

前言

最近在做公司的自研产品,是一款监测人体睡眠的硬件和配套的小程序,可以实时监测人体心率,呼吸率,睡眠分期,夜间体动,离床分析的数据。 目前硬件传感器只支持蓝牙协议传输数据和发送指令,接下来我将为大家梳理在微信小程序如何使用蓝牙读取硬件设备的数据。

1. 初始化蓝牙模块

wx.openBluetoothAdapter({
      success: (res) => {
          console.log('openBluetoothAdapter', res)
      },
      fail:  (fail)=>{
        wx.showToast({
          title: '请先开启蓝牙',
          icon: 'none',
          duration: 1000
       })
    }
});

2. 搜索蓝牙设备

wx.startBluetoothDevicesDiscovery({
          success: (ress) => {
            console.log("discovery", ress);
            if (ress.errCode == 0) {
              .....
              // errCode为0的话代表搜索成功
            })
       }
     },
});

3. 获取搜索到的蓝牙设备列表

这里建议使用定时器异步获取蓝牙设备列表,搜索完立即获取,获取到的数组为空

setTimeout(() => {
     wx.getBluetoothDevices({
          success: (resu) => {
              console.log('getBluetoothDevices', resu)
                // resu.device 为蓝牙列表
               }
        })
 }, 3000)

4. 连接蓝牙

// 根据设备名称获取蓝牙的deviceId
let k = data.find(item => item.name === 'HLK_B40_0965')
if(k){
    // 将设备id保存起来
    this.setData({
       deviceId :k.deviceId
    })
    wx.showLoading({
        title: '连接中',
      })
    wx.createBLEConnection({
        deviceId: this.data.deviceId,
        timeout: 10000,
        success: (res) => {
            if (res.errCode == 0) {
            console.log('连接成功')
            // 这时候需要及时停止蓝牙设备搜索
            wx.stopBluetoothDevicesDiscovery();
            } else {
            wx.showModal({
              title: '提示',
              content: '连接失败',
              showCancel: false
            })
          }
        },
        fail: (fail) => {
          wx.hideLoading();
          if (res.errCode == 10012) {
            wx.showModal({
              title: '提示',
              content: '连接超时',
              showCancel: false
            })
          }
          console.warn("创建连接失败", fail);
        },
        complete: () => {
          wx.hideLoading();
        }
      })
}

5. 获取蓝牙设备上的服务列表

 wx.getBLEDeviceServices({
     deviceId: this.data.deviceId,
         success: (getServicesRes) => {
              console.log("获取蓝牙低功耗设备所有服务", getServicesRes);
              this.setData({
               services: getServicesRes.services
             })
             console.log("保存的服务列表", this.data.services)
         },
         fail: (fail) => {
              console.warn("获取服务信息失败", fail);
         },
         complete: () => {
           wx.hideLoading();
        }
})
              

6. 获取蓝牙低功耗设备某个服务中的所有特征

// 我们的设备是第一个服务中有传输数据的服务所以这里选择第一个服务的uuid
let service = getServicesRes.services[0].uuid
wx.getBLEDeviceCharacteristics({
     // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立链接
     deviceId: this.data.deviceId,
     // 这里的 serviceId 需要在 wx.getBLEDeviceServices 接口中获取
     serviceId: service,
     success: (ret) => {
         console.log('获取蓝牙低功耗设备某个服务中所有特征', ret)
         let arr = []
         for (var i = 0; i < ret.characteristics.length; i++) {
              console.log('特征值:' + ret.characteristics[i].uuid)
              // 查找所有特征中支持notify功能的特征并保存起来
             if (ret.characteristics[i].properties.notify) {
                 console.log("获取开启notify的ServicweId:", service);
                 console.log("获取开启notify的CharacteristicsId:",ret.characteristics[i].uuid);
                 arr.push({
                   service,
                   characteristicId: ret.characteristics[i].uuid
                 })
              }
           }
              this.setData({
                notify: arr
              })
          console.log('支持notify的服务:', this.data.notify);
         
     },
     fail: (fail) => {
         console.warn("获取特征值信息失败", fail);
     },
     complete: (res) => {
       console.log('获取服务信息完成', res);
     }
})

7. 启用蓝牙低功耗设备特征值变化时的 notify 功能,订阅特征。

wx.notifyBLECharacteristicValueChange({
    state: true, // 启用 notify 功能
    // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId: this.data.deviceId,
    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
    serviceId: this.data.notify[0].service,
    // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
    characteristicId: this.data.notify[0].characteristicId,
    success: (rest) => {
      
    },
    fail: function (fail) {
      console.log(fail.errMsg);
    },
})

8. 监听蓝牙低功耗设备的特征值变化事件并读取数据

蓝牙传输来的数据是ArrayBuffer格式,需要转成16进制字符串

// 官方文档的转换代码
ab2hex(buffer) {
    let hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      (bit) => {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
},
// 监听特征值变化读取数据
wx.onBLECharacteristicValueChange((characteristic) => {
    console.log('characteristic value comed:', this.ab2hex(characteristic.value))
})

结尾

到现在,小程序中初始化设备、搜索设备,展示设备,连接设备,获取设备服务,获取服务特征,读取数据都已经完成,后续持续更新发送指令相关操作。

转载自:https://juejin.cn/post/7255498215012778039
评论
请登录