遇到这种东西很蛋疼,文档几乎拉闸几乎靠度娘(谷歌没翻墙,见笑了各位),不过本人头铁,淦就完了!
不多BB切入正题:
原则上来说调用wx.notifyBLECharacteristicValueChange之后就能用wx.onBLECharacteristicValueChange进行回调
代码如下:
//注册通知
notifyBleEvent: function(){
//接收设置是否成功
this.printLog("注册Notice 回调函数");
var that = this;
var thisNotifyDeviceId = that.data.initNotifyDeviceId;
var thisNotifyServiceId = that.data.initNotifyServiceId;
var thisNotifyCharacteristicId = that.data.initNotifyCharacteristicId;
wx.notifyBLECharacteristicValueChange({
deviceId: thisNotifyDeviceId,
serviceId:thisNotifyServiceId,
characteristicId: thisNotifyCharacteristicId,
state: true, //启用Notify功能
success: function(res) {
//订阅通知
that.printLog("测试回调")
that.printLog(res.errMsg)
console.log("Notify:",res.errMsg)
},
fail: function(res){
console.log(res);
that.printLog("特征值Notice 接收数据失败: " + res.errMsg);
}
})
},
wx.notifyBLECharacteristicValueChange代码如下:
notifySuccess:function(){
var that = this;
that.printLog("接收通知")
//注册成功后数据回调
wx.onBLECharacteristicValueChange(function(res){
console.log("收到Notify",res);
console.log("收到Notify数据",that.ab2hex(res.value));
//打印
wx.showModal({
title: '接收的通知',
content: that.ab2hex(res.value),
})
that.setData({
notifyValue:that.ab2hex(res.value)
})
});
},
这两个都是次要的,是个瓜皮都会写,主要点来了::
//写入数据
writeBleEvent: function (){
this.printLog("开始写入值");
var that = this;
var cell = {
"writeValue": that.data.writeValue,
}
//蓝牙设备特征值对应的值,为 16 进制字符串,限制在 20 字节内。超过可使用分包
var buffer = this.string2buffer(JSON.stringify(cell));
setTimeout(function(){
var thisWriteDeviceId = that.data.initWriteDeviceId;
var thisWriteServiceId = that.data.initWriteServiceId;
var thisWriteCharacteristicId = that.data.initWriteCharacteristicId;
wx.writeBLECharacteristicValue({
deviceId: thisWriteDeviceId,
serviceId: thisWriteServiceId,
characteristicId: thisWriteCharacteristicId,
value: buffer,
success: function(res) {
that.printLog(res.errMsg);
that.printLog("发送成功");
},
fail: function(res){
console.log(res);
that.printLog("发送失败." + res.errMsg);
},
complete: function(){
}
}, 1000);
});
},
我这样的流程是能接收到数据回调的,若有不足的地方请大家多多指教,如果还收不到数据,请看传进去的东西是否会有回应,报文对不上是不会发送任何数据的。还有就是如果接受的超过20个字节,会多次接受。
如果还是接受不到数据回调,看下特征值读写和通知是不是都为true ,还是不行的话,要先写入了才会回调的哦