read method
Read data from the serial port.
The operation attempts to read N bytes
of data.
Implementation
@override
Future<Uint8List> read(int bytes, {Duration? timeout}) async {
if (_usbPort != null) {
List<int> inData = [];
final completer = Completer<Uint8List>();
StreamSubscription<List<int>> subscription;
subscription = _usbPort!.inputStream!.listen((data) {
inData.addAll(data);
if (inData.length >= bytes) {
completer.complete(Uint8List.fromList(inData));
}
}, onError: (error) {
completer.completeError(error);
}, cancelOnError: true);
var rxData = await completer.future
.timeout(timeout ?? const Duration(seconds: 60), onTimeout: () {
subscription.cancel();
return Uint8List.fromList(inData);
});
try {
subscription.cancel();
} catch (_) {}
return rxData;
}
return Uint8List(0);
}