Refactor USB handling to improve connection management and error cleanup

This commit is contained in:
just_stuff_tm
2026-03-02 01:24:33 -05:00
committed by just-stuff-tm
parent f462815775
commit 98f7c3b088
4 changed files with 81 additions and 16 deletions
+33
View File
@@ -88,8 +88,10 @@ class UsbSerialService {
debugPrint('USB serial opened port=$_connectedPortName via Web Serial');
} catch (error) {
await _cleanupFailedConnect();
_status = UsbSerialStatus.disconnected;
_connectedPortName = null;
_connectedPortKey = null;
rethrow;
}
}
@@ -205,6 +207,37 @@ class UsbSerialService {
return port.callMethod<JSPromise<JSAny?>>('open'.toJS, options).toDart;
}
Future<void> _cleanupFailedConnect() async {
final reader = _reader;
final writer = _writer;
final port = _port;
_reader = null;
_writer = null;
_port = null;
if (reader != null) {
try {
await reader.callMethod<JSPromise<JSAny?>>('cancel'.toJS).toDart;
} catch (_) {
// Ignore cleanup errors after a failed connect.
}
_releaseLock(reader);
}
if (writer != null) {
_releaseLock(writer);
}
if (port != null) {
try {
await port.callMethod<JSPromise<JSAny?>>('close'.toJS).toDart;
} catch (_) {
// Ignore cleanup errors after a failed connect.
}
}
}
JSObject? _getReader(JSObject port) {
final readable = port.getProperty<JSAny?>('readable'.toJS);
if (readable == null) {