Code前端首页关于Code前端联系我们

微信小程序开发:如何使用接口连接蓝牙设备?

terry 2年前 (2023-09-23) 阅读数 70 #移动小程序

如何将小程序连接至蓝牙设备?

我实现的小程序模块的自动连接(如有需要可以改为手动连接)是在小程序初始化完成后自动启动的。

大致流程:

  1. 开启蓝牙适配;
  2. 获取蓝牙适配器的状态,判断设备蓝牙是否可用;
  3. 启用搜索蓝牙设备,并在判断蓝牙适配器是否可用时允许获取已连接的蓝牙设备;
  4. 成功启用搜索蓝牙设备后,将启用对扫描到的设备的监控;
  5. 如果扫描到的新设备包含特定的名称模式,则开始连接到该设备;
  6. 打开对连接的蓝牙设备的采集。成功后,连接特定名称模式的设备;
  7. 均无法找到合适的设备,请等待5秒后重新搜索;
  8. 开始 当有设备连接时,停止搜索设备并停止循环访问已连接的设备;
  9. 连接成功后,停止搜索设备并停止循环获取已连接的设备。

我们将在下面逐步完成这个过程。

一步步教你如何用小程序进行蓝牙连接

1.打开连接

app.jsonLaunch() 方法中,我们调用 this.startConnect (); 将,舞会。以实现适应。如果失败,它会警告您设备的蓝牙不可用,并启用蓝牙适配器运行状况监控。 ? false,表示用户没有打开系统的蓝牙。

同时我们判断程序还没有开始发现蓝牙设备,调用this.startBluetoothDevicesDiscovery()开始搜索附近的蓝牙设备。 ()获取本地蓝牙设备。已配对的蓝牙设备。

getBluetoothAdapterState: function () {
  var that = this;
  wx.getBluetoothAdapterState({
    success: function (res) {
      var available = res.available,
        discovering = res.discovering;
      if (!available) {
        wx.showToast({
          title: '设备无法开启蓝牙连接',
          icon: 'success',
          duration: 2000
        })
        setTimeout(function () {
          wx.hideToast()
        }, 2000)
      }
      else {
        if (!discovering) {
          that.startBluetoothDevicesDiscovery();
          that.getConnectedBluetoothDevices();
        }
      }
    }
  })
}

3。开始发现新设备

开始发现蓝牙设备 startBluetoothDevicesDiscovery() 请求蓝牙发现。?我从来没有见过有人填写过。如果不填写该属性和该方法,将无法获得配对资产。

调用该方法意味着你需要连接到特定的设备并知道该设备的主要服务serviceId

如果您还不知道ID,您可以手动连接一次想要连接的设备,然后在服务列表中记录primary属性♾ 。 true 该值至少为 1。

getConnectedBluetoothDevices: function () {
  var that = this;
  wx.getConnectedBluetoothDevices({
    services: [that.serviceId],
    success: function (res) {
      console.log("获取处于连接状态的设备", res);
      var devices = res['devices'],
        flag = false,
        index = 0,
        conDevList = [];
      devices.forEach(function (value, index, array) {
        if (value['name'].indexOf('FeiZhi') != -1) {
          // 如果存在包含FeiZhi字段的设备
          flag = true;
          index += 1;
          conDevList.push(value['deviceId']);
          that.deviceId = value['deviceId'];
          return;
        }
      });
      if (flag) {
        this.connectDeviceIndex = 0;
        that.loopConnect(conDevList);
      }
      else {
        if (!this.getConnectedTimer) {
          that.getConnectedTimer = setTimeout(function () {
            that.getConnectedBluetoothDevices();
          }, 5000);
        }
      }
    },
    fail: function (err) {
      if (!this.getConnectedTimer) {
        that.getConnectedTimer = setTimeout(function () {
          that.getConnectedBluetoothDevices();
        }, 5000);
      }
    }
  });
}

5。处理搜索功能未启动的情况

如果搜索功能未启动,请返回步骤2并再次检查蓝牙适配器。如果可用,成功启用蓝牙发现后,启用附近蓝牙设备上的事件监控:this.onBluetoothDeviceFound()

onBluetoothDeviceFound: function () {
  var that = this;
  console.log('onBluetoothDeviceFound');
  wx.onBluetoothDeviceFound(function (res) {
    console.log('new device list has founded')
    console.log(res);
    if (res.devices[0]) {
      var name = res.devices[0]['name'];
      if (name != '') {
        if (name.indexOf('FeiZhi') != -1) {
          var deviceId = res.devices[0]['deviceId'];
          that.deviceId = deviceId;
          console.log(that.deviceId);
          that.startConnectDevices();
        }
      }
    }
  })
}

可以自定义此方法来过滤一些无效的蓝牙设备,例如name为空,或者个人产品开发需要过滤设备名称中没有特定正则字符串的设备。 ? ()。

startConnectDevices: function (ltype, array) {
  var that = this;
  clearTimeout(that.getConnectedTimer);
  that.getConnectedTimer = null;
  clearTimeout(that.discoveryDevicesTimer);
  that.stopBluetoothDevicesDiscovery();
  this.isConnectting = true;
  wx.createBLEConnection({
    deviceId: that.deviceId,
    success: function (res) {
      if (res.errCode == 0) {
        setTimeout(function () {
          that.getService(that.deviceId);
        }, 5000)
      }
    },
    fail: function (err) {
      console.log('连接失败:', err);
      if (ltype == 'loop') {
        that.connectDeviceIndex += 1;
        that.loopConnect(array);
      }
      else {
        that.startBluetoothDevicesDiscovery();
        that.getConnectedBluetoothDevices();
      }
    },
    complete: function () {
      console.log('complete connect devices');
      this.isConnectting = false;
    }
  });
}

打开连接后,为了避免冲突,连接建立后,必须停止搜索附近的蓝牙设备,并停止读取该设备的配对设备。

7。连接成功后握手

连接成功后,使用接口this.getService(deviceId)访问设备的所有服务。 ? getConnectedBluetoothDevices() 获取设备配对的蓝牙设备,然后过滤设备(可能获取多个配对的蓝牙设备)。

将接收到的蓝牙设备deviceId列表放入数组中,然后调用自定义方法this.loopConnect();

思路:通过递归调用获取配对的蓝牙设备deviceId。如果有,请连接它。如果devicesId[x]为空,则表示在getConnectedBluetooth Devices()上传调用中,所有配对设备连接失败。

此时,我们需要启用检索已配对蓝牙设备的状态,并开始搜索附近的蓝牙设备。

loopConnect: function (devicesId) {
  var that = this;
  var listLen = devicesId.length;
  if (devicesId[this.connectDeviceIndex]) {
    this.deviceId = devicesId[this.connectDeviceIndex];
    this.startConnectDevices('loop', devicesId);
  }
  else {
    console.log('已配对的设备小程序蓝牙连接失败');
    that.startBluetoothDevicesDiscovery();
    that.getConnectedBluetoothDevices();
  }
}

10。自动连接蓝牙设备

startConnectDevices('loop', array) 方法在获取要连接的配对蓝牙设备时调用。上面贴出了

的处理逻辑,也就是说连接失败后,fail方法会累加一个全局变量,然后回调loopConnect(array)。

11。手动连接

以上介绍的方法是直接自动连接。如果不需要自动连接,您可以使用 getBluetoothDevices() 方法检索扫描到的蓝牙设备列表。

开发者可以创建一个页面来显示设备名称,然后点击设备即可开始连接。

需要注意的是

  • .serviceId是在初始化时设置的。这是可以完成的,因为主要服务标识符和要连接的设备的各种特征是已知的。如果不知道,可以自己制作一个扫描方法来检查特征值目标。
  • 连接成功后,记下操作writeBLECharacteristicValueopenNotifyService。如果同时打开这两个动作,先开启wirte notify(原因不明,个人经验)。
  • 3。有人提醒我,您可以通过在onBlueToothAdapterStateChange()中监视蓝牙适配器状态来进一步改进它,以确定用户在连接过程中或连接后是否打开或关闭了设备的蓝牙。如果发现蓝牙关闭,系统会提示您打开蓝牙;如果您发现蓝牙已打开,请返回步骤 1。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门