小程序蓝牙(低功耗)数据交互

239 阅读1分钟

*需求分析(项目需要和硬件设备的蓝牙连接 实现数据交互)

1.通过初始化蓝牙+发现蓝牙+建立连接
2.建立连接的时候保存蓝牙的设备id
3.连接成功后获取蓝牙的外围服务 在服务列表中 找到对应的设备uuid并保存
4.读取服务的特征值 然后再启用蓝牙特征变化时的notify功能(只有这个启用,才能监听设备的特征的change事件)
5.根据notify的开启 封装要写入的指令 写入服务的特征值 并打印获取监听到的返回值

1.蓝牙建立连接

  1. 初始化
//初始化
            BLEInit(event) {
                let that = this;
                wx.openBluetoothAdapter({
                    success: function(res) {
                        console.log('初始化蓝牙适配器成功')
                        console.log(res);
                        that.$refs.uToast.show({
                            message: '初始化蓝牙适配器成功',
                            type: 'success'
                        })
                    },
                    fail: function(res) {
                        console.log('请打开蓝牙和定位功能')
                        that.$refs.uToast.show({
                            message: '请打开蓝牙和定位功能',
                            type: 'default'
                        })
                    }
                })
            },
  1. 获取蓝牙状态
//获取蓝牙状态
            BLEState() {
                let that = this;
                wx.getBluetoothAdapterState({
                    success: function(res) {
                        //打印相关信息
                        console.log(res, 62);
                        console.log(JSON.stringify(res.errMsg) + "\n蓝牙是否可用:" + res.available);
​
                    },
                    fail: function(res) {
                        console.log(res, 69);
                        //打印相关信息
                        console.log(JSON.stringify(res.errMsg) + "\n蓝牙是否可用:" + res.available);
                    }
                })
            },
  1. 搜索设备
//搜索设备
            BLESearch(event) {
                let that = this;
                wx.startBluetoothDevicesDiscovery({
                    // services: [], //如果填写了此UUID,那么只会搜索出含有这个UUID的设备,建议一开始先不填写
                    success: function(res) {
                        console.log('搜索设备返回' +JSON.stringify(res))
                    }
                })
            },
  1. 获取所有设备
//获取所有设备
            BLEGetDevices(event) {
                let that = this;
                wx.getBluetoothDevices({
                    success: function(res) {
                        that.devices = res.devices.filter(item => item.name !== '未知设备')
                        console.log(that.devices);
                        console.log('搜设备数目:' + res.devices.length)
                        console.log('设备信息:\n' + JSON.stringify(res.devices) + "\n")
                    }
                })
            },
  1. 连接设备
//连接设备
            BLEConnect(id) {
                let that = this;
                console.log(id);
                wx.createBLEConnection({
                    deviceId: id,
                    success: function(res) {
                        console.log(res);
                        console.log('调试信息:' + res.errMsg);
                        that.connectedDeviceId = id
                        that.info = '  调试信息:' + res.errMsg
                        that.$refs.uToast.show({
                            message: '蓝牙连接成功',
                            type: 'success'
                        })
                        that.getBlueTouchServices(id)
                    },
                    fail: function() {
                        console.log("连接失败");
                    },
                })
​
            },
  1. ☠ 连接设备后要关闭搜索所有设备 会对性能有很大的消耗
//停止搜索设备
            BLESearchStop() {
                let that = this;
                wx.stopBluetoothDevicesDiscovery({
                    success: function(res) {
                        console.log("停止搜索" + JSON.stringify(res.errMsg));
                    }
                })
            },

2.获取蓝牙的外围服务

//获取蓝牙外围服务
            getBlueTouchServices(id) {
                let that = this
                wx.getBLEDeviceServices({
                    deviceId: id,
                    success: function(res) {
                        console.log(res)
                        that.buleDeviceServiceId = res.services[1].uuid //存入对应设备的uuid
                        that.getBlueTouchCharacterisitics(id) //特征时需要传入的id
                    }
                })
            },

3.读取服务的特征值 启用蓝牙notify

//读写服务的特征值
            getBlueTouchCharacterisitics(id) {
                let that = this;
                wx.getBLEDeviceCharacteristics({
                    deviceId: id,
                    serviceId: that.buleDeviceServiceId,
                    success: function(res) {
                        console.log(res);
                        that.uniWriteCharacteristicsId = res.characteristics[0].uuid
                        res.characteristics.forEach(v => {
                            let item = v
                            if (item.properties.read) { // 改特征值可读
                                wx.readBLECharacteristicValue({
                                    deviceId: id,
                                    serviceId: that.buleDeviceServiceId,
                                    characteristicId: item.uuid,
                                    success: function(res) {
                                        console.log(res);
                                    }
                                })
                            }
                            if (item.properties.notify || item.properties.indicate) {
                                // 必须先启用 wx.notifyBLECharacteristicValueChange 才能监听到设备 onBLECharacteristicValueChange 事件
                                wx.notifyBLECharacteristicValueChange({
                                    deviceId: id,
                                    serviceId: that.buleDeviceServiceId,
                                    characteristicId: item.uuid,
                                    state: true,
                                    success: function(res) {
                                        console.log(res);
                                        // ArrayBuffer转16进制字符串示例if (res.errCode == 0) {
                                            that.getChange()
                                            //取时间
                                            that.toSendData(41)
                                            //mac地址
                                            // that.toSendData(22)
                                            //个人信息
                                            // that.toSendData(42)
                                        }
                                    }
                                })
                            }
                        })
                    }
                })
            },

4.封装指令

//发送数据包
        toSendData(num){
            let that=this
            let arr = [that.turnHex(num), '00', '00', '00', '00', '00','00', '00', '00', '00','00', '00', '00', '00', '00']
            let count = arr.length / 2;
            if (count.toString().indexOf('.') != -1) {
                count = parseInt(count) + 1 // 有.5就加 1
                count = parseInt(count) // 或者不加
            }
            let crc = 0
            for (let i = 0; i < arr.length; i++) {
                    crc += Number(arr[i])
            }
            arr[15] = crc
            arr=arr.map(Number)
            let buffer = new ArrayBuffer(arr.length)
            let dataView = new DataView(buffer)
            arr.forEach((i, v) => {
                dataView.setUint8(v, i)
            })
            that.sendToBlueTooth(buffer)
        },
            //转16进制
        turnHex(num){
            return parseInt(num,16)
        },

5.写入服务的特征值 并打印获取监听到的返回值

//发送数据
            sendToBlueTooth(buffer) {
                // console.log('buffer', buffer);
                const that = this
                wx.writeBLECharacteristicValue({
                    deviceId: that.connectedDeviceId,
                    serviceId: that.buleDeviceServiceId,
                    characteristicId: that.uniWriteCharacteristicsId,
                    value: buffer,
                    success: function(res) {
                        // console.log('发送的数据包', buffer);
                        console.log('写入数据包成功', res);
                    }
                })
            },
                //数据转16进制
                ab2hex(buffer) {
                let hexArr = Array.prototype.map.call(
                    new Uint8Array(buffer),
                    function(bit) {
                        return ('00' + bit.toString(16)).slice(-2)
                    }
                )
                console.log(hexArr.join(''));
                return hexArr.join('');
            },
               //监听拿到硬件接收指令后的返回值数据
                getChange() {
                let that=this
                 wx.onBLECharacteristicValueChange(function(res) {
                    // console.log(res);
                    // console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`, 185)
                    console.log(that.ab2hex(res.value), 186)
                })
            },

\