小程序藍牙通信模塊


// 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('關閉藍牙')
  }
})

具體見https://gitee.com/jiangdaqi/minPro/blob/master/pages/configuration/configuration.js

 

要注意的是組織參數時,需將字符串變為字節數組


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM