微信小程序蓝牙连接发送信息

小天天天天    前端    999+ 次    2023-05-16 16:32:21


///获取应用实例

var app = getApp()

Page({

    data: {

        lanya: "",

        state: "",

        msg: "",

        sousuo: "",

        status: "",

        connectedDeviceId: "", //连接设备Id

        devices: [],

        serviceId: "",

        writeCharacteristicId: "",

        notifyCharacteristicId: "",

    },

    onLoad: function() {

        var that = this;

        wx.openBluetoothAdapter({

            success: function(res) {

                console.log(res.errMsg);

                that.setData({

                    lanya: "初始化小程序蓝牙" + res.errMsg

                });



            },

            fail: function(res) {

                console.log(res);

                that.setData({

                    lanya: "初始化小程序蓝牙" + res.errMsg

                });

            }

        });

    },

    adapterState: function() {

        //获取本机蓝牙适配器状态

        var that = this;

        wx.getBluetoothAdapterState({

            success: function(res) {

                console.log(res);

                that.setData({

                    state: res.errMsg

                });

            }

        });

    },

    selectDevices: function() { //搜索设备

        var that = this;

        wx.startBluetoothDevicesDiscovery({

            allowDuplicatesKey: false,

            success: function(res) {

                //监听蓝牙适配器状态

                wx.onBluetoothAdapterStateChange(function(res) {

                    that.setData({

                        sousuo: res.discovering ? "在搜索" : "未搜索",

                        status: res.available ? "可用" : "不可用",

                    });

                });

                setTimeout(function() {

                    that.getDevices();

                }, 1000);



            }

        });

    },

    getDevices: function() {

        //获取设备列表

        var that = this;

        wx.getBluetoothDevices({

            success: function(res) {

                that.setData({

                    devices: res.devices

                });

                //that.test(res.devices);

            }

        });

    },

    //停止搜索周边设备

    stop: function() {

        var that = this;

        wx.stopBluetoothDevicesDiscovery({

            success: function(res) {

                that.setData({

                    sousuo: res.discovering ? "在搜索" : "未搜索",

                    status: res.available ? "可用" : "不可用",

                });



            }

        })

    },



    test: function(devices) {

        wx.onBluetoothDeviceFound(function(devices) {

            console.log(devices);

            function ab2hex(buffer) {

                var hexArr = Array.prototype.map.call(

                    new Uint8Array(buffer),

                    function(bit) {

                        return ('00' + bit.toString(16)).slice(-2)

                    }

                )

                return hexArr.join('');

            }

            console.log('new device list has founded');

            console.log(ab2hex(devices.devices[0].advertisData));



        });

    },

    connect: function(e) { //连接蓝牙

        var that = this;

        wx.showModal({

            title: '提示',

            content: '确定连接此设备吗?',

            success: function(res) {

                if (res.confirm) {

                    console.log('用户点击确定');

                    var clickId = e.currentTarget.id;

                    wx.createBLEConnection({

                        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接

                        deviceId: clickId,

                        success: function(res) {

                            that.setData({

                                connectedDeviceId: clickId

                            });

                            wx.showToast({

                                title: '成功',

                                icon: 'success',

                                duration: 2000

                            });

                            wx.getBLEDeviceServices({

                                // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接

                                deviceId: clickId,

                                success: function(res) {

                                    console.log('device services:', res.services);

                                    that.setData({

                                        service: res.services[1]

                                    });

                                }

                            });

                            that.getService(clickId);

                            setTimeout(function() {

                                that.getCharacteristics(clickId, that.data.serviceId);

                            }, 3000);

                            wx.onBLEConnectionStateChange(function(res) {

                                // 该方法回调中可以用于处理连接意外断开等异常情况

                                console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)

                            });

                        },
                        fail: function(res) {

                            console.log(res.errMsg);

                        }

                    });

                } else if (res.cancel) {

                    console.log('用户点击取消')

                }

            }

        });

    },

    getService: function(deviceId) {

        var that = this;

        wx.getBLEDeviceServices({

            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接

            deviceId: deviceId,

            success: function(res) {

                console.log('device services:', res.services);

                that.setData({

                    serviceId: res.services[1].uuid

                });

            }

        });

    },

    getCharacteristics: function(deviceId, serviceId) {

        var that = this;

        wx.getBLEDeviceCharacteristics({

            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接

            deviceId: deviceId,

            // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取

            serviceId: serviceId,

            success: function(res) {

                console.log(res);

                console.log('device getBLEDeviceCharacteristics:', res.characteristics);

                for (var i = 0; i < res.characteristics.length; i++) {

                    if (res.characteristics[i].properties.write && !res.characteristics[i].properties.read &&

                        !res.characteristics[i].properties.notify && !res.characteristics[i].properties.indicate) {

                        that.setData({

                            writeCharacteristicId: res.characteristics[i].uuid

                        });

                    } else if (!res.characteristics[i].properties.write && !res.characteristics[i].properties.read &&

                        res.characteristics[i].properties.notify && !res.characteristics[i].properties.indicate) {

                        that.setData({

                            notifyCharacteristicId: res.characteristics[i].uuid

                        });

                    }

                }

                console.log("writeCharacteristicId=" + that.data.writeCharacteristicId);

                console.log("notifyCharacteristicId=" + that.data.notifyCharacteristicId);

                wx.notifyBLECharacteristicValueChange({

                    state: true, // 启用 notify 功能

                    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接

                    deviceId: deviceId,

                    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取

                    serviceId: serviceId,

                    // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取

                    characteristicId: that.data.notifyCharacteristicId,

                    success: function(res) {

                        console.log('notifyBLECharacteristicValueChange success', res.errMsg);

                    }

                });

                that.onBLECharacteristicValueChange();

            }

        });

    },

    writeMsg: function() {

        var that = this;

        let buffer = new ArrayBuffer(7);

        let dataView = new DataView(buffer);

        dataView.setUint8(0, 0xaa);

        dataView.setUint8(1, 0x04);

        dataView.setUint8(2, (1 << 7));

        dataView.setUint8(3, (1 << 3 | 1));

        dataView.setUint8(4, 1);

        dataView.setUint8(5, 1 << 2);



        // var buffer = new ArrayBuffer(7);

        // buffer[0] = ;

        // buffer[1] = ;

        // buffer[2] = (1 << 7)

        // buffer[3] = (1 << 3) | 1

        // buffer[4] = 1;

        // buffer[5] = 10;

        console.log(buffer);

        wx.writeBLECharacteristicValue({

            // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取

            deviceId: that.data.connectedDeviceId,

            // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取

            serviceId: that.data.serviceId,

            // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取

            characteristicId: that.data.writeCharacteristicId,

            // 这里的value是ArrayBuffer类型

            value: buffer,

            success: function(res) {

                console.log('writeBLECharacteristicValue success', res.errMsg)

            }

        });

    },

    onBLECharacteristicValueChange: function() {

        console.log("start change listen");

        wx.onBLECharacteristicValueChange(function(res) {

            console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)

            console.log(ab2hext(res.value))

        });

    },

    closeBLEConnection: function() {

        //断开蓝牙连接

        var that = this;

        wx.closeBLEConnection({

            deviceId: that.data.connectedDeviceId,

            success: function(res) {

                console.log(res);

            }

        })



    }



});

如果你觉得本篇文章对您有帮助,请打赏作者

上一篇: 原生小程序左右滑动切换页面事件

下一篇: 微信小程序个人中心模板

最新评论

暂无评论

热门文章

最新评论

网站数据

网站文章数:481

今日UV/PV/IP:7/35/7

昨日UV/PV/IP:9/10 /9

TOP