uniapp 蓝牙自动会连,设备断开,无法监听问题解决

2024-06-16  本文已影响0人  小李不小

重点:断开蓝牙,遇到 onBLEConnectionStateChange 监听时间无响应,就断开事件之后再执行一次就可以了。

在微信小程序中,当蓝牙设备连接断开后,需要重新调用wx.onBLEConnectionStateChange方法进行重新监听蓝牙连接状态。以下是一个示例代码,展示了在蓝牙设备连接断开后重新监听连接状态的方法:

// 定义全局变量保存连接状态
let isConnected = false;
let deviceId = ''; // 设备ID

// 监听蓝牙连接状态改变
wx.onBLEConnectionStateChange(function (res) {
  console.log(`Bluetooth connection state has changed: ${res.deviceId}, connected: ${res.connected}`);
  isConnected = res.connected;

  // 如果连接断开了,可以在这里重新连接
  if (!isConnected) {
    console.log('Bluetooth connection is disconnected, trying to reconnect...');

    wx.createBLEConnection({
      deviceId: deviceId,
      success: function (res) {
        console.log('Reconnect success:', res);
        // 重连成功后,可以进行后续操作
      },
      fail: function (err) {
        console.log('Reconnect failed:', err);
      }
    });
  }
});

// 在连接成功后保存设备ID和连接状态
wx.createBLEConnection({
  deviceId: 'xxx', // 替换为实际设备ID
  success: function (res) {
    deviceId = 'xxx';
    isConnected = true;
    console.log('Bluetooth connection success:', res);
  },
  fail: function (err) {
    console.log('Bluetooth connection failed:', err);
  }
});

// 在需要断开连接时调用
wx.closeBLEConnection({
  deviceId: deviceId,
  success: function (res) {
    console.log('Disconnect success:', res);
    isConnected = false;
  },
  fail: function (err) {
    console.log('Disconnect failed:', err);
  }
});

在示例代码中,我们首先监听蓝牙连接状态的改变,当连接状态变为断开时,就会触发重连的逻辑。在重连的逻辑中,我们重新调用wx.createBLEConnection方法进行连接操作。在连接成功后,会保存设备ID和连接状态。当需要断开连接时,我们调用wx.closeBLEConnection方法来断开连接,并将连接状态标记为断开。

上一篇 下一篇

猜你喜欢

热点阅读