小程序?qū)崿F(xiàn)BLE藍(lán)牙連接硬件設(shè)備

最近公司想做一個(gè)小程序使用藍(lán)牙連接硬件設(shè)備進(jìn)行相互傳輸數(shù)據(jù)指令, 接下來是我做這個(gè)功能的總結(jié)

兩種藍(lán)牙普遍使用規(guī)格

  • 藍(lán)牙基礎(chǔ)率/增強(qiáng)數(shù)據(jù)率
    也稱為經(jīng)典藍(lán)牙。常用在對(duì)數(shù)據(jù)傳輸帶寬有一定要求的場(chǎng)景上,比如需要傳輸音頻數(shù)據(jù)的藍(lán)牙音箱、藍(lán)牙耳
    機(jī)等;
  • 藍(lán)牙低功耗
    特點(diǎn)就是功耗極低,傳輸速度更快, 常用在對(duì)續(xù)航要求較高且只需小數(shù)據(jù)量傳輸?shù)母鞣N智能電子產(chǎn)品中,比如
    智能穿戴設(shè)備、智能家電、傳感器等,應(yīng)用場(chǎng)景廣泛。

實(shí)現(xiàn)步驟

4bb6a82c858e1aed51e2aff72f9ad2e.jpg
初始化藍(lán)牙
/**
   * 初始化藍(lán)牙設(shè)備
*/
  onConnect() {
    let that = this;
    wx.openBluetoothAdapter({ //調(diào)用微信小程序api 打開藍(lán)牙適配器接口
      success: function(res) {
          that.startBluetoothDevicesDiscovery(); // 調(diào)用搜索
          wx.showLoading({
            title: '搜索中',
          })
      },
      fail: function(res) {
        wx.showToast({
          title: '請(qǐng)先開啟藍(lán)牙',
          icon: 'none',
          duration: 1000
        })
      }
    });
  },
開始搜索藍(lán)牙設(shè)備
  startBluetoothDevicesDiscovery: function() {
    var that = this;
    wx.startBluetoothDevicesDiscovery({
      success: function(res) {
        console.log("discovery", res);
        if (res.errCode == 0) { // 搜索成功
          that.getConnect(); // 調(diào)用連接該設(shè)備
        }
      },
    });
  },
開始連接
  getConnect: function() {
    var that = this;
    var timer = setInterval(function() {
        wx.getBluetoothDevices({ // 獲取在藍(lán)牙模塊生效期間所有搜索到的藍(lán)牙設(shè)備。包括已經(jīng)和本機(jī)處于連接狀態(tài)的設(shè)備
          success: function(res) {
            console.log("devices", res);
            for (var i = 0; i < res.devices.length; i++) {
              if (res.devices[i].name == that.data.deviceName) {
                wx.hideLoading();
                wx.showLoading({
                  title: '連接中',
                })
                that.setData({
                  isFinded: true
                });
                clearInterval(timer);
                that.setData({
                  deviceId: res.devices[i].deviceId
                });
                console.log('設(shè)備號(hào)', that.data.deviceId);
                console.log("開始嘗試建立連接");
                wx.createBLEConnection({  // 連接藍(lán)牙低功耗設(shè)備。
                  deviceId: that.data.deviceId,
                  timeout: 10000,
                  success: function(res) {
                    console.log(res);
                    if (res.errCode == 0) {
                      console.log('連接成功')
                      that.setData({
                        isConnected: true
                      });
                      wx.stopBluetoothDevicesDiscovery(); // 如果已經(jīng)找到, 停止搜尋附近的藍(lán)牙外圍設(shè)備。
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: '不能正常對(duì)藍(lán)牙設(shè)備進(jìn)行連接',
                        showCancel: false
                      })
                    }
                  },
                  fail: (res) => {
                    wx.hideLoading();
                    if (res.errCode == 10012) {
                      wx.showModal({
                        title: '提示',
                        content: '連接超時(shí)',
                        showCancel: false
                      })
                    }
                    console.warn("fail", res);
                  },
                  complete: () => {
                    wx.hideLoading();
                  }
                })
                break;
              }
            }
          }
        });
      },
      3000);
    setTimeout(function() {
      if (!that.data.isFinded && !that.data.isConnected) {
        clearInterval(timer);
        that.setData({
          isFailed: false
        });
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '搜索藍(lán)牙超時(shí)',
          showCancel: false
        })
      }
    }, 12000);
  },
獲取設(shè)備信息
  onGetuuid(){
    let that = this;
    if(that.data.isConnected && that.data.isFailed){
    wx.showLoading({
      title: '獲取serviceId',
    })
    console.log("開始獲取設(shè)備信息");
    wx.getBLEDeviceServices({
      deviceId,
      success(getServicesRes) {
        console.log("getServicesRes", getServicesRes);
        let service = getServicesRes.services[1]
        let serviceId = service.uuid
        console.log(serviceId);
        wx.showLoading({
          title: '獲取characteristicId',
        })
        wx.getBLEDeviceCharacteristics({
          deviceId,
          serviceId,
          success(getCharactersRes) {
            console.log("getCharactersRes", getCharactersRes);
            wx.hideLoading();
            let characteristic = getCharactersRes.characteristics[0]
            let characteristicId = characteristic.uuid
            wx.notifyBLECharacteristicValueChange({
              state: true,
              deviceId,
              serviceId,
              characteristicI,
              success() {
                console.log('開始監(jiān)聽特征值')
                wx.onBLECharacteristicValueChange(function (onNotityChangeRes) {
                  console.log('監(jiān)聽到特征值更新', onNotityChangeRes);
                  let characteristicValue = that.ab2hex(onNotityChangeRes.value);
                  console.log("characteristicValue-16進(jìn)制", characteristicValue ); // 設(shè)備返回的16進(jìn)制值
                  wx.showModal({
                    title: '監(jiān)聽到特征值更新',
                    content: `更新后的特征值(16進(jìn)制格式):${characteristicValue}`,
                    showCancel: false
                  })
                })
              },
              fail: (res) => {
                console.warn("監(jiān)聽特征值失敗");
              }
            })
          },
          fail: (res) => {
            console.warn("獲取特征值信息失敗", res);
          },
          complete: (res) => {
            console.log('獲取服務(wù)信息完成',res);
            wx.hideLoading();
          }
        })
      },
      fail: (res) => {
        console.warn("獲取服務(wù)信息失敗", res);
      },
      complete: () => {
        wx.hideLoading();
      }
    })
    }else{
      wx.showToast({
        title: '請(qǐng)先連接藍(lán)牙',
      })
    }
  },
發(fā)送指令
  onSendCommand() {
    var buf = new ArrayBuffer(6);
    let dataView = new DataView(buf);
      wx.writeBLECharacteristicValue({
        // 需要上面的 getBluetoothDevices 或者 onBluetoothDeviceFound 接口中獲取
        deviceId,
        // 需要在上面的 getBLEDeviceServices 接口中獲取
        serviceId,
        // getBLEDeviceCharacteristics 接口中獲取
        characteristicId,
        value: buf,
        success: function(res) {
          console.log(res);
          console.log("發(fā)送指令成功");
          wx.showToast({
            title: '發(fā)送成功',
            icon: 'none'
          })
        },
        fail: function(res) {
          console.warn("發(fā)送指令失敗", res)
        }
      })
  },
斷開連接
  onCloseConnect(){
    this.setData({
      isConnected:false,
      isFinded:false
    })
    wx.closeBLEConnection({
      deviceId: this.data.deviceId,
      success: function(res) {
        console.log("成功斷開連接");
        wx.showToast({
          title: '成功斷開連接',
        })
      },
    })
  }
完整dome代碼已放github上

https://github.com/xxj435/wx_lanya

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容