Unity连接ESP32蓝牙LE手柄首次尝试立即断开、后续连接成功的问题求助
Unity连接ESP32蓝牙LE手柄首次尝试立即断开、后续连接成功的问题求助
我现在在开发一款Unity安卓应用,需要连接基于ESP32自制的BLE手柄,最近遇到了一个非常固定的奇怪问题:第一次发起连接尝试后,不到250ms就会立即断开,然后等待30秒超时后失败,但后续的连接尝试却能100%成功。
我使用的环境是Unity 2022.3.62f2,搭配BluetoothLEHardwareInterface插件,从安卓Logcat里能看到如下日志:
15:42:31.461 >> Connecting joystick DeviceName [MAC Address]...
15:42:31.705 >> device disconnected: [MAC Address]
15:43:01.465 >> connection to DeviceName [MAC Address] timed out!
断开动作发生在连接发起后不到250ms,之后会触发我设置的30秒默认超时(TIMEOUT_DEFAULT)。
以下是我的核心连接实现代码:
public async UniTask<bool> Connect(Peripheral _peripheral, CancellationToken _cancellationToken = default) { if (!string.IsNullOrEmpty(DeviceAddress)) { Debug.LogWarning($">> Already connected to {DeviceName}. Disconnecting first..."); Disconnect(); await UniTask.Delay(RECONNECTION_GUARD_DELAY, cancellationToken: _cancellationToken); } IsConnected = false; DeviceName = null; DeviceAddress = null; var connectionPromise = new UniTaskCompletionSource<bool>(); await using var registration = _cancellationToken.Register(() => connectionPromise.TrySetCanceled()); print($">> Connecting joystick {_peripheral.ToString()}..."); BluetoothLEHardwareInterface.ConnectToPeripheral( _peripheral.Address, OnDeviceConnected, null, // ServiceCallback, unused OnCharacteristicDiscovered, OnDeviceDisconnected); bool success = await connectionPromise.Task.Timeout(TimeSpan.FromMilliseconds(TIMEOUT_DEFAULT)); if (success) print($">> Successfully paired joystick {_peripheral.ToString()}!"); else Debug.LogError($">> connection to {_peripheral.ToString()} timed out!"); if (IsConnected) OnConnected?.Invoke(); return success; void OnDeviceConnected(string _name) { DeviceAddress = _peripheral.Address; DeviceName = _name; IsConnected = true; connectionPromise.TrySetResult(true); } }
断开回调的实现如下:
private void OnDeviceDisconnected(string _disconnectedDeviceAddress) { print(">> device disconnected: " + _disconnectedDeviceAddress); if (string.IsNullOrEmpty(DeviceAddress) || DeviceAddress != _disconnectedDeviceAddress) return; DeviceName = null; DeviceAddress = null; IsConnected = false; OnDisconnected?.Invoke(); }
我已经排查过的点:
- 确认传入
BluetoothLEHardwareInterface.ConnectToPeripheral()的所有参数(MAC地址、各个回调方法)都是正确的 - 测试了两个不同的手柄,不管先连接哪一个,第一次尝试都会触发这个立即断开的问题
- 已经在重连前加了延迟等待(
RECONNECTION_GUARD_DELAY),但第一次连接的问题依然存在
想请教各位大佬:
- 这会不会是安卓BLE栈的已知问题?有没有什么规避方案?
- 我的UniTask异步实现有没有什么潜在的问题,导致第一次连接时出现异常?
- 还有哪些排查方向可以尝试?




