readBytesUntil method

Future<Uint8List> readBytesUntil(
  1. Uint8List expected, {
  2. Duration dataPollingInterval = const Duration(microseconds: 500),
})

readBytesUntil will read until an expected sequence is found

Implementation

Future<Uint8List> readBytesUntil(Uint8List expected,
    {Duration dataPollingInterval =
        const Duration(microseconds: 500)}) async {
  /// either [readBytesOnListen] or [readBytesUntil]
  if (_readStream != null) {
    throw Exception("You have used listen function");
  }

  int event = 0;
  List<int> readData = List<int>.empty(growable: true);
  final expectedListLength = expected.length;

  while (true) {
    event = WaitCommEvent(handler!, _dwCommEvent, _over);
    if (event != FALSE) {
      ClearCommError(handler!, _errors, _status);
      if (_status.ref.cbInQue != 0) {
        readData.add((await _read(1))[0]);
      } else {
        /// do nothing
      }
    } else {
      if (GetLastError() == ERROR_IO_PENDING) {
        /// wait io complete, timeout in 500ms
        for (int i = 0; i < 1000; i++) {
          if (WaitForSingleObject(_over.ref.hEvent, 0) == 0) {
            ClearCommError(handler!, _errors, _status);
            if (_status.ref.cbInQue != 0) {
              readData.add((await _read(1))[0]);
            } else {}
            ResetEvent(_over.ref.hEvent);
            // break for next read operation.
            break;
          } else {
            ResetEvent(_over.ref.hEvent);
            // continue waiting
            await Future.delayed(dataPollingInterval);
          }
        }
      } else {
        /// Fallback
      }
    }
    if (readData.length < expectedListLength) {
      continue;
    } else {
      if (listEquals(
          readData.sublist(readData.length - expectedListLength), expected)) {
        return Uint8List.fromList(readData);
      } else {
        await Future.delayed(dataPollingInterval);
        continue;
      }
    }
  }
}