跳转到主要内容

小程序配网代码示例说明

设备端: 需要具备WI-FI和蓝牙功能

小程序端: 通过微信小程序提供的API来实现与设备的连接、通信和配网

配网流程: 选择WI-FI、发送配置数据、设备连接WI-FI、确认配网成功

1.小程序配网流程

获取WI-FI信息:

配网之前调用微信 wx.startWifi API初始化WI-FI模块获取WI-FI信息,输入连接WI-FI的密码存储下来

获取设备信息:

使用小程序的wx.openBluetoothAdapter和wx.getBluetoothDevicesAPI,通过蓝牙搜索设备获取设备的信息,选择并连接

发送WI-FI信息到设备:

通过之前保存的WI-FI信息通过蓝牙发送到设备端进行配网操作,等待设备返回信息确认配网成功

2. 小程序实现WI-FI配网

1.先获取wifi信息保存下来

startConfigNet:function(e) {
        wx.startWifi({
            success(res) {
              console.log(res.errMsg, "wifi初始化成功")
              wx.getConnectedWifi({
                success: (result) => {
                    console.log("test");console.log(result.wifi.frequency);
                    if(result.wifi.frequency > 3000){
                        wx.showModal({
                            title: '错误',
                            content: '不支持5G频段WIFI,请重新选择WIFI网络!'
                        })
                    }else{
                        app.WIFIInformation.SSID = result.wifi.SSID;
                        wx.navigateTo({
                            url: '/pages/input_wifi_psd/input_wifi_psd',
                        })
                    }  
                  },
                fail:(result) => {
                    console.log(result);
                      wx.showModal({
                          title: '错误',
                          content: 'WIFI初始化失败,请检查是否连接WIFI和是否开启定位功能'
                      })
                  },
                  
              },)
            },
            fail: function(res){
              console.log(res.errMsg, "wifi初始化失败")
              wx.showModal({
                title: '错误',
                content: 'WIFI初始化失败,请检查是否连接WIFI'
              })
            }
          })
    }

2.通过蓝牙搜索并连接设备后获取可以监听与写数据的uuid

//搜索设备
    startSearch: function () {
        var that = this
        wx.stopPullDownRefresh()
        wx.closeBluetoothAdapter({
            complete(res) {
                wx.openBluetoothAdapter({
                    success: function (res) {
                        wx.getBluetoothAdapterState({
                            success: function (res) {
                                console.log('openBluetoothAdapter success', res)
                                if (res.available) {
                                    if (res.discovering) {
                                        wx.stopBluetoothDevicesDiscovery({
                                            success: function (res) {console.log(res)}
                                        })
                                    } else {that.getBluetoothDevices()}
                                } else {
                                    wx.showModal({title: '提示',content: '本机蓝牙适配器不可用',showCancel: false})
                                }
                            },
                        })
                    },
                    fail: function () {
                        wx.showModal({title: '提示',content: '手机蓝牙未打开,请打开蓝牙!',showCancel: false })
                    }
                })
            }
        })
    },
    checkPemission: function () { //android 6.0以上需授权地理位置权限
        var that = this
        var platform = app.BLEInformation.platform
        if (platform == "ios") {
            app.globalData.platform = "ios"
            that.getBluetoothDevices()
        } else if (platform == "android") {
            app.globalData.platform = "android"
            console.log(app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1))
            if (app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1) > 5) {
                wx.getSetting({
                    success: function (res) {
                        console.log(res)
                        if (!res.authSetting['scope.userLocation']) {
                            wx.authorize({
                                scope: 'scope.userLocation',
                                complete: function (res) {
                                    that.getBluetoothDevices()
                                }
                            })
                        } else {
                            that.getBluetoothDevices()
                        }
                    }
                })
            }
        }
    },
    getBluetoothDevices: function () { //获取蓝牙设备信息
        var that = this
        
        console.log("start search")
        that.setData({
            isScanning: true
        })
        wx.startBluetoothDevicesDiscovery({
            success: function (res) {
                console.log(res)
                if(timerID != -1) return
                timerID = setInterval(function () {
                    wx.getBluetoothDevices({
                        success: function (res) {
                            console.log("searching...",res)
                            var devices = []
                            var num = 0
                            for (var i = 0; i < res.devices.length; ++i) {
                                if (res.devices[i].name != "未知设备" && res.devices[i].name.startsWith('WT')) {
                                    devices[num] = res.devices[i]
                                    num++
                                }
                                // if (res.devices[i].name != "未知设备" && res.devices[i].name != undefined && res.devices[i].name != null) {
                                //     devices[num] = res.devices[i]
                                //     num++
                                // }
                            }
                            that.setData({
                                list: devices,
                                isScanning: true
                            })
                            console.log(devices)
                        },
                    })
                }, 2500)
            },
        })
    },

3.将wifi信息与指定的协议数据发送给设备进行配网

// 将 Wi-Fi 信息发送给设备进行配网
  sendWifiInfoToDevice(wifi) {
    // 这里可以通过蓝牙、局域网等方式将 Wi-Fi 配置信息发送给设备
    // 假设通过蓝牙发送配网信息
    var writeNum=14; //代表固定的不包含wifi名称和wifi密码的总长度
    var ssid = ""//wifi名称
    var pwd = ""//wifi密码
    var ssid_array = ""//对ssid(wifi名称)转码;
    writeNum=writeNum+ssid_array.length //累加名称长度
    var pwd_array = ""//对pwd(wifi密码)转码;
    writeNum=writeNum+pwd_array.length //累加密码长度
    var writeArray=new ArrayBuffer(writeNum)//数据包长度
    const uint8View = new Uint8Array(writeArray); //需要填充指定对应的协议信息与wifi信息
    
    //按照协议说明对照
    uint8View[0]=126 
   	const hexString = (writeNum-2).toString(16)
    const paddedHexString = hexString.padStart(4, '0');
    const byte1 = parseInt(paddedHexString.substring(0, 2), 16) & 255;
    const byte2 = parseInt(paddedHexString.substring(2, 4), 16) & 255;
    uint8View[1]=byte1
    uint8View[2]=byte2
    uint8View[3]=0
    uint8View[4]=0
    uint8View[5]=1
    uint8View[6]=89
    uint8View[7]=222
   	const hexString1 = (writeNum-12).toString(16)
    const paddedHexString1 = hexString1.padStart(4, '0');
    const byte3 = parseInt(paddedHexString1.substring(0, 2), 16) & 255;
    const byte4 = parseInt(paddedHexString1.substring(2, 4), 16) & 255;
    uint8View[8]=byte3
    uint8View[9]=byte4
    uint8View[10]=ssid.length
   	//循环名称填充
    for(let i=0;i<ssid_array.length;i++){
        uint8View[i+11]=ssid_array[i]
    }
    uint8View[11+ssid_array.length]=pwd.length
   	//循环密码填充
    for(let i=0;i<pwd_array.length;i++){
        uint8View[i+12+ssid_array.length]=pwd_array[i]
    }
    //循环从byte1开始到此的字节相加之和后计算出校验和
    var checksum=0;
    for(let i=0;i<uint8View.length-3;i++){
        checksum=checksum+uint8View[i+1]
    }
    uint8View[12+pwd_array.length+ssid_array.length]=checksum & 255
    uint8View[13+pwd_array.length+ssid_array.length]=239
    
    wx.getBluetoothDevices({
      success: res => {
        const device = res.devices[0]; // 获取第一个设备,假设是目标设备
        if (device) {
          // 发送 Wi-Fi 信息给设备
          wx.writeBLECharacteristicValue({
            deviceId: device.deviceId,
            serviceId: 'YOUR-SERVICE-ID',
            characteristicId: 'YOUR-CHARACTERISTIC-ID',
            value: uint8View.buffer,
            success: () => {
              console.log('Wi-Fi 配网信息已发送到设备');
            },
            fail: err => {
              console.error('发送配网信息失败', err);
            }
          });
        }
      },
      fail: err => {
        console.error('获取蓝牙设备失败', err);
      }
    });
  }