微信小程序对接蓝牙设备连接全过程

初始化蓝牙


initBlue(){
    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: 'error',
          duration: 1000
        })
      }
    })
  },

搜索蓝牙设备,本来参照大佬的例子是下面再次安全检索,但是由于小程序开发更新,需要调用新的接口onBluetoothDeviceFound才能搜索到所有设备,因此改进了一些。


//搜索蓝牙设备
  findBlue(){
    var that = this
    //开始搜索蓝牙
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: function (res) {
        console.log(res);
        
        wx.showLoading({
          title: '正在搜索设备',
        })
        // that.getBlue()//3.0
      }
    })
    wx.onBluetoothDeviceFound((res)=>{
      const device = res.devices[0]
      if (device.name == that.data.value || device.localName == that.data.value){
        console.log(device);
        
        that.setData({
          deviceId: device.deviceId,
        })
        that.data.deviceId=device.deviceId;
        
        wx.hideLoading()
        wx.offBluetoothDeviceFound()
        wx.stopBluetoothDevicesDiscovery();
        wx.showToast({
          title: '正在连接',
          icon: 'loading',
          duration: 800
        })
        that.connetBlue(device.deviceId);//4.0
      }
    })
  },

连接蓝牙设备

// 连接蓝牙设备
  connetBlue(deviceId){                    
    var that = this;
    wx.createBLEConnection({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: deviceId,//设备id
      success: function (res) {
        console.log("res",res)
        wx.showToast({
          title: '连接成功',
          icon: 'success',
          duration: 800
        })
        that.getServiceId()//5.0
      }
    })
  },

获取蓝牙设备上所有服务

// 获取蓝牙设备上所有服务
    // 连接上需要的蓝牙设备之后,获取这个蓝牙设备的服务uuid
    getServiceId(){
      var that = this
      wx.getBLEDeviceServices({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: that.data.deviceId,
        success: function (res) {
          console.log(res)
          console.log(that.data.deviceId)
          var item = res.services[1];
          that.setData({
            services: item.uuid
          })
          that.getCharacteId(that.data.deviceId,that.data.services)//6.0
        },
        fail(err){
          console.log(err);
        }
      })
    },

获取蓝牙设备某个服务中所有特征值


//获取蓝牙设备某个服务中所有特征值
  getCharacteId(deviceId,services){
    var that = this 
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId:that.data.deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId:that.data.services,
      success: function (res) {
        console.log(res)
        for (var i = 0; i < res.characteristics.length; i++) {//2个值
          var item = res.characteristics[i];
          if(item.properties.indicate||item.properties.notify){
            that.setData({
              propertiesuuId: item.uuid,
            })
            that.startNotice(that.data.propertiesuuId)//7.0
          }
          if (item.properties.write == true){
            that.setData({
              writeId: item.uuid//用来写入的值
            })
          }
        }
      },
      fail(err){
        console.log("getBLEDeviceCharacteristics",err);
      }
    })
  },

创建连接,发送指令

//创建连接,发送指令
  startNotice(uuid){
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      deviceId: this.data.deviceId,
      serviceId: this.data.services,
      characteristicId: uuid,  //第一步 开启监听 notityid  第二步发送指令 write
      success: (res) => {
        console.log("aaaa")
        // 设备返回的方法
        wx.onBLECharacteristicValueChange((res) => {
          // 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,
          //所以需要通过一个方法转换成字符串
          var nonceId = this.ab2hex(res.value) 
          console.log(nonceId)
      //拿到这个值后,肯定要去后台请求服务(当前步骤根据当前需求自己书写),
      //获取下一步操作指令写入到蓝牙设备上去
       wx.request({
             method: "POST",
        data: {
              describe:nonceId
             },
             url: 'http:192.168.4.45:5500',
             success: (res) => {
               //res.data.data.ciphertext:我这边服务返回来的是16进制的字符串,
               //蓝牙设备是接收不到当前格式的数据的,需要转换成ArrayBuffer
               console.log(res.data.data.ciphertext)
               console.log(this.string2buffer(res.data.data.ciphertext))
              //  this.sendMy(this.string2buffer(res.data.data.ciphertext))//8.0
             // 服务器返回一个命令  我们要把这个命令写入蓝牙设备
             }
            })
          })
       }
    })
  }