小程序:ble蓝牙连接

1.定义数据变量

   bleList: [],
    deviceId: '',    //设备蓝牙deviceId
    services: '',    //蓝牙的uuid
    notifyId: '',    //开启notify接收
    writeId: '',    //接收写入的值

2.初始化蓝牙

  initBlue() {
    wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
      success: (res)=> {
        UI.showToast({
          title: '初始化成功',
          icon: 'success',
          duration: 800
        })
        // this.findBlue();//2.0
      },
      fail: function (res) {//如果手机上的蓝牙没有打开,可以提醒用户
        UI.showToast({
          title: '请开启蓝牙',
          icon: 'fails',
          duration: 1000
        })
      }
    })
  },

3.搜索蓝牙

  findBlue() {
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success:(res) =>{
        console.log(res);
        UI.showLoading({
          title: '正在搜索设备',
        })
        this.getBlue()//3.0
      }
    })
  },

4.获取到蓝牙设备信息

 getBlue() {
    wx.getBluetoothDevices({
      success: (res) => {
        wx.hideLoading();
        this.setData({
          bleList: res.devices
        })
      },
      fail: () => {
        UI.showToast({
          title: '搜索蓝牙设备失败'
        })
      }
    })
  },

5.获取到设备之后连接蓝牙设备

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

6.获取蓝牙设备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
      }
    })
  },

7.写入蓝牙数据

  getCharacteId() {
    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 model = res.characteristics[i]
          if (model.properties.write == true) {
            that.setData({
              writeId: model.uuid//用来写入的值
            })
          }
          if (model.properties.notify == true) {
            that.setData({
              notifyId: model.uuid//监听的值
            })
            that.startNotice(model.uuid)//7.0
          }
        }
      }
    })
  },

8.创建连接(注意:写入我们想传输的数据之前需要先开启notify功能)

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: (res) => {
        //跳转到配置wifi页面
        that.sendMy()
        that.receiveClick()
      },
      fail: (err) => {
        UI.showToast({

        })
        console.log(err);
      }
    })

  },

9.接收数据

receiveClick(){
  console.log('开始接收数据');
  wx.onBLECharacteristicValueChange( (res)=> {
      console.log(res,333);
    // this.packDecoder(res.value)
    // console.log("characteristicId:" + res.characteristicId)
    // console.log("serviceId:" + res.serviceId)
    // console.log("deviceId" + res.deviceId)
    // console.log("Length:" + res.value.byteLength)
    // console.log("hexvalue:" + this.ab2hex(res.value))
    // that.setData({
    //   info: that.data.info + ab2hex(res.value)
    // })

  })

10.写入数据

//将请求的数据写入到蓝牙里面
sendMy(buffer){
  var that = this 
  var hex = buffer  //要发送的信息
    console.log('要发送的信息是:'+hex)
    // var buf = new ArrayBuffer(hex.length * 2); // 每个字符占用2个字节
    // var buf = new ArrayBuffer(7);
  var bufView = new Uint8Array([0xA1,0x03,0x00,0x00,0x00,0x00,0x00]);
  var arrayBuffer = bufView.buffer;
  // for (var i = 0, strLen = hex.length; i < strLen; i++) {
  //   bufView[i] = hex.charCodeAt(i);
  // }
    // var buffer1 = typedArray.buffer
    var buffer1 = arrayBuffer
    console.log(buffer1);

  wx.writeBLECharacteristicValue({
    // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId: that.data.deviceId,
    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
    serviceId: that.data.services,
    // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
    characteristicId: that.data.writeId,//第二步写入的特征值
    // 这里的value是ArrayBuffer类型
    value: buffer1,
    success: function (res) {
      console.log("写入成功",res)
    },
    fail: function (err) {
      console.log('写入失败',err)
    },
    complete:function(){
      console.log("调用结束");
    }
  })
},

11.转换

/**
* 将字符串转换成ArrayBufer
*/
string2buffer(str) {
  var hex = str  //要发送的信息
     var typedArray = new Uint16Array(hex.match(/[\u4E00-\u9FA5\u0F00-\u0FFFa-zA-Z\d\s\u3002\uff01-\uff1f\u3001-\u301f\u2013-\u201f\x20-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E$]/gi).map(function (h) {
      return parseInt(h, 16)
    }))
    return  typedArray.buffer

},
  /**
   * 将ArrayBuffer转换成字符串
   */
  // String.fromCharCode.apply(null, new Uint8Array(buf));
  ab2hex(buffer) {
    let  encodedString = String.fromCodePoint.apply(null, new Uint8Array(buffer));
    return encodedString
  },

猜你喜欢

转载自blog.csdn.net/fankse/article/details/112532217