当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 微信小程序-蓝牙连接

微信小程序-蓝牙连接

2018年11月12日  | 移动技术网IT编程  | 我要评论

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

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搜索蓝牙设备之后,需要获取搜索到的蓝牙设备信息,微信小程序提供了两个方法可以获取搜索到的蓝牙设备信息,分别是:

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

  wx.getbluetoothdevices(获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备)

看两个方法的介绍我们知道他们的区别,但是不了解他们的区别会造成什么样的问题?

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

所以后来我就用了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:以上是蓝牙连接的全部流程,但是我们在实际使用中肯定不会这么顺畅,而且蓝牙发送指令的设备都会有一个特性,就是当前蓝牙设备有人连接上之后,其他人是搜索不到这个蓝牙设备的,所以你需要考虑在某些个特殊情况,代码里需要主动断开蓝牙连接把设备释放出来供其他用户使用,还有就是将指令写入蓝牙设备的时候很容易出问题,所以要写个回调去多次写入,保证成功性!第一次写博客,不正确的地方,欢迎大家讨论,谢谢!

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网