// pages/configuration/configuration.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceArr: [],
    isConnected: false,
    chs: [],
    bytes:[]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let type = ''
    if(options.type=='wifi'){
      type = {
        name: 'WIFI',
        isShow: true,
        isShowPswText: '显示密码',
        placeholder1: '请输入wifi名称',
        placeholder2: '请输入wifi密码'
      };
    }else{
      type = {
        name: '手机热点',
        isShow: true,
        isShowPswText: '显示密码',
        placeholder1: '请输入热点名称',
        placeholder2: '请输入热点密码'
      }
    }
    this.setData({
      type:type
    })
    //判断wifi是否连接
    wx.getConnectedWifi({
      success: function (res) {
        app.globalData.wifi = res.wifi
      },
      fail: function (res) {
        app.globalData.wifi = ''
      }
    })
  //蓝牙使用准备模块=======================================================================================================
    let that = this;
    if (app.getPlatform() == 'android' && app.versionCompare('6.5.7', app.getVersion())) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低,请更新至最新版本',
        showCancel: false
      })
    } else if (app.getPlatform() == 'ios' && app.versionCompare('6.5.6', app.getVersion())) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低,请更新至最新版本',
        showCancel: false
      })
    }
    wx.showLoading({
      title: '初始化蓝牙'
    })
    this.initBuleTooth()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.wifi){
      let wifi = app.globalData.wifi;
      this.setData({
        wifiName: wifi.SSID
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  showPsw:function(){
    let isShow = 'type.isShow';
    let ShowPswText = 'type.isShowPswText';
    let isShowPswText = this.data.type.isShow ? '隐藏密码' : '显示密码';
    this.setData({
      [isShow]:!this.data.type.isShow
    });
    this.setData({
      [ShowPswText]:isShowPswText
    })
  },
  connect:function(){
    let that = this;
    let name = this.data.wifiName;
    let psw = this.data.psw;
    if(name && psw){
      wx.startWifi({
        success(res) {
          wx.connectWifi({
            SSID: name,
            password: psw,
            success(res) {
              wx.showToast({
                title: '连接成功!',
                icon: 'none'
              })
              wx.showLoading({
                title: '配网中',
              })
              //组织参数
              let param1 = [-86, 1, 2, null, 0];
              let param2 = that.stringToBytes(name)
              let param3 = that.stringToBytes(psw)
              let param4 = that.stringToBytes(app.globalData.wifi ? app.globalData.wifi.BSSID.replace(/:/g, ''):'');
              let param5 = that.stringToBytes("5G");
              let param6 = [1, 2, 1, 0, 1, 0]
              let param = that.data.bytes.concat(param1).concat(param2.length).concat(param2).concat(param3.length).concat(param3).concat(param4.length).concat(param4).concat(param5.length).concat(param5).concat(param6);
              param[3] = param.length
              //蓝牙配网
              that.wirteData(param)
            },
            fail: function (res) {
              if (res.errCode == 12002) {
                wx.showToast({
                  title: '密码错误',
                  icon: 'none'
                })
              } else {
                wx.showToast({
                  title: '连接失败,错误码:' + res.errCode,
                  icon: 'none'
                })
              }
            }
          })
        },
        fail: function () {
          wx.showToast({
            title: 'wifi模块初始化失败!',
            icon: 'none'
          })
        }
      })
    }else{
      wx.showToast({
        title: '请输入账号密码!',
        icon:'none'
      })
    }
  },
  getVal:function(e){
    let key = e.currentTarget.dataset.value;
    this.setData({
      [key]:e.detail.value
    })
  },
  //工具类=====================================================================
  inArray: function (arr, key, val) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i][key] === val) {
        return i;
      }
    }
    return -1;
  },
  // ArrayBuffer转16进度字符串示例
  ab2hex: function (buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
  stringToBytes:function(str) {
    let ch, st, re =[];
    for(var i = 0; i<str.length; i++ ) {
      ch = str.charCodeAt(i);
      st = [];
      do {
        st.push(ch & 0xFF);  // push byte to stack  
        ch = ch >> 8;          // shift value down by 1 byte  
      }
      while (ch);
      re = re.concat(st.reverse());
    } 
    return re;  
  },
  //蓝牙函数=====================================================================
  //初始化蓝牙模块
  initBuleTooth: function () {
    let that = this;
    if (wx.openBluetoothAdapter) {
      wx.openBluetoothAdapter({
        success(res) {
          that.getBuleTooth()
        },
        fail: function (res) {
          wx.hideLoading()
          wx.showToast({
            title: '蓝牙模块不可用!',
            icon: 'none'
          })
        }
      })
    } else {
      wx.hideLoading()
      // 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示  
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
      })
    }
  },
  //开始搜索附近蓝牙设备
  getBuleTooth: function (uuid) {
    let that = this;
    wx.startBluetoothDevicesDiscovery({
      services: (uuid && uuid.length == 0) ? '' : uuid,
      success: function (res) {
        that.foundBuleTooth()
      },
      fail: function (res) {
        wx.showToast({
          title: '搜索失败',
          icon: 'none'
        })
      }
    })
  },
  //发现设备
  foundBuleTooth: function () {
    let that = this;
    let found = false;
    let timeOut;
    wx.onBluetoothDeviceFound(function (res) {
      res.devices.forEach((device) => {
        let str1 = that.ab2hex(device.advertisData).substr(0,2);
        let str2 = that.ab2hex(device.advertisData).substr(2,4);
        let tag = parseInt(str2+str1,16)
        if (tag == app.globalData.dongleTag){
          found = true
          that.getConnect(device)
          that.stopBuleTooth()
        }
      })
    });
    timeOut = setTimeout(function () {
      if (!found) {
        wx.showToast({
          title: '未找到指定设备',
          icon: 'none'
        })
      }
      timeOut = null;
    }, 20000)
  },
  //停止搜索
  stopBuleTooth: function () {
    wx.stopBluetoothDevicesDiscovery({
      success(res) {
        console.log('成功停止搜索')
      }
    })
  },
  //建立连接
  getConnect: function (dvs) {
    let that = this;
    const ds = dvs;
    const deviceId = ds.deviceId;
    const name = ds.name;
    wx.createBLEConnection({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      success(res) {
        that.setData({
          isConnected: true,
          connectedDevice: name
        })
        that.getService(deviceId)
      }
    });
    //that.stopBuleTooth()
  },
  //获取设备所有服务
  getService: function (deviceId) {
    let that = this;
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: function (res) {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            that.getCharacteristic(deviceId, res.services[i].uuid)
          }
        }
      }
    })
  },
  //获取蓝牙设备某个服务中所有特征值(characteristic)
  getCharacteristic: function (deviceId, serviceId) {
    let that = this;
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success(res) {
        wx.hideLoading()
        wx.showToast({
          title: '初始化蓝牙成功!',
          icon: 'none'
        });
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            that.setData({
              canWrite: true
            })
            that._deviceId = deviceId
            that._serviceId = serviceId
            that._characteristicId = item.uuid
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail: function (res) {
        console.log("获取服务特征值失败,再次获取" + res)
        that.getCharacteristic(deviceId, serviceId)
      }
    })
  },
  //写数据
  wirteData: function (param) {
    let that = this;
    let data = new Uint8Array(param);
    let dataBuffer = data.buffer;
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: dataBuffer,
      success: function (res) {
        console.log('成功')
        console.log(res)
      },
      fail: function (res) {
        wx.showToast({
          title: '写入失败,请重新配网',
          icon:'none'
        })
      }
    })
    //写入数据之后监听
    wx.onBLECharacteristicValueChange((characteristic) => { 
      switch (that.ab2hex(characteristic.value)){
        case '42':
          wx.hideLoading()
          wx.showToast({
            title: '配网成功',
            icon:'none'
          });
          that.closeBluetoothAdapter()
          wx.navigateTo({
            url: '../finish/finish',
          })
          break;
        case '0b':
          break;
        default:
          wx.hideLoading()
          wx.showToast({
            title: '配网失败',
            icon:'none'
          })
      }
    })
  },
  //关闭蓝牙
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    console.log('关闭蓝牙')
  }
})


 

要注意的是组织参数时,需将字符串变为字节数组