微信小程序—调用扫一扫功能,通过扫描二维码连接蓝牙模块

使用微信小程序的扫码功能连接蓝牙,具体操作如下

实现流程图

Created with Raphaël 2.2.0 准备好二维码 小程序调用扫码功能 小程序获取到二维码内容(我这里为蓝牙的名字) 小程序通过搜索到该蓝牙名后连接 结束

首先,准备需要使用的二维码
这里我们可以使用网上的二维码生成器,把需要的信息写入然后就能自动生成二维码了。我使用的是蓝牙的名字
使用蓝牙的名字生成一个二维码

调用微信小程序的蓝牙扫码功能
界面

在这里插入图片描述
以下是该功能代码

// index.wxml
<button class='btn1'  bindtap="click">
    <image class='btnImg' src='../../images/button.png'></image>扫码
 </button>
// index.js
Page({
  data: {
    deviceName: "",
  },
  onLoad: function () {
  },
  onShow: function () {
  },
 
  /* 点击事件 */
  click: function (event) { 
    var that = this;
    //调用扫码功能
    wx.scanCode({
      success: (res) => {
        console.log(res)
        that.setData({
          deviceName: res.result
        })
        //获取到二维码中的蓝牙设备名后跳转到连接页面
              var title = that.data.deviceName;
              wx.redirectTo({
                url: '../detail/detail?id=' + title
              })   
      },
      fail: (res) => {
        wx.showToast({
          title: '扫码失败',
          icon: 'success',
          duration: 2000
        })
      },
    })  
  },
})

通过二维码获取到蓝牙设备名后连接
下面直接贴代码,只需要修改js就够了

//detail.js
data: {
    deviceId: '',
  },
  //获取二维码中的蓝牙name,然后连接
  onLoad: function(options) {
    wx.showLoading({
      title: '请打开蓝牙',
    });
    console.log(options);
    this.setData({
      deviceName: options.id,
    });
    console.log('设备的Name', this.data.deviceName);
    var that = this;

    var deviceName = options.id;
    wx.closeBluetoothAdapter({
      success: function(res) {
        console.log('关闭蓝牙模块');
        /* 初始化蓝牙适配器 */
        wx.openBluetoothAdapter({
          success: function(res) {
            console.log('初始化蓝牙适配器成功');
            wx.hideLoading();
            wx.showLoading({
              title: '请稍后....',
            });
            wx.startBluetoothDevicesDiscovery({
              allowDuplicatesKey: false,
              success: function(res) {
                console.log('这里是开始搜索附近设备', res);
                //添加延迟
                setTimeout(() => {
                  wx.getBluetoothDevices({
                    success: function(res) {
                      console.log(res)
                      //在搜索到的所有蓝牙中找到需要连接的那一个蓝牙
                      for (var i = 0; i < res.devices.length; i++) {
                        if (res.devices[i].name == deviceName) {
                          that.setData({
                            deviceId: res.devices[i].deviceId,
                          })
                          console.log(res.devices[i].deviceId)
                          wx.hideLoading();
                          /* 连接中动画 */
                          wx.showLoading({
                            title: '正在连接...',
                          });
                          that.CreateBLEConnection();
                        }
                      }
                    },
                    fail: function() {
                      console.log("搜索蓝牙设备失败")
                    }
                  });
                }, 1300);
              },
            });
          },
        })
      }
    });
  },
  //连接蓝牙
  CreateBLEConnection: function() {   
    var that = this;
    wx.stopBluetoothDevicesDiscovery({
      success: function(res) {
        console.log('停止搜索设备', res)
      }
    })
    /* 开始连接蓝牙设备 */
    wx.createBLEConnection({
      deviceId: that.data.deviceId,
      success: function(res) {
        console.log('连接成功', res);
        wx.hideLoading();
        /* 获取设备的服务UUID */
        wx.getBLEDeviceServices({
          deviceId: that.data.deviceId,
          success: function(service) {
            var all_UUID = service.services; //取出所有的服务
            console.log('所有的服务', all_UUID);
            var UUID_lenght = all_UUID.length; //获取到服务数组的长度
            /* 遍历服务数组 */
            for (var index = 0; index < UUID_lenght; index++) {
              var ergodic_UUID = all_UUID[index].uuid; //取出服务里面的UUID
              var UUID_slice = ergodic_UUID.slice(4, 8); //截取4到8位
              /* 判断是否是我们需要的FFE0 */
              if (UUID_slice == 'FFE0' || UUID_slice == 'ffe0') {
                var index_uuid = index;
                that.setData({
                  serviceId: all_UUID[index_uuid].uuid //确定需要的服务UUID
                });
              };
            };
            console.log('需要的服务UUID', that.data.serviceId)
            that.Characteristics(); //调用获取特征值函数
          },
        });
      },
    })
  },
  Characteristics: function() {
    var that = this;
    var device_characteristics = [];
    var characteristics_uuid = {};
    wx.getBLEDeviceCharacteristics({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      success: function(res) {
        var characteristics = res.characteristics; //获取到所有特征值
        var characteristics_length = characteristics.length; //获取到特征值数组的长度
        console.log('获取到特征值', characteristics);
        console.log('获取到特征值数组长度', characteristics_length);

        /* 遍历获取characteristicsId */
        for (var index = 0; index < characteristics_length; index++) {
          var characteristics_UUID = characteristics[index].uuid; //取出特征值里面的UUID
          var characteristics_slice = characteristics_UUID.slice(4, 8); //截取4到8位
          /* 判断是否是我们需要的FFE1 */
          if (characteristics_slice == 'FFE1' || characteristics_slice == 'ffe1') {
            var index_uuid = index;
            that.setData({
              characteristicsId: characteristics[index_uuid].uuid //确定的写入UUID
            });
          };
        };
        console.log('写入characteristicsId', that.data.characteristicsId);
        that.SendTap(); //发送指令
      },
    })
  },
  /* 发送指令 */
  SendTap: function() {
    var that = this;
    var value_ascii = "";
    var value_initial = "01"; //发送的信息
    console.log('输入框中的值', value_initial);
    /* 以Ascii字符发送 */
    var value_split = value_initial.split(''); //将字符一个一个分开
    console.log('value_split', value_split);
    for (var i = 0; i < value_split.length; i++) {
      value_ascii = value_ascii + value_split[i].charCodeAt().toString(16); //转为Ascii字符后连接起
    }
    var value = value_ascii;
    console.log('转为Ascii码值', value);
    var write_function = that.write(value); //调用数据发送函数
  },
  write: function(str) {
    var that = this;
    var value = str;
    console.log('value', value);
    /* 将数值转为ArrayBuffer类型数据 */
    var typedArray = new Uint8Array(value.match(/[\da-f]{2}/gi).map(function(h) {
      return parseInt(h, 16)
    }));
    var buffer = typedArray.buffer;
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.characteristicsId,
      value: buffer,
      success: function(res) {
        console.log('数据发送成功', res);
        wx.showToast({
          title: '发送成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function(res) {
        console.log('调用失败', res);
        /* 调用失败时,再次调用 */
        wx.writeBLECharacteristicValue({
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.characteristicsId,
          value: buffer,
          success: function(res) {
            console.log('第2次数据发送成功', res);
            wx.showToast({
              title: '发送成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail: function(res) {
            console.log('第2次调用失败', res);
            /* 调用失败时,再次调用 */
            wx.writeBLECharacteristicValue({
              deviceId: that.data.deviceId,
              serviceId: that.data.serviceId,
              characteristicId: that.data.characteristicsId,
              value: buffer,
              success: function(res) {
                console.log('第3次数据发送成功', res);
                wx.showToast({
                  title: '发送成功',
                  icon: 'success',
                  duration: 2000
                })
              },
              fail: function(res) {
                console.log('第3次调用失败', res);
              }
            });
          }
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var that = this;
    wx.closeBLEConnection({
      deviceId: that.data.deviceId,
      success: function(res) {
        console.log('断开设备连接', res);
      }
    });
  },
})

注意:代码中的UUID提取出的FFE0,FFE1是我自己的设备的,不同的蓝牙UUID也会不同,需要自己修改,这数据一般在自己使用蓝牙模块的介绍文档里给出

  • 12
    点赞
  • 72
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
微信小程序可以通过使用wx.getBluetoothAdapter方法获取蓝牙适配器实例,并且可以通过调用适配器的方法来搜索、连接和通信蓝牙设备。 首先,你需要在小程序的app.json文件中声明蓝牙权限: ```json { "permissions": { "bluetooth": true } } ``` 然后,在小程序的页面中,你可以调用以下代码实现扫描二维码自动连接蓝牙设备的功能: ```javascript // 扫描二维码 wx.scanCode({ success: function(res) { // 获取扫描得到的二维码内容 var qrcode = res.result; // 连接蓝牙设备 wx.getBluetoothAdapterState({ success: function(stateRes) { if (stateRes.available) { wx.startBluetoothDevicesDiscovery({ success: function(discoveryRes) { // 监听蓝牙设备发现事件 wx.onBluetoothDeviceFound(function(deviceRes) { var devices = deviceRes.devices; for (var i = 0; i < devices.length; i++) { var device = devices[i]; if (device.advertisServiceUUIDs.indexOf(qrcode) !== -1) { // 连接指定的蓝牙设备 wx.createBLEConnection({ deviceId: device.deviceId, success: function(connectRes) { // 连接成功后的操作 } }); } } }); } }); } } }); } }); ``` 上述代码首先调用wx.scanCode方法扫描二维码,并获取到二维码内容。然后调用wx.getBluetoothAdapterState方法获取蓝牙适配器的状态,如果蓝牙适配器可用,则调用wx.startBluetoothDevicesDiscovery方法开始搜索蓝牙设备。使用wx.onBluetoothDeviceFound方法监听蓝牙设备发现事件,当发现设备时,根据二维码内容匹配设备的服务UUID,然后调用wx.createBLEConnection方法连接指定的蓝牙设备。 请注意,上述代码仅为示例,具体的实现方式需要根据你的业务需求和蓝牙设备的特性进行调整。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值