waitForString method
Waits for a specific string from the device.
Implementation
Future<String> waitForString({String? match, Duration? timeout}) async {
StreamSubscription<String>? subscription;
Completer<String> completer = Completer();
try {
if (match != null) {
subscription = stringResponse
.where((event) => event.trim() == match.trim())
.timeout(timeout ?? defaultTimeout)
.listen((event) {
subscription?.cancel();
_log.fine("Received the $match string we were waiting for");
completer.complete(event);
}, onError: (error) {
_log.warning("Error waiting for string $match: $error");
completer.completeError(error);
});
} else {
subscription =
stringResponse.timeout(timeout ?? defaultTimeout).listen((event) {
_log.fine("Received a string we were waiting for: $event");
completer.complete(event);
}, onError: (error) {
_log.warning("Error waiting for string: $error");
completer.completeError(error);
});
}
} on TimeoutException {
_log.warning("Timeout while waiting for string.");
if (subscription != null) {
subscription.cancel();
}
if (!completer.isCompleted) {
completer.completeError(const BrilliantBluetoothException(
"Timeout while waiting for string"));
}
}
return completer.future;
}