如果觉得自己的代码是没有问题,那不妨换个思路,可能是蓝牙设备有问题,并不是你的特征值属性write是true,你就一定可以成功写入。解释下,我学习的时候,一直是连接的我华为手环的蓝牙,因为有特征值的write属性是true,我就没考虑过蓝牙有问题,后来我用其他蓝牙的一个设备(蓝牙调试设备)试了下,发现确实是可以成功写入的。
这是html对应的一个输入框
<input type="text" style="height: 120rpx;width: auto;" confirm-type="send" bindconfirm="sendData" focus="{{showKeyboard}}"/>
这是输入框对应的写入操作的js文件
sendData(e) {
wx.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId:this.data.deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId: this.data.serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId: this.data.characteristicId,
success (res) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
wx.onBLECharacteristicValueChange(function(res) {
console.log('1');
console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
console.log(ab2hex(res.value))
})
}
})
let value = e.detail.value
console.log('要发送的信息是:' + value);
// 向蓝牙设备发送一个0x00的16进制数据
debugger
let buffer = new ArrayBuffer(value.length)
console.log('buffer' + buffer);
let dataView = new DataView(buffer)
console.log('buffer' + dataView);
for (let i = 0; i < value.length; i++) {
dataView.setUint8(i, value.charAt(i).charCodeAt())
}
console.log('buffer' + dataView);
wx.writeBLECharacteristicValue({
// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: this.data.deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId: this.data.serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId: this.data.characteristicId,
// 这里的value是ArrayBuffer类型
value: buffer,
success(res) {
console.log('发送成功');
console.log(buffer);
console.log('writeBLECharacteristicValue success', res.errMsg)
},
fail(res) {
console.log('发送失败');
console.log(buffer);
console.log('writeBLECharacteristicValue fail', res.errMsg)
},
complete(res) {
console.log('writeBLECharacteristicValue complete', res.errMsg)
console.log('该方法完成');
}
})
console.log('1111111111111111');
}
用debugger运行
在输入值的过程中,当我在输入框输入‘1’,value=e.detail.value,value是可以成功拿到值的,然后进入了 writeBLECharacteristicValue方法中,但是不管是success,fail,complete都是没有回调出来
重新连接了蓝牙调试设备后,写入就成功了(设备是被人的,已经还回去了,没有运行图)