waitForDataOfType method

Future<Uint8List> waitForDataOfType(
  1. FrameDataTypePrefixes dataType, {
  2. Duration? timeout,
})

Waits for data of a specific type from the device.

Implementation

Future<Uint8List> waitForDataOfType(FrameDataTypePrefixes dataType,
    {Duration? timeout}) async {
  StreamSubscription<Uint8List>? subscription;
  Completer<Uint8List> completer = Completer();
  _log.fine("Waiting for data of type ${dataType.name}");
  try {
    subscription = dataResponse
        .where((event) => event[0] == dataType.value)
        .timeout(timeout ?? defaultTimeout)
        .listen((event) {
      _log.fine(
          "Received data of type ${dataType.name}: ${event.length} bytes");
      subscription?.cancel();
      completer.complete(event.sublist(1));
    });
  } on TimeoutException {
    _log.warning("Timeout while waiting for data of type ${dataType.name}");
    if (subscription != null) {
      subscription.cancel();
    }
    if (!completer.isCompleted) {
      completer.completeError(BrilliantBluetoothException(
          "Timeout while waiting for data of type ${dataType.name}"));
    }
    return Future.error(BrilliantBluetoothException(
        "Timeout while waiting for data of type ${dataType.name}"));
  }
  return completer.future;
}