微信小程序蓝牙自动连接

作者: 你美依旧 | 来源:发表于2019-03-21 19:47 被阅读4次

    小程序 蓝牙自动连接

    1 初始化手机蓝牙

    . 初始化成后添加 监听蓝牙是否会异常断开,监听蓝牙因为距离,手机蓝牙关闭 等其他情况断开
    . 初始化成功后 监听蓝牙断开才能成功

    initBlue() {
        var that = this;
        wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
          success: function (res) {
            that.countdown()
            that.getTheBlueDisConnectWithAccident();//监听蓝牙是否会异常断开
            that.findBlue()
            that.setData({
              isBloothOpen:20
            })
            that.monitorTheBlue();
          },
    
          fail: function (res) {//如果手机上的蓝牙没有打开,可以提醒用户
          if(that.data.isFirestShow){
            wx.showToast({
              title: '请开启蓝牙',
              icon: 'fails',
              duration: 3000,
            })
          }
            that.setData({
              remaiderString: '等待连接',
              connectionEquipment: '请先打开手机蓝牙,等待连接分析仪',
              isBloothOpen: 10,
              isFirestShow: false,
            })
            console.log(res)
            console.log("蓝牙为打开");
            setTimeout(function () {
              that.initBlue();
            }, 3000) 
          }
        })
      },
    

    2 监听手机蓝牙开关 判定手机蓝牙是否打开

    判定手机蓝牙是否打开

    //监听手机蓝牙的开关
      monitorTheBlue:function(){
        var that =this;
        wx.onBluetoothAdapterStateChange(function(res){
          console.log(`adapterState changed, now is`, res)
          if (res.available){
            that.setData({
              isBloothOpen: 20,
              connectionEquipment: '请打开设备,并靠近手机',
            })
            wx.showToast({
              title: '蓝牙已开启',
              icon: 'fails',
              duration: 3000,
            })
          }else{
            that.setData({
              remaiderString: '等待连接',
              connectionEquipment: '请先打开手机蓝牙,等待连接分析仪',
              isBloothOpen: 10,
              isFirestShow: false,
            })
            wx.showToast({
              title: '蓝牙已关闭',
              icon: 'fails',
              duration: 3000,
            })
          }
        })
      },
    

    3 开始获取附近的蓝牙设备

    . 获取到附近的蓝牙数组 通过蓝牙特定的名称获取自己想要连接的蓝牙设备
    . 获取附近蓝牙设备的数组

    findBlue() {
        var that = this
        wx.startBluetoothDevicesDiscovery({
          allowDuplicatesKey: false,
          interval: 0,
         success: function (res) {
            if(that.data.isFirestShow){
              wx.showLoading({
                title: '正在搜索设备',
              })
            }
            that.getBlue()//3.0
            // that.stopFindBlue()
          },
          complete:function(){
          },
        })
      },
    

    4 搜索获取附近的所有蓝牙设备 获取附近所有的蓝牙设备的相关信息 获取需要连接蓝牙设备的deviceID

    . 通过bluetoothDeviceName 和 localName 来确定制定蓝牙
    . 一般根据制定设备的名字去连接 设备的名字 是出产厂家设定

    getBlue() {
        var that = this
        wx.getBluetoothDevices({
          success: function (res) {
            wx.hideLoading();
            console.log(res);
            var index = 10
            for (var i = 0; i < res.devices.length; i++) {
              if(res.devices[i].name && res.devices[i].localName){
                var arr = res.devices[i].name.split("-")
                var secArr = res.devices[i].localName.split("-")
                if (arr[0] == that.data.bluetoothDeviceName || secArr[0] == that.data.bluetoothDeviceName) {
                  console.log(that.data.bluetoothDeviceName);
                  index = 20
                  that.setData({
                    deviceId: res.devices[i].deviceId,
                    devices: res.devices,
                    connectionEquipment: '已连接到设备:' + res.devices[i].localName + '请开始测量',
                    remaiderString: '测量中',
                  })
                  console.log("设备:" + res.devices[i].deviceId + that.data.deviceId);
                  that.connetBlue();//4.0
                }
              }         
            }
            if(index == 10){
              if (that.data.isFirestShow) {
                that.showFailReminder("未搜索到配套设备")
              }
              that.setData({
                connectionEquipment: '请打开设备,并靠近手机',
                remaiderString: '等待连接',
              })
            }
          },
          fail: function () {
            if (that.data.isFirestShow) {
              that.showFailReminder("未搜索到配套设备")
            } 
            that.setData({
              connectionEquipment: '请打开设备,并靠近手机',
              remaiderString: '等待连接',
            })
          },
          complete:function(){
            that.setData({
              isFirestShow:false,
            })
          },
        })
      },
    

    5 连接蓝牙设备

    通过deviceId 连接蓝牙

    /**
      *  第四步 连接蓝牙设备
      */
      connetBlue(deviceId) {
        var that = this;
        wx.createBLEConnection({
          // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
          deviceId: that.data.deviceId,//设备id
          success: function (res) {
            that.setData({
              remaiderString: '正在测量',
            })
           wx.showToast({
              title: '连接成功',
              icon: 'success',
              duration: 1000
            })
          var isConnect = that.data.isConnected;
          if(isConnect == 10){
            that.getServiceId()//5.0
            that.setData({
              isConnected:20,
            })
          }
          },
          fail:function(res){
          },
        })
      },
    

    6 连接上需要的蓝牙设备之后,获取这个蓝牙设备的服务uuid

    获取设备的uuid

    getServiceId() {
        var that = this
        wx.getBLEDeviceServices({
          // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
          deviceId: that.data.deviceId,
         success: function (res) {
            var model = res.services[1]
            console.log(res)
            that.setData({
              servicesUUID: model.uuid
            })
           that.getCharacteId()//6.0
          }
        })
      },
    

    7 如果一个蓝牙设备需要进行数据的写入以及数据传输,就必须具有某些特征值,所以通过上面步骤获取的id可以查看当前蓝牙设备的特征值

    notify write read 当只有 notify为true的时候才能 接收蓝牙设备传来的数据,
    write 为true 才能传入数据
    read 为true 才能读取设备数据

    getCharacteId() {
        var that = this
        wx.getBLEDeviceCharacteristics({
          // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
          deviceId: that.data.deviceId,
          // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
          serviceId: that.data.servicesUUID,
          success: function (res) {
            console.log(res);
            for (var i = 0; i < res.characteristics.length; i++) {//2个值
              var model = res.characteristics[i]
              if (model.properties.notify == true) {
              that.setData({
                characteristicId: model.uuid//监听的值
              })
              that.startNotice(model.uuid)//7.0
              }
              if (model.properties.read == true) {
                that.readData(model.uuid)
              }
              if (model.properties.write == true) {
                that.setData({
                  writeId: model.uuid//用来写入的值
                })
              }
            }
          }
        })
      },
    

    8 如果一个蓝牙设备需要进行数据的写入以及数据传输,就必须具有某些特征值,所以通过上面步骤获取的id可以查看当前蓝牙设备的特征值

    开启设备数据监听 监听蓝牙设备返回来的数据

    startNotice(uuid) {
        var that = this;
        wx.notifyBLECharacteristicValueChange({
          state: true, // 启用 notify 功能
          deviceId: that.data.deviceId,
          serviceId: that.data.servicesUUID,
          characteristicId: uuid,  //第一步 开启监听 notityid  第二步发送指令 write
          success: function (res) {
            // 设备返回的方法
            wx.onBLECharacteristicValueChange(function (res) {
              console.log(res  + "蓝牙测试返回的数据" + res.value);
               var nonceId = that.ab2hex(res.value)
              }
              setTimeout(function () {
                that.setData({
                  isDeleteRepetition: 100,
                })
              }, 20000)       
            })
          },
          fail: function (res) {
            console.log(res);
          }
        })
      },
    
    /**
        * 将ArrayBuffer转换成字符串
        */
    ab2hex(buffer) {
        var hexArr = Array.prototype.map.call(
          new Uint8Array(buffer),
          function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
          }
        )
        return hexArr.join('');
      },
    

    10 监听异常断开

    . 当蓝牙设备异常断开时 就开始重新开启计时器
    . 注意异常返回 android 和iOS 返回的标示不是完全相同 使用res.connected 返回值来判定蓝牙是否连接

    //监听蓝牙设备是否会异常断开
      getTheBlueDisConnectWithAccident:function(e){
        var that = this;
        wx.onBLEConnectionStateChange(function (res) {
          console.log(res)
          if (!res.connected){
          wx.closeBluetoothAdapter({
            success: function(res) {
              wx.openBluetoothAdapter({
               success: function(res) {
                },
              })
            },
          })
            that.setData({
              showBacGroundImageView: '../../images/button_bg_disabled@2x.png',//背景图片
              remaiderString: "等待连接",
              ishindden: true,
              isSugarHidden: true,
              isConnected: 10,
              isFirestShow: false,
              testResultIndex: 0,
            })
            that.countdown()//开启计时
          } 
        })
      },
    

    11 异常断开再次开始

    . 我使用的是再次初始化 蓝牙 ,前面思路只是继续搜索蓝牙设备,但发现返回的数值一直都是一样的,比如设备的蓝牙已经关闭,但是设备数组中还是会有原来设备存在 但是就是连接不上

    // 倒计时
      countdown: function() {
        var that = this;
        that.init(that);          //这步很重要,没有这步,重复点击会出现多个定时器
        var time = that.data.time;
        console.log("倒计时开始")
        var interval = setInterval(function () {
          time--;
          that.setData({
            time: time
          })
          if (time == 0) {          //归0时回到60
              var countId = that.data.isConnected;
              if(countId == 10){
                that.restartTap();
                that.findBlue()
              }
              if(countId == 20){
                that.clearTimeInterval()
              }
          }
        }, 1000)
        that.setData({
          interval: interval
        })
      },
    

    12 存在问题

    . 当连接上蓝牙设备,接收蓝牙设备返回数据时候,一个数据会返回多次,是多次初始化的原因 还是蓝牙notify 被多次监听,请大牛该出手时就出手

    相关文章

      网友评论

        本文标题:微信小程序蓝牙自动连接

        本文链接:https://www.haomeiwen.com/subject/ovlfuqtx.html