概述
最近这段时间接了一个蓝牙车位锁的项目;项目中包括APP和微信小程序;其中涉及蓝牙部分的功能就是手机连接蓝牙然后通过蓝牙给车位锁发指令控制车位锁开关;更多细节不好透露;毕竟涉及到客户项目这点职业道德还是得守的;我们这里只存技术角度去说;APP部分的就不说了,这里说微信小程序连接蓝牙并且通过蓝牙发送指令
小程序发送蓝牙指令流程
1、 开启蓝牙适配
2、 获取蓝牙适配器状态,判断设备蓝牙是否可用。
3、通过deviceId连接蓝牙
4、发送和接收信息
由于业务是通过扫描二维码后连接蓝牙,所以我这里省去了扫描蓝牙流程,直接通过扫描二维码然后通过二维码中的内容去服务器交互获取deviceId最后直接连接蓝牙
//打开适配器
wx.openBluetoothAdapter({
success: function (res) {console.log("蓝牙适配器打开成功!")//从服务器获取设备idutil.httpClient.httpGet("/parklock/manager/android/ble2/locker!getLockerInfor.do", {lockerId: 20001}, function (data) {that.setData({ webData: data });wx.createBLEConnection({deviceId: that.data.deviceId,success: function (res) {console.log("连接成功", res)wx.getBLEDeviceServices({// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId: that.data.deviceId,success: function (res) {console.log('蓝牙服务:', res.services)wx.getBLEDeviceCharacteristics({// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId: that.data.deviceId,// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取 serviceId: that.data.serviceId,success: function (res1) {console.log('服务设备特:', res1.characteristics)//发送信息给蓝牙设备// 向蓝牙设备发送一个0x00的16进制数据var hex = 'AA5504B10000B5'var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {return parseInt(h, 16)}))var buffer1 = typedArray.bufferconsole.log("发送内容:",buffer1)wx.writeBLECharacteristicValue({deviceId: that.data.deviceId,serviceId: that.data.serviceId,characteristicId: that.data.characteristicId,value: buffer1,success: function (resr) {console.log("发送成功")},fail: function (res2) {console.log("发送失败:", res2)}})}})}})}})});// 接收结果监听wx.onBLECharacteristicValueChange(function (characteristic) {console.log('characteristic value comed:', characteristic)})},fail: function (res) {console.log("蓝牙适配器打开失败!")console.log(res)}});
其中data中定义了serviceId 和 characteristicId
data: {serviceId:"0000FFE0-0000-1000-8000-00805F9B34FB",characteristicId:"0000FFE1-0000-1000-8000-00805F9B34FB",deviceId: "34:15:13:87:DF:60"}
欢迎关注微信公众号【千里授渔】免费获取教学视频。
QQ507545336