From b978b81cb12bcfd616ab2673380dba76b5969de3 Mon Sep 17 00:00:00 2001 From: Rohit Sangwan Date: Thu, 19 Sep 2024 12:50:31 +0530 Subject: [PATCH] Add default timeout in Connect, Pair and IsPaired apis --- lib/src/universal_ble.dart | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/lib/src/universal_ble.dart b/lib/src/universal_ble.dart index 3363cc1..5ecf9ae 100644 --- a/lib/src/universal_ble.dart +++ b/lib/src/universal_ble.dart @@ -76,12 +76,14 @@ class UniversalBle { /// Connect to a device. /// It is advised to stop scanning before connecting. /// It might throw errors if device is not connectable. - /// `connectionTimeout` is supported on Web only. + /// Default connection timeout is 60 sec static Future connect( String deviceId, { Duration? connectionTimeout, }) async { + connectionTimeout ??= const Duration(seconds: 60); StreamSubscription? connectionSubscription; + try { Completer completer = Completer(); @@ -104,10 +106,7 @@ class UniversalBle { }, ); - if (connectionTimeout != null) { - return await completer.future.timeout(connectionTimeout); - } - return await completer.future; + return await completer.future.timeout(connectionTimeout); } finally { connectionSubscription?.cancel(); } @@ -211,6 +210,7 @@ class UniversalBle { static Future isPaired( String deviceId, { BleCommand? pairingCommand, + Duration? connectionTimeout, }) async { if (BleCapabilities.hasSystemPairingApi) { return _bleCommandQueue.queueCommand( @@ -218,8 +218,12 @@ class UniversalBle { deviceId: deviceId, ); } else if (pairingCommand != null) { - return _connectAndExecuteBleCommand(deviceId, pairingCommand, - updateCallbackValue: false); + return _connectAndExecuteBleCommand( + deviceId, + pairingCommand, + connectionTimeout: connectionTimeout, + updateCallbackValue: false, + ); } return null; } @@ -236,11 +240,16 @@ class UniversalBle { static Future pair( String deviceId, { BleCommand? pairingCommand, + Duration? connectionTimeout, }) async { if (BleCapabilities.hasSystemPairingApi) { return _platform.pair(deviceId); } - return _connectAndExecuteBleCommand(deviceId, pairingCommand); + return _connectAndExecuteBleCommand( + deviceId, + pairingCommand, + connectionTimeout: connectionTimeout, + ); } /// Unpair a device. @@ -306,12 +315,20 @@ class UniversalBle { static Future _connectAndExecuteBleCommand( String deviceId, BleCommand? bleCommand, { + Duration? connectionTimeout, bool updateCallbackValue = false, }) async { try { - if (await getConnectionState(deviceId) != BleConnectionState.connected) { - await connect(deviceId); + bool isConnected = + await getConnectionState(deviceId) != BleConnectionState.connected; + + if (!isConnected) { + isConnected = await connect( + deviceId, + connectionTimeout: connectionTimeout, + ); } + if (!isConnected) return null; List services = await discoverServices(deviceId);