这个蓝牙的坑也是比较多,有api也好改,但是有些坑api根本没有写出来,让我猜?
权限必须打开 "蓝牙权限", "定位权限"
坑1:连接顺序
api的方法都出来了,但是没先写执行什么,后执行什么,按照我的理解写出来了,报错,因为什么呢少写了一个方法直接跳到写一个方法上去了,导致的。 我把流程写一下
wx.openBluetoothAdapter(打开蓝牙适配器)->wx.startBluetoothDevicesDiscovery(准备开始搜寻附近的蓝牙外围设备,为什么要说准备呢 因为这一步不会搜索)->wx.onBluetoothDeviceFound(找到蓝牙,此方法会返回大量蓝牙设备,去重,去空)->(在执行此步骤之前一定要停止搜索,挺耗费系统资源的,一定要停止)wx.createBLEConnection(根据上一步拿到的deviceId进行连接)->wx.onBLEConnectionStateChange(监听蓝牙连接状态 连接上,断开 友好提醒)wx.getBLEDeviceServices(获取蓝牙服务得到uuid)->wx.getBLEDeviceCharacteristics(读取蓝牙特征值 读,写,监听都能拿到)->根据返回的值判断进入wx.readBLECharacteristicValue;wx.writeBLECharacteristicValue;wx.notifyBLECharacteristicValueChange->最后一个是wx.onBLECharacteristicValueChange(当数据过来会在此方法内接收)
坑2.
所有方法都写好了,发送数据后,监听不到数据回来(安卓),需要注意一个地方,wx.writeBLECharacteristicValue 发送数据之后要写一个读取wx.readBLECharacteristicValue 如下:
wx.writeBLECharacteristicValue({
deviceId: _deviceId+'',
serviceId: _serviceId+'',
characteristicId:'000000000',
value: buffer,
success: function(res) {
console.log('writeBLECharacteristicValue success');
},fail(res){
console.log('writeBLECharacteristicValue fail');
}
})
console.log('read特征值:' + that.data._deviceId + ',' + that.data._serviceId + ',' + that.data._readuuid);
wx.readBLECharacteristicValue({
deviceId: that.data._deviceId + '',
serviceId: that.data._serviceId + '',
characteristicId: '000000000',
success: function (res) {
console.log('readBLECharacteristicValue success' )
}, fail(res) {
console.log('readBLECharacteristicValue fail' )
}
})
完成之后,理论上在wx.onBLECharacteristicValueChange就能接收到了 这一步是在wx.getBLEDeviceCharacteristics获取特征值之后notify或者indicate 有个为true才能做wx.notifyBLECharacteristicValueChange,成功之后wx.onBLECharacteristicValueChange设置接收就好了,基本就这些,没写的那些 在api上全能找到。
wx.notifyBLECharacteristicValueChange({
deviceId: deviceid+'',
serviceId: uuids+'',
characteristicId: item.uuid+'',
state: true,
success: function(res) {
console.log('notifyBLECharacteristicValueChange success=' + JSON.stringify(res))
wx.onBLECharacteristicValueChange(function (res) {
console.log('onBLECharacteristicValueChange' + JSON.stringify(res));
let buffer = res.value
let dataView = new DataView(buffer)
let dataResult = []
console.log("拿到的数据")
console.log("dataView.byteLength", dataView.byteLength)
for (let i = 0; i < dataView.byteLength; i++) {
console.log("0x" + dataView.getUint8(i).toString(16))
dataResult.push(dataView.getUint8(i).toString(16))
}
const result = dataResult
})
},fail(res){
console.log('notifyBLECharacteristicValueChange fail=' + JSON.stringify(res))
}
})