微信小程序-蓝牙链接

最近的项目须要使用小程序的蓝牙功能与硬件设备进行链接相互传送数据指令,联调过程当中发现一些问题,因而想着记录下来,方便之后查看!小程序

1.0通常使用蓝牙功能确定是想链接某一个蓝牙设备,因此须要知道这个蓝牙设备的名称,通常来讲都是扫描二维码链接,那么当你扫描这个设备二维码的时候,就须要去初始化你手机上的蓝牙模块了微信小程序

/**
   * 初始化蓝牙设备
   */
  initBlue:function(){
    var that = this;
    wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
      success: function (res) {
        // console.log(res)
        wx.showToast({
          title: '初始化成功',
          icon: 'success',
          duration: 800
        })
        that.findBlue();//2.0
      },
      fail: function (res) {//若是手机上的蓝牙没有打开,能够提醒用户
        wx.showToast({
          title: '请开启蓝牙',
          icon: 'fails',
          duration: 1000
        })
      }
    })
  },
 

 

2.0 手机蓝牙初始化成功以后,就会去搜索周边的蓝牙设备
 
/**
  *开始搜索蓝牙设备
*/
findBlue(){
    var that = this
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: function (res) {
       
        wx.showLoading({
          title: '正在搜索设备',
        })
        that.getBlue()//3.0
      }
    })
  },

 

3.0搜索蓝牙设备以后,须要获取搜索到的蓝牙设备信息,微信小程序提供了两个方法能够获取搜索到的蓝牙设备信息,分别是:api

  wx.onBluetoothDeviceFound(监听寻找到新设备的事件 ——表示只要找到一个新的蓝牙设备就会调用一次该方法)服务器

  wx.getBluetoothDevices(获取在蓝牙模块生效期间全部已发现的蓝牙设备。包括已经和本机处于链接状态的设备)微信

看两个方法的介绍咱们知道他们的区别,可是不了解他们的区别会形成什么样的问题?网络

第一次我使用的是wx.onBluetoothDeviceFound方法进行联调,发现一切正常,因为调试的时候就只有一台设备,发现第二次从新扫码这个蓝牙设备的时候,找不到这个设备了,由于对这个方法来讲,这不是一个新的设备,之前链接上过;或者当你由于某些缘由蓝牙传送数据指令的时候出错了须要从新链接,再次链接的时候也找不到当前设备,仍是一样的缘由,由于当前设备对这个方法来讲不是一个新设备ide

因此后来我就用了wx.getBluetoothDevices方法网站

/**
  * 获取搜索到的设备信息
 */
  getBlue(){
    var that = this
    wx.getBluetoothDevices({
      success: function(res) {
        wx.hideLoading();
        for (var i = 0; i < res.devices.length; i++){
   //that.data.inputValue:表示的是须要链接的蓝牙设备ID,简单点来讲就是我想要链接这个蓝牙设备,因此我去遍历我搜索到的蓝牙设备中是否有这个ID
          if (res.devices[i].name == that.data.inputValue || res.devices[i].localName == that.data.inputValue){
            that.setData({
              deviceId: res.devices[i].deviceId,
              consoleLog: "设备:" + res.devices[i].deviceId,
            })
            that.connetBlue(res.devices[i].deviceId);//4.0
            return;
          }
        }
      },
      fail: function(){
        console.log("搜索蓝牙设备失败")
      }
    })
  },

 

 
4.0经过3.0步骤找到这个蓝牙以后,经过蓝牙设备的id进行蓝牙链接
/**
  * 获取到设备以后链接蓝牙设备
 */
  connetBlue(deviceId){                    
    var that = this;
    wx.createBLEConnection({
      // 这里的 deviceId 须要已经经过 createBLEConnection 与对应设备创建连接
      deviceId: deviceId,//设备id
      success: function (res) {
        wx.showToast({
          title: '链接成功',
          icon: 'fails',
          duration: 800
        })
        console.log("链接蓝牙成功!")
        wx.stopBluetoothDevicesDiscovery({
          success: function (res) {
            console.log('链接蓝牙成功以后关闭蓝牙搜索');
          }
        })
        that.getServiceId()//5.0
      }
    })
  },

 

 
5.0链接上须要的蓝牙设备以后,获取这个蓝牙设备的服务uuid
getServiceId(){
    var that = this
    wx.getBLEDeviceServices({
      // 这里的 deviceId 须要已经经过 createBLEConnection 与对应设备创建连接
      deviceId: that.data.deviceId,
      success: function (res) {
        var model = res.services[0]
        that.setData({
          services: model.uuid
        })
        that.getCharacteId()//6.0
      }
    })
  },

 

 
6.0若是一个蓝牙设备须要进行数据的写入以及数据传输,就必须具备某些特征值,因此经过上面步骤获取的id能够查看当前蓝牙设备的特征值
getCharacteId(){
    var that = this 
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 须要已经经过 createBLEConnection 与对应设备创建连接
      deviceId: that.data.deviceId,
      // 这里的 serviceId 须要在上面的 getBLEDeviceServices 接口中获取
      serviceId: that.data.services,
      success: function (res) {
        for (var i = 0; i < res.characteristics.length; i++) {//2个值
          var model = res.characteristics[i]
          if (model.properties.notify == true) {
            that.setData({
              notifyId: model.uuid//监听的值
            })
            that.startNotice(model.uuid)//7.0
          }
          if (model.properties.write == true){
            that.setData({
              writeId: model.uuid//用来写入的值
            })
          }
        }
      }
    })
  },

 

 
7.0
startNotice(uuid){
    var that = this;
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      // 这里的 deviceId 须要已经经过 createBLEConnection 与对应设备创建连接 
      deviceId: that.data.deviceId,
      // 这里的 serviceId 须要在上面的 getBLEDeviceServices 接口中获取
      serviceId: that.data.services,
      // 这里的 characteristicId 须要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: uuid,  //第一步 开启监听 notityid  第二步发送指令 write
      success: function (res) {
      
          // 设备返回的方法
          wx.onBLECharacteristicValueChange(function (res) {
              // 此时能够拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,因此须要经过一个方法转换成字符串
              var nonceId = that.ab2hex(res.value) 
      //拿到这个值后,确定要去后台请求服务(当前步骤根据当前需求本身书写),获取下一步操做指令写入到蓝牙设备上去
      
     wx.request({
                    method: "POST",
         
                    data: {
                      xx:nonceId
                    },
                    url: url,
                    success: (res) => {
                      //res.data.data.ciphertext:我这边服务返回来的是16进制的字符串,蓝牙设备是接收不到当前格式的数据的,须要转换成ArrayBuffer
                      that.sendMy(that.string2buffer(res.data.data.ciphertext))//8.0
                      // 服务器返回一个命令  咱们要把这个命令写入蓝牙设备
                    }
                   })
  }
    })
  },

 

 
8.0 将从后台服务获取的指令写入到蓝牙设备当中
sendMy(buffer){
    var that = this 
    wx.writeBLECharacteristicValue({
      // 这里的 deviceId 须要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId: that.data.deviceId,
      // 这里的 serviceId 须要在上面的 getBLEDeviceServices 接口中获取
      serviceId: that.data.services,
      // 这里的 characteristicId 须要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: that.data.writeId,//第二步写入的特征值
      // 这里的value是ArrayBuffer类型
      value: buffer,
      success: function (res) {
        console.log("写入成功")
      },
      fail: function () {
        console.log('写入失败')
      },
      complete:function(){
        console.log("调用结束");
      }
    })
  },

 

 
//ps:下面是须要使用到的两个格式相互转换的方法
/**
* 将字符串转换成ArrayBufer
*/
  string2buffer(str) {
    let val = ""
    if(!str) return;
    let length = str.length;
    let index = 0;
    let array = []
    while(index < length){
      array.push(str.substring(index,index+2));
      index = index + 2;
    }
    val = array.join(",");
    // 将16进制转化为ArrayBuffer
    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    })).buffer
  },
 
  /**
   * 将ArrayBuffer转换成字符串
   */
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
 

 

 
//PS:以上是蓝牙链接的所有流程,可是咱们在实际使用中确定不会这么顺畅,并且蓝牙发送指令的设备都会有一个特性,就是当前蓝牙设备有人链接上以后,其余人是搜索不到这个蓝牙设备的,因此你须要考虑在某些个特殊状况,代码里须要主动断开蓝牙链接把设备释放出来供其余用户使用,还有就是将指令写入蓝牙设备的时候很容易出问题,因此要写个回调去屡次写入,保证成功性!第一次写博客,不正确的地方,欢迎你们讨论,谢谢!
 
有些人会用小程序蓝牙功能去连接另外的手机蓝牙,可是发现搜索不到蓝牙信息,因此说明一下:微信小程序官方文档上说:支持低功耗蓝牙设备

BLE低功耗蓝牙具备如下要求的应用:ui

1.通讯距离长达100米左右。不少低功耗蓝牙须要使用纽扣电池运行。不少的物联网设备须要使用标准纽扣电池运行不少年。BLE低功耗蓝牙可实现超低的峰值、均衡和空闲模式的功耗。另外,低占空比设备还能节省更多电能。this

2.多智能厂商互操做性。做为一个标准协议,BLE低功耗蓝牙与此前的蓝牙版本同样,也获得了主设备制造商的普遍采用。也有不少的物联网从设备也支持BLE低功耗蓝牙。安卓、iOS、Windows 十、Linux等主流操做系统均原生支持BLE低功耗蓝牙。预测,到2020年,95%的智能手机都将支持BLE低功耗蓝牙。而这个生态系统将有助于实现多厂商互操做性。

3.BLE低功耗蓝牙是搭建集体、家庭、我的网络的最佳选择,可经过无线方式将供电型智能设备链接至手机或计算机。所以,愈来愈多的智能穿戴设备、计算机/手机外设和医疗监测设备将BLE低功耗蓝牙视为了首选通讯协议。在蓝牙技术联盟的网站上也列出了不少不一样支持智能蓝牙协议的产品和蓝牙智能设备产品。这直接代表了BLE低功耗蓝牙通讯协议在物联网应用领域的重要性。

相关文章
相关标签/搜索