connect static method
Connect to a device.
It is advised to stop scanning before connecting.
It throws error if device connection fails.
Default connection timeout is 60 sec.
Can throw ConnectionException or PlatformException.
Implementation
static Future<void> connect(
String deviceId, {
Duration? timeout,
}) async {
timeout ??= const Duration(seconds: 60);
StreamSubscription? connectionSubscription;
Completer<bool> completer = Completer();
void handleError(dynamic error) {
if (completer.isCompleted) return;
connectionSubscription?.cancel();
completer.completeError(ConnectionException(error));
}
try {
connectionSubscription = _platform
.bleConnectionUpdateStreamController.stream
.where((e) => e.deviceId == deviceId)
.listen(
(e) {
if (e.error != null) {
handleError(e.error);
} else {
if (!completer.isCompleted) {
completer.complete(e.isConnected);
}
}
},
onError: handleError,
cancelOnError: true,
);
_platform
.connect(deviceId, connectionTimeout: timeout)
.catchError(handleError);
if (!await completer.future.timeout(timeout)) {
throw ConnectionException("Failed to connect");
}
} finally {
connectionSubscription?.cancel();
}
}