一、这里我先把我遇到的两个天坑在这里先说明一下:
1、根据锁的开发文档描述:读特征值是000036F6-0000-1000-8000-00805F9B34FB,但是在iOS上设置通知一直报10008错误码!实际开发下来发现:在Android手机是使用这个,在iOS手机确是0000FEC8-0000-1000-8000-00805F9B34FB这个问题一直没有搞懂!(上面这两个特征值至是举例)
2、开启读特征值通知成功后发送数据给锁,无法收到锁回复的数据 二、这里就主要总结一下BLE的开发步骤,与蓝牙设备进行交互 第一步:初始化蓝牙模块
1 2 3 4 5 6 7 8 |
wx.openBluetoothAdapter({ success(res) { //开启成功 }, fail(res) { //开启失败 } }) |
第二步:监听寻找到新设备的事件
1 2 3 4 5 |
wx.onBluetoothDeviceFound(function (devices) { var bleArray = devices.devices //这里会收到周边搜索到的蓝牙 } }) |
第三步:开始搜寻附近的蓝牙外围设备
1 2 3 4 5 6 7 8 9 |
wx.startBluetoothDevicesDiscovery({ services: ['FEE7'], success(res) { console.log("搜索蓝牙:", res) }, fail(res) { console.log(res) } }) |
第四步:在onBluetoothDeviceFound中搜索到的蓝牙进行连接
先停止搜索蓝牙
1 2 3 4 5 6 7 8 |
wx.stopBluetoothDevicesDiscovery({ success(res) { //停止搜索蓝牙成功 }, fail(res) { //停止搜索蓝牙失败 } }) |
再连接蓝牙
1 2 3 4 5 6 7 8 9 10 |
wx.createBLEConnection({ //蓝牙设备ID deviceId: bleDeviceId, success: function (res) { //蓝牙连接成功 }, fail: function (res) { //蓝牙连接失败 } }) |
第五步:获取蓝牙服务ID(一个蓝牙会有多个服务,所以需要取自己需要的服务ID)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
wx.getBLEDeviceServices({ //蓝牙设备ID deviceId: bleDeviceId, success: function (res) { var services = res.services; let bleServiceUUID = ""; for (let i = 0; i < services.length; i++) { if (services[i].uuid.toUpperCase().indexOf("FEE7") != -1) { bleServiceUUID = services[i].uuid; break; } } //获取蓝牙设备服务UUID成功 }, fail(res) { //获取蓝牙设备服务失败 } }) |
第六步:根据蓝牙服务ID获取特征值ID(一个蓝牙服里会有多个特征值ID,所以需要取自己需要的特征值ID)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
wx.getBLEDeviceCharacteristics({ //蓝牙设备ID deviceId: bleDeviceId, //蓝牙服务ID serviceId: bleServiceUUID, success: function (res) { for (let i = 0; i < res.characteristics.length; i++) { let character = res.characteristics[i]; if (character.uuid.toUpperCase().indexOf("36F5") != -1) { //获取写特征值 } if (character.uuid.toUpperCase().indexOf("36F6") != -1) { //读特征值 } } } }); |
这里就会遇到我开头说的第一个问题。然后这里取读、写特征值需要根据你的蓝牙协议文档来
第七步:开启读特征值通知
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
wx.notifyBLECharacteristicValueChange({ state: true, //蓝牙设备ID deviceId: bleDeviceId, //蓝牙服务ID serviceId: bleServiceUUID, //特征值ID characteristicId: uuid, success: function (res) { //开启通知成功 }, fail: function (res) { //开启通知失败 } }); |
第八步:监听读特征值变化也就是收到的蓝牙数据包
1 2 3 |
wx.onBLECharacteristicValueChange(function (res) { //这里坐等数据过来,res.value }) |
第九步:发送数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
wx.writeBLECharacteristicValue({ //蓝牙设备ID deviceId: bleDeviceId, //蓝牙服务ID serviceId: bleServiceUUID, //写特征值ID characteristicId: uuid, //数据ArrayBuffer value: buffer, success(res) { //发送蓝牙数据成功 }, fail(res) { //发送蓝牙数据失败 } }) |
这里就会遇到我开头说的第二个问题。发送了数据无法收到锁的数据,原因就是第八步设置监听变化比发送数据慢,也就是我还没监听你就把数据发出去了,导致设备回的数据包没有收到,所以这里需要在第八步执行后,延时一段时间在发送数据
第十步:释放资源、断开蓝牙、释放蓝牙模块
1 2 3 4 5 6 7 8 9 10 11 12 |
//断开蓝牙连接 wx.closeBLEConnection({ //设备ID deviceId: bleDeviceId, success(res) { } }); //关闭蓝牙模块 wx.closeBluetoothAdapter({ success(res) { } }) |