微信小程序之如何连接蓝牙向蓝牙发送信息

技能 · 2018-11-23 · 638 人浏览
微信小程序之如何连接蓝牙向蓝牙发送信息

1、初始化蓝牙模块

openBluetoothAdapter:function() {
    let that = this;
    wx.openBluetoothAdapter({
        complete(res) {
                
        }
    })
},

2、检查蓝牙适配器状态

getBluetoothAdapterState: function () {
     let that = this;
     wx.getBluetoothAdapterState({
        success(res) {

        }
    })
},

3、搜索蓝牙外围设备

getBluetoothAdapterState: function () {
     let that = this;
     wx.getBluetoothAdapterState({
        success(res) {

        }
    })
},

4、获取所有已经发现的蓝牙设备

     getBluetoothDevices:function () {
        let that = this;
        wx.getBluetoothDevices({
            success(res) {
                for (let i = 0; i < res.devices.length; i++) {
                    //解析所有 advertisData
                    var stt = that.buf2hex(res.devices[i].advertisData);
                    
                    //检索指定设备
                    if (stt == that.data.codeQT2) {

                        wx.getSystemInfo({
                            success(ds) {
                                if (ds.platform == 'android') {
                                    that.setData({
                                        dev: res.devices[i],
                                        deviceId: res.devices[i].deviceId,
                                    })

                                } else if (ds.platform == 'ios') {
                                    that.setData({
                                        dev: res.devices[i],
                                        deviceId: res.devices[i].deviceId,
                                    })
                                }

                            }
                        })

                        
                        // res.devices[i].deviceId
                        wx.stopBluetoothDevicesDiscovery();
                    }
                }
            },
            fail(res) {
                that.errCode(res.errCode);
            }
        })
    },

5、连接低功耗蓝牙设备

createBLEConnection:function() {
        let that = this;
        wx.createBLEConnection({
            deviceId: that.data.deviceId,
            success: function (res) {
            },
            fail(res) {
                wx.showModal({
                    content: '连接错误,请重新连接',
                    confirmColor: '#66A6FF',
                    showCancel: false
                })
            }
        })

        // 监听蓝牙连接异常或突然断开
        wx.onBLEConnectionStateChange(function (res) {
            if (res.connected == false) {
                wx.showModal({
                    content: '蓝牙连接已断开或发生异常情况,请重新连接',
                })
            }
        })
    },

6、获取蓝牙设备所有服务

getBLEDeviceServices: function () {
        let that = this;
        wx.getBLEDeviceServices({
            deviceId: that.data.deviceId,
            success: function (res) {
                let service_id = "";
                for (let i = 0; i < res.services.length; i++) {
                    if (res.services[i].uuid.toUpperCase().indexOf("这里填写要使用的服务ID") != -1) {
                        that.setData({
                            service_id: res.services[i].uuid
                        })
                        break;
                    }
                }
            },
            fail(res) {
                wx.showModal({
                    content: '连接错误,请重新连接',
                    confirmColor: '#66A6FF',
                    showCancel: false
                })
            }
        })
    },

7、获取服务特征值/发送数据/监听

getBLEDeviceCharacteristics:function() {
        let that = this;
        wx.getBLEDeviceCharacteristics({
            deviceId: that.data.deviceId,
            serviceId: that.data.service_id,
            success: function (res) {
                for (let i = 0; i < res.characteristics.length; i++) {
                    let item = res.characteristics[i];
                    that.setData({
                        characteristics:item.uuid
                    })

                    //开启notify
                    wx.notifyBLECharacteristicValueChange({
                        deviceId: that.data.deviceId,
                        serviceId: that.data.service_id,
                        characteristicId: item.uuid,
                        state: true,
                        success: function (res) {

                        }
                    })


                    //该特征值可写
                    if (item.properties.write) {
                        var hex = '这里填写你要发送的数据'
                        var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
                            return parseInt(h, 16)
                        }))
                        var buffer1 = typedArray.buffer

                        wx.writeBLECharacteristicValue({
                            deviceId: that.data.deviceId,
                            serviceId: that.data.service_id,
                            characteristicId: item.uuid,
                            value: buffer1,
                            success: function(res) {
                                console.log('发送数据:' + '√');
                            },
                        })
                    }

                    //监听新动态
                    wx.onBLECharacteristicValueChange(function (res) {
                        console.log(res);
                        var stt = that.buf2hex(res.value);
                        console.log(stt);
                        if (stt) {
                            that.setData({
                                random: stt.slice(6, 38)
                            })
                        }
                    })
                }
            },
            fail:function(res) {
                wx.showModal({
                    content: '连接错误,请重新连接',
                    confirmColor: '#66A6FF',
                    showCancel:false
                })
            }
        })
    },

8、关闭蓝牙全部链接

closeBluetoothAdapter:function() {
        let that = this;
        wx.closeBLEConnection({
            deviceId: that.data.deviceId,
        })
        wx.closeBluetoothAdapter()
    },

使用到的函数

/**
     * 字符串转byte
     */
    stringToBytes:function (str) {
        var array = new Uint8Array(str.length);
        for(var i = 0, l = str.length; i<l; i++) {
            array[i] = str.charCodeAt(i);
        }
        return array.buffer;
    }, 


    /**
     * ArrayBuffer转16进制字符串
     */
    buf2hex: function (buffer) {
        var tohex =  Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
        return tohex;
        
    },

页面数据

 data: {
        codeQT2: '2a6938114530',
        dev:null,
        deviceId:'',
        service_id:'未选中服务',
        characteristics:'未选中服务特征值',
        strMAC:null,
        random:null
    },
JavaScript 小程序 蓝牙锁 BLE
Theme Jasmine by Kent Liao