微信小程序低功耗蓝牙开发,实现连接,监听接收数据

官方文档:
https://developers.weixin.qq.com/miniprogram/dev/api/device/bluetooth-ble/wx.writeBLECharacteristicValue.html

1. 初始化蓝牙设备
data:{
    getBlueToothString:'', // 读取蓝牙返回数据
    diaStatus:true,
    failText:'', // 错误提示
    notifyId:"",
    deviceId:'',// 蓝牙设备id
    progressTime:1,
    timesContorl:'', // 时间计时
    bluetooth:false, // 蓝牙连接
}
  initBluetooth() {
    var that = this;
    wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
      success: function (res) { 
        that.findBluetooth(); // 2.搜索蓝牙设备
      },
      fail: function (res) {  //如果手机上的蓝牙没有打开,可以提醒用户
        wx.showToast({
           title: '请开启蓝牙',
          icon: 'fails',
          duration: 1000
         })
      }
    })
  },
2. 搜索蓝牙设备
findBluetooth(){
var that = this
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: function (res) {
        console.log(res, 'find')
        wx.showLoading({
          title: '正在搜索设备',
        })
        that.getBluetooth()//3.获取搜索到的蓝牙设备信息
      }
    })
},
3.获取搜索到的蓝牙设备信息
getBluetooth(){
var that = this
    wx.getBluetoothDevices({
      success: function (res) {
        wx.hideLoading();
        console.log(res, 'getblue')
        let m = 0
        for (var i = 0; i < res.devices.length; i++) {
          if (res.devices[i].name == 'LP-100            ') { // 指定设备的name 或 deviceId
            console.log(res.devices[i].deviceId, '设备id')
            that.setData({
              deviceId: res.devices[i].deviceId,
              consoleLog: "设备:" + res.devices[i].deviceId,
            })
            m = 1
            that.connetBluetooth(res.devices[i].deviceId);//4 连接当前设备
            return;
          }
        }
        if(m == 0){ // 未找到指定设备,继续搜索
          that.findBluetooth() //
        }
      },
      fail: function () {
        console.log("搜索蓝牙设备失败")
      }
    })
}
4.连接设备
connetBluetooth(){
	var that = this;
	// 与对应设备创建连接
    wx.createBLEConnection({
      deviceId: deviceId,//设备id
      success: function (res) {
        wx.showToast({
          title: '连接成功',
          icon: 'fails',
          duration: 800
        })
        that.setData({ 
          diaStatus: true,
          bluetooth: true
        })
        console.log("连接蓝牙成功!")
        wx.stopBluetoothDevicesDiscovery({
          success: function (res) {
            console.log('连接蓝牙成功之后关闭蓝牙搜索');
          }
        })
        that.getServiceId()//5.获取蓝牙设备所有服务
      },
      fail:(res)=>{
        that.setData({
          failText:'蓝牙连接失败,是否重新连接',
          diaStatus:false,
        })
      }

    })
},
5.获取蓝牙设备所有服务
 getServiceId() {
    var that = this
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: that.data.deviceId,
      success: function (res) {
        console.log(res, '获取蓝牙设备服务', that.data.deviceId)
        // var model = res.services[0]
        res.services.forEach((item) =>{
          if (item.uuid == '00001000-0000-1000-8000-00805F9B34FB'){ // 有多个UUid,选择当前设备指定的UUid通道
            that.setData({
              services: item.uuid
            })
            that.getCharacteId()//6.获取蓝牙设备特殊值信息
          }
        })
        // 
       
      }
    })
  }
6.获取蓝牙设备特殊值信息,查看有哪些权限(read,notify,write)
  var that = this
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: that.data.deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: that.data.services,
      success: function (res) {
        console.log(res, '获取值', that.data.services, that.data.deviceId)
        var model = res.characteristics[0] 
        res.characteristics.forEach(item =>{
          if (item.uuid == '00001002-0000-1000-8000-00805F9B34FB'){ // 指定通道
            that.setData({
              notifyId: item.uuid//监听的值
            })
            that.startNotice(item.uuid)//7 开始通信
          }
        })
      }
    })
7.开始通信(项目只用到读取设备传过来的消息,不具有写的功能)
  startNotice(uuid) {
    var that = this;
    wx.notifyBLECharacteristicValueChange({
      state:true,
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
      deviceId: that.data.deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: that.data.services,
      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: uuid,  //第一步 开启监听 notityid 
      success: function (res) {
        console.log(res, 'resjieguo')
        // 设备返回的方法
        that.setData({
          getBlueToothString: ''
          })
        var getBlueToothstr = ''
        wx.onBLECharacteristicValueChange(function (res) {
          console.log(JSON.stringify(res))
          // 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,所以需要通过一个方法转换成字符串
          var nonceId = that.ab2hex(res.value)
          that.setData({
            getBlueToothString:  getBlueToothstr + nonceId,
            progressTime:100
          })
          console.log('over' , res.value, nonceId) // nonceId:设备传过来的值。
        })
      }

    })
  },

8.解析ArrayBuffer类型数据,查看设备传过来的值

  ab2hex(e) {
    for (var a = e, i = new DataView(a), n = "", s = 0; s < i.byteLength; s++) n += String.fromCharCode(i.getUint8(s));
    return n
  },

Tips:【小程序云开发】中高级前端面试题库(源码:小程序中联系我哟)。
---------- 创作不易,感谢大家,请多多支持!
在这里插入图片描述

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卜卦丶cc

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值