您好,小程序模板欢迎您。
小程序模板
当前位置 : 首页> 小程序教程> 微信小程序蓝牙自动连接功能

微信小程序蓝牙自动连接功能

1.   如果是新设备,需要搜索并连接新设备

// 在页面onLoad方法中调用该方法
searchAndConnect: function() {
  // 开始搜索设备
  wx.startBluetoothDevicesDiscovery({
    success: function(res) {
      // 监听设备发现事件
      wx.onBluetoothDeviceFound(function(res) {
        // 遍历设备列表,查找需要连接的设备
        for (var i = 0; i < res.devices.length; i++) {
          var device = res.devices[i];
          if (device.name == "需要连接的设备名称") {
            // 停止搜索设备
            wx.stopBluetoothDevicesDiscovery({
              success: function(res) {
                // 连接设备
                wx.createBLEConnection({
                  deviceId: device.deviceId,
                  success: function(res) {
                    console.log("连接成功");
                  },
                  fail: function(res) {
                    console.log("连接失败");
                  }
                });
              }
            });
            break;
          }
        }
      });
    }
  });
}

请注意,此代码仅适用于搜索并连接新设备。如果需要连接已配对的设备,则需要使用 wx.getBluetoothDevices 方法获取已配对的设备列表。


 2.  已配对的设备连接

// 在页面onLoad方法中调用该方法
autoConnect: function() {
  // 获取已配对的设备列表
  wx.getBluetoothDevices({
    success: function(res) {
      // 遍历设备列表,查找需要连接的设备
      for (var i = 0; i < res.devices.length; i++) {
        var device = res.devices[i];
        if (device.name == "需要连接的设备名称") {
          // 连接设备
          wx.createBLEConnection({
            deviceId: device.deviceId,
            success: function(res) {
              console.log("连接成功");
            },
            fail: function(res) {
              console.log("连接失败");
            }
          });
          break;
        }
      }
    }
  });
}

请注意,此代码仅适用于已配对的设备。如果需要搜索并连接新设备,则需要使用 wx.startBluetoothDevicesDiscovery 方法来搜索设备。

联系客服 意见反馈

签到成功!

已连续签到1天,签到3天将获得积分VIP1天

知道了