微信小程序蓝牙自动连接

小程序 蓝牙自动连接

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 被多次监听,请大牛该出手时就出手

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容