小程序读取低功耗蓝牙设备的特征值的二进制数据值readBLECharacteristicValue

2018年12月17日 10:37 | 6477次浏览 作者原创 版权保护

wx.readBLECharacteristicValue(Object object)

读取低功耗蓝牙设备的特征值的二进制数据值。注意:必须设备的特征值支持 read 才可以成功调用。

参数

Object object

属性类型默认值必填说明最低版本
deviceIdstring
蓝牙设备 id
serviceIdstring
蓝牙特征值对应服务的 uuid
characteristicIdstring
蓝牙特征值的 uuid
successfunction
接口调用成功的回调函数
failfunction
接口调用失败的回调函数
completefunction
接口调用结束的回调函数(调用成功、失败都会执行)

注意

并行调用多次会存在读失败的可能性。

接口读取到的信息需要在 onBLECharacteristicValueChange 方法注册的回调中获取。


示例代码

// 必须在这里的回调才能获取
wx.onBLECharacteristicValueChange(function (characteristic) {
  console.log('characteristic value comed:', characteristic)
})

wx.readBLECharacteristicValue({
  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  deviceId,
  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
  serviceId,
  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  characteristicId,
  success(res) {
    console.log('readBLECharacteristicValue:', res.errCode)
  }
})


如上述接口使用说明是官方文档介绍的,其实大家根据前17个章节学习,就会很快明白如何使用readBLECharacteristicValue接口,在这里呢,本作者在啰嗦一遍。


参数解释说明

第一、deviceId,在读者可在第5章节学习到如何获取到deviceid,实际上安卓用户的deviceid就是设备的mac地址。

第二、serviceId,也就是设备服务UUID,读者可在第9章学习如何获取serviceId,此服务的UUID可能不止一个,大家谨慎选择,实在不知道是哪一个,可每个都试一遍。

第三、characteristicId,蓝牙特征值的uuid,实际上特征值的uuid是包含在serviceId下的,一个serviceId下面会有多个characteristicId,而characteristicId只能属于一个serviceId。characteristicId的获取可在第10章学习。

第四、readBLECharacteristicValue和onBLECharacteristicValueChange两个接口必须同时配合使用,readBLECharacteristicValue接口读取,onBLECharacteristicValueChange接口接收设备返回的值


实际示例

wx.readBLECharacteristicValue({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId:'09087ABC56A2',
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId:'0000000f-0000-1000-0000-008123456489',
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId: '00000009-0000-1000-0000-0012345678f0',
success(res) {
console.log('电量readBLECharacteristicValue:', res.errCode)
},
fail(res){
console.log('电2量readBLECharacteristicValue:', res.errCode)
}
})

接收设备返回值

wx.onBLECharacteristicValueChange(function (res) {

console.log(res.value)

 
})

说明:readBLECharacteristicValue读取低功耗蓝牙设备的特征值的二进制数据值接口一般用于读取设备电量,电压,风速,沙尘指数,PM2.5指数等实时数据。



小说《我是全球混乱的源头》
此文章本站原创,地址 https://www.vxzsk.com/1936.html   转载请注明出处!谢谢!

感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程