小程序如何延迟异步获取蓝牙数据(wx.onBLECharacteristicValueChang)?
有这样一个业务场景: 点击按钮,小程序通过蓝牙连接到血压测量设备,需要在血压测量完成之后,再去读取血压测量设备返回的数据。 现在的情况是在连接成功之后,就去读数据(这一步还没有测量数据,所以读不到),请问有提供轮询或异步监听的事件函数吗? 部分代码如下: // 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
getBLEDeviceCharacteristics(deviceId, serviceId) {
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
console.log('getBLEDeviceCharacteristics success', res.characteristics)
for (let i = 0; i < res.characteristics.length; i++) {
const item = res.characteristics[i]
console.log('iii-item', item)
if (item.properties.read) {
wx.readBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: item.uuid,
success: (res) => {
console.log('readBLECharacteristicValue--res', res)
}
})
}
if (item.properties.notify || item.properties.indicate) {
console.log('notify')
wx.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId: item.uuid,
state: true
})
}
}
},
fail(res) {
console.error('getBLEDeviceCharacteristics', res)
}
})
// 操作之前先监听,保证第一时间获取数据
wx.onBLECharacteristicValueChange((characteristic) => {
console.log('onBLECharacteristicValueChange-characteristic', characteristic)
const idx = inArray(this.chs, 'uuid', characteristic.characteristicId)
if (idx === -1) {
this.$set(this.chs, this.chs.length, {
uuid: characteristic.characteristicId,
value: ab2hex(characteristic.value)
})
} else {
this.$set(this.chs, idx, {
uuid: characteristic.characteristicId,
value: ab2hex(characteristic.value)
})
}
console.log('this.chs', this.chs)
})
},