微信小程序蓝牙连接详细流程

小程序蓝牙我一直使用过很多次了,一直没有做总结,今天总结一下,来一个完整的教程,从初始配置到连接的整个过程。写的有点简陋,还请见谅



 

蓝牙硬件告知条件

serviceId    设备ID   使用在蓝牙搜索范围,开启广播、开启数据传播等地方使用

characteristicId  特征值ID  主要使用在打开  使用在蓝牙搜索范围,开启广播、开启数据传播等地方使用
 
注释:serviceId和characteristicId在主要是使用在开启广播和蓝牙数据传输中,应该是硬件方面会直接给你,开启广播和数据传输可能是同一个serviceId下面的不同characteristicId,也可能是两个serviceId,两个characteristicId,请注意查看,我这里所用的是同一个serviceId下不同的characteristicId。
 
一、初始数据 
data: {
    serviceId: '0000A002-0000-1000-8000-00805F9B34FB',
    characteristicId: '0000C305-0000-1000-8000-00805F9B34FB',    //notify的特征值
    WcharacteristicId: '0000C304-0000-1000-8000-00805F9B34FB',   //write的特征值
    connectMac : '',  //蓝牙的deviceId
}

二、初始化蓝牙和适配器

//关闭蓝牙模块、释放蓝牙资源,保证连接顺畅
closeBluetoothAdapter(){
   var that = this
   wx.closeBluetoothAdapter({
     complete(){
       that.openBluetoothAdapter()
     }
   })
 },
//初始化蓝牙
  openBluetoothAdapter:function(){
    var that =this;
    // 蓝牙连接
    wx.openBluetoothAdapter({
      success: function (res) {
        that.getBluetoothAdapterState();
      },
      fail: function (res) {
        console.log(res);
        wx.showModal({
          title: '提示',
          content: '请您打开蓝牙或检查微信是否授权蓝牙',
          confirmColor: '#00b6b5',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },
注意:这里会判断是否打开蓝牙,在ios中还会出现另一种失败的情况,就是蓝牙未授权给微信,导致微信不能使用蓝牙。打开授权的方法是:点击【设置】- 【隐私】-【蓝牙】- 【微信】中打开。
getBluetoothAdapterState: function () {
    var that = this;
    wx.getBluetoothAdapterState({
      success: function (res) {
        if(!res.discovering){
          that.startBluetoothDevicesDiscovery();
        }
        if(!res.available){
          wx.showModal({
            title: '提示',
            content: '当前蓝牙适配器不可用',
            confirmColor: '#00b6b5',
            showCancel: false,
            success(res) {
            }
          })
        }
      },
      fail:function(res){
        wx.showModal({
          title: '提示',
          content: '适配蓝牙失败',
          confirmColor: '#00b6b5',
          showCancel: false,
          success(res) {
          }
        })
      }
    });
  },

三、搜索周围蓝牙

蓝牙搜索一共又两种方法,第一种是一次性查询,第二种是持续监听上传,两种方法都有自己的优劣势,看自己需要来使用哪一种

  //搜索设备
  startBluetoothDevicesDiscovery: function () {
    var that = this;
    wx.startBluetoothDevicesDiscovery({
      services: [that.data.serviceId],
      allowDuplicatesKey: false,
      success: function (res) {
        console.log('蓝牙获取列表成功');
        // 第一种方法,需要给一点搜索时间
        setTimeout(()=>{
          that.getBluetoothDevices();
        },500)
        //第二种方法
        that.onBluetoothDeviceFound();
      },
      fail:function(res){
        wx.showModal({
          title: '提示',
          content: '搜索蓝牙设备失败'
        })
      }
    })
  },

serviceId在这里使用是限制范围,将是自己的小程序显示,其他的排除,可以去除掉

第一种方法

 // // 获取所有已发现的设备
    getBluetoothDevices: function () {
      var that = this;
      wx.getBluetoothDevices({
        success(res){
          var BluetoothDataList = that.data.BluetoothDataList; //数据列表,可以自己定义
          res.devices.forEach(item => {
            var buff = item.advertisData; //获取蓝牙的广播数据
            var arrayBuff = Array.prototype.map.call(new Uint8Array(buff), x => ('00' + x.toString(16)).slice(-2)).join(':');
            arrayBuff = arrayBuff.toUpperCase() //将数据处理了获取macId
            item.noteName = arrayBuff?arrayBuff:item.deviceId; //将macId放进列表里面
            BluetoothDataList.push(item);
          })
          that.setData({
            BluetoothDataList : BluetoothDataList
          })
        }
      })
    },

第二种方法,一般安卓的蓝牙时deviceId就是macId,但是ios的deviceId是一串乱码,很长不好排版,所以我就和硬件调试,在广播里面加入了macId,来保证小程序显示的比较满意(一般的蓝牙也会在广播里面插入macId的)

  // // 获取所有已发现的设备
  onBluetoothDeviceFound: function () {
    var that = this;
    wx.onBluetoothDeviceFound((res) => {
      var BluetoothDataList = this.data.BluetoothDataList;//数据列表,可以自己定义
      res.devices.forEach(item => {
        var buff = item.advertisData;//获取蓝牙的广播数据
        var arrayBuff = Array.prototype.map.call(new Uint8Array(buff), x => ('00' + x.toString(16)).slice(-2)).join(':');
        arrayBuff = arrayBuff.toUpperCase()//将数据处理了获取macId
        item.noteName = arrayBuff?arrayBuff:item.deviceId;//将macId放进列表里面
        BluetoothDataList.push(item);
      })
      that.setData({
        BluetoothDataList : BluetoothDataList
      })
    })
  },

停止蓝牙搜索,这个根据不同的情况有不同地方的调用,在第一种情况下,在调用完了之后就直接调用了,而第二种情况下,需要在连接了蓝牙之后才能关闭搜索

// //停止搜索周边设备
  lanya5: function () {
    wx.getBluetoothAdapterState({
      success: function (res) {
        if(res.discovering){
          wx.stopBluetoothDevicesDiscovery({
            success: function (res) {
              console.log("蓝牙停止搜索")
            }
          })
        }
      }
    })
  },

四、设备连接

将列表列出来了之后就是点击就该连接设备

  //连接设备
  connectTO: function (mac,num=0) {
    var that = this;
    return new Promise((reslove,rejcts)=>{
      wx.showLoading({
        title: '连接中',
      })
      wx.createBLEConnection({
        deviceId: mac.deviceId,
        success: function (res) {
          wx.hideLoading();
          that.setData({
            connectMac : mac.deviceId
          })
          let sys = wx.getSystemInfoSync()
          that.lanya6();
          reslove()
          wx.onBLEConnectionStateChange(function(res) {
            // 该方法回调中可以用于处理连接意外断开等异常情况
            console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
            if(!res.connected){ 
              that.connectTO(mac);
              clearInterval(timer)
              timer = null
            }
          })
        },
        fail: function (res) {
          wx.hideLoading()
          if(num < 3){
            that.connectTO(mac,++num);
          }else{
            wx.showModal({
              title : '提示',
              content : '蓝牙连接失败',
              cancelText : '重新连接',
              confirmText : '返回首页',
              success(res){
                if(res.confirm){
                  wx.switchTab({
                    url: '/pages/mainIndex/index',
                  })
                }
                if(res.cancel){
                  that.connectTO(mac);
                }
              }
            })
          }
          rejcts();
        }
      })
    })
  },

 


 


 

 上面基本上就是微信使用蓝牙从配置到连接的整个过程,基本上的坑都已经列上去了

 

posted @ 2021-12-03 14:55  闲人甲  阅读(8319)  评论(0编辑  收藏  举报