Merge pull request #557 from M0Rf30/fix/usb-serial-nonblocking-close

Close USB serial port off the UI isolate
This commit is contained in:
zjs81 authored and GitHub committed 2026-09-27 11:54:38 -07:00
commit 31186fc134
4 files changed
+310 -9

No files matched your search

+9
View File
@@ -7,6 +7,15 @@
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
analyzer:
exclude:
- build/**
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
include: package:flutter_lints/flutter.yaml
linter:
+93 -1
View File
@@ -189,6 +189,18 @@ class MeshCoreConnector extends ChangeNotifier {
String? _lastDeviceId;
String? _lastDeviceDisplayName;
bool _manualDisconnect = false;
/// Non-null while [disconnect] is tearing the transport down. Connect paths
/// join it so a teardown cannot finish after a new connection and reset the
/// state to `disconnected`. USB made this reachable: its native close now
/// waits out the kernel's closing_wait off the UI isolate, so the teardown
/// can outlive the tap that starts the next connection.
Future<void>? _activeDisconnect;
/// Set by [dispose]. A teardown started before disposal can still be running
/// (the USB native close waits out the kernel's closing_wait off the UI
/// isolate), so state publication is suppressed once the connector is gone.
bool _disposed = false;
final MeshCoreUsbManager _usbManager = MeshCoreUsbManager();
final LinuxBlePairingService _linuxBlePairingService =
LinuxBlePairingService();
@@ -1820,6 +1832,18 @@ class MeshCoreConnector extends ChangeNotifier {
tag: 'USB',
);
await _awaitActiveDisconnect();
// The await is a suspension point: another connect may have claimed the
// connector while this one was waiting for the teardown.
if (_state == MeshCoreConnectionState.connecting ||
_state == MeshCoreConnectionState.connected) {
_appDebugLogService?.warn(
'connectUsb ignored: already $_state after disconnect wait',
tag: 'USB',
);
return;
}
await stopScan();
_cancelReconnectTimer();
_manualDisconnect = false;
@@ -1918,6 +1942,18 @@ class MeshCoreConnector extends ChangeNotifier {
_appDebugLogService?.info('connectTcp: endpoint=$host:$port', tag: 'TCP');
await _awaitActiveDisconnect();
// The await is a suspension point: another connect may have claimed the
// connector while this one was waiting for the teardown.
if (_state == MeshCoreConnectionState.connecting ||
_state == MeshCoreConnectionState.connected) {
_appDebugLogService?.warn(
'connectTcp ignored: already $_state after disconnect wait',
tag: 'TCP',
);
return;
}
await stopScan();
_cancelReconnectTimer();
_manualDisconnect = false;
@@ -2070,6 +2106,14 @@ class MeshCoreConnector extends ChangeNotifier {
return;
}
await _awaitActiveDisconnect();
// The await is a suspension point: another connect may have claimed the
// connector while this one was waiting for the teardown.
if (_state == MeshCoreConnectionState.connecting ||
_state == MeshCoreConnectionState.connected) {
return;
}
_activeTransport = MeshCoreTransportType.bluetooth;
await stopScan();
@@ -2759,6 +2803,7 @@ class MeshCoreConnector extends ChangeNotifier {
}
bool get _shouldAutoReconnect =>
!_disposed &&
!_manualDisconnect &&
_lastDeviceId != null &&
_activeTransport == MeshCoreTransportType.bluetooth;
@@ -2811,8 +2856,51 @@ class MeshCoreConnector extends ChangeNotifier {
Future<void> disconnect({
bool manual = true,
bool skipBleDeviceDisconnect = false,
}) {
final inFlight = _activeDisconnect;
if (inFlight != null) {
if (manual) {
// A teardown started as automatic must still honour a later manual
// request, otherwise _manualDisconnect stays false and its tail
// schedules an auto-reconnect the user did not ask for.
_manualDisconnect = true;
_cancelReconnectTimer();
unawaited(_backgroundService?.stop());
}
return inFlight;
}
final teardown = _disconnectInternal(
manual: manual,
skipBleDeviceDisconnect: skipBleDeviceDisconnect,
);
_activeDisconnect = teardown;
return teardown.whenComplete(() {
if (identical(_activeDisconnect, teardown)) {
_activeDisconnect = null;
}
});
}
/// Joins an in-flight [disconnect] so a new connection cannot be started
/// while the previous teardown is still running.
Future<void> _awaitActiveDisconnect() async {
final pending = _activeDisconnect;
if (pending == null) return;
_appDebugLogService?.info(
'Waiting for the in-flight disconnect to finish before connecting',
tag: 'Connection',
);
try {
await pending;
} catch (_) {
// Teardown failures are logged by the disconnect path.
}
}
Future<void> _disconnectInternal({
required bool manual,
required bool skipBleDeviceDisconnect,
}) async {
if (_state == MeshCoreConnectionState.disconnecting) return;
final transportAtDisconnect = _activeTransport;
final transportLabel = switch (transportAtDisconnect) {
MeshCoreTransportType.bluetooth => 'BLE',
@@ -7219,6 +7307,7 @@ class MeshCoreConnector extends ChangeNotifier {
}
void _setState(MeshCoreConnectionState newState) {
if (_disposed) return;
if (_state != newState) {
_state = newState;
if (newState == MeshCoreConnectionState.connected) {
@@ -7231,6 +7320,7 @@ class MeshCoreConnector extends ChangeNotifier {
}
void markNotifyDirty() {
if (_disposed) return;
if (_notifyListenersDirty && _notifyListenersTimer != null) {
return;
}
@@ -7261,11 +7351,13 @@ class MeshCoreConnector extends ChangeNotifier {
@override
void notifyListeners() {
if (_disposed) return;
markNotifyDirty();
}
@override
void dispose() {
_disposed = true;
_scanSubscription?.cancel();
_isScanningSubscription?.cancel();
_connectionSubscription?.cancel();
+207 -8
View File
@@ -1,6 +1,9 @@
import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
import 'package:ffi/ffi.dart';
import 'package:flserial/flserial.dart';
import 'package:flserial/flserial_exception.dart';
import 'package:flutter/foundation.dart';
@@ -32,6 +35,18 @@ class UsbSerialService {
String? _connectedPortKey;
String? _connectedPortLabel;
FlSerial? _serial;
/// Non-null while a disconnect teardown (native close in a helper isolate,
/// then subscription cancel) is running.
Future<void>? _activeDisconnect;
/// Exists while a native close runs in a helper isolate. flserial's slot
/// table is process-global and survives a hot restart, but
/// [_activeDisconnect] does not, so a fresh isolate checks this marker
/// before fl_free() tears down a slot that is still inside close().
static final String _pendingClosePath =
'${Directory.systemTemp.path}/meshcore_open_usb_close_$pid';
static const Duration _maxPendingClose = Duration(seconds: 45);
AppDebugLogService? _debugLogService;
Object? _lastError;
@@ -120,6 +135,33 @@ class UsbSerialService {
throw UnsupportedError('USB serial is not supported on this platform.');
}
// A previous disconnect may still be running: on desktop its native close
// waits out the kernel's closing_wait in a helper isolate, and the
// teardown only marks the transport disconnected afterwards. Reopening
// before it finishes would let the old teardown overwrite the new
// connection's state (and, on desktop, race fl_free()/fl_close() over the
// process-global flserial_tab). Wait for the whole teardown — on every
// platform — before claiming the `connecting` state.
final pendingDisconnect = _activeDisconnect;
if (pendingDisconnect != null) {
_debugLogService?.info(
'Waiting for the previous USB disconnect to finish before reopening',
tag: 'USB Serial',
);
try {
await pendingDisconnect;
} catch (_) {
// Failures are already logged by the teardown path.
}
// The await above is a suspension point: another caller may have claimed
// the transport while this one waited.
if (_status == UsbSerialStatus.connected ||
_status == UsbSerialStatus.connecting) {
throw StateError('USB serial transport is already active');
}
}
_status = UsbSerialStatus.connecting;
var normalizedPortName = normalizeUsbPortName(portName);
_frameDecoder.reset();
@@ -157,6 +199,9 @@ class UsbSerialService {
//
// This must happen before we register any new NativeCallable, so it must
// be the very first thing we do in the desktop branch.
// (the previous teardown was already awaited above)
await _waitForOrphanedNativeClose();
try {
bindings.fl_free();
bindings.fl_init(16);
@@ -289,9 +334,23 @@ class UsbSerialService {
}
}
Future<void> disconnect() async {
if (_status == UsbSerialStatus.disconnected) return;
/// Tears the transport down. Re-entrant calls (e.g. the `onDone` handler
/// firing while a disconnect is already running) join the in-flight
/// teardown instead of racing it.
Future<void> disconnect() {
final pending = _activeDisconnect;
if (pending != null) return pending;
if (_status == UsbSerialStatus.disconnected) return Future<void>.value();
final teardown = _disconnectInternal();
_activeDisconnect = teardown;
return teardown.whenComplete(() {
if (identical(_activeDisconnect, teardown)) {
_activeDisconnect = null;
}
});
}
Future<void> _disconnectInternal() async {
final portLabel = _connectedPortLabel ?? _connectedPortKey;
_debugLogService?.info(
'USB disconnect starting port=${portLabel ?? 'unknown'}',
@@ -322,11 +381,13 @@ class UsbSerialService {
try {
if (serial?.isOpen() == FlOpenStatus.open) {
serial?.setDTR(false);
serial?.closePort();
}
} catch (_) {
// Ignore errors while closing.
}
if (serial != null) {
await _closePortOffUiIsolate(serial);
}
// Note: we do NOT call free() here; that would globally reset native
// state for all ports. The global reset is done in connect() instead,
// before the next open, which is the safer place to do it.
@@ -362,20 +423,150 @@ class UsbSerialService {
);
}
/// Closes the native port without blocking the Dart UI isolate.
///
/// `close(2)` on a tty whose output has not been drained by the peer blocks
/// in the kernel for the line discipline's `closing_wait` (30s by default —
/// measured 30.4s on Linux with a CDC-ACM device that never reads its bulk
/// OUT endpoint, e.g. a MeshCore board flashed with a BLE-only companion
/// build). `FlSerial.closePort()` is a synchronous FFI call, so running it
/// inline freezes the whole app for that entire window. `fl_close()` only
/// touches process-global native state, so it is safe to run in a helper
/// isolate; the Dart-side cleanup that `closePort()` also performs is
/// replicated here afterwards.
Future<void> _closePortOffUiIsolate(FlSerial serial) async {
final flh = serial.flh;
if (flh < 0) {
// Already closed synchronously by dispose(), which also closed the
// stream and freed both I/O buffers.
return;
}
serial.flh = -1;
final startedAt = DateTime.now();
final markerPath = _pendingClosePath;
try {
File(markerPath).writeAsStringSync('');
} catch (_) {}
try {
await Isolate.run(() {
bindings.fl_close(flh);
try {
File(markerPath).deleteSync();
} catch (_) {}
});
} catch (error) {
// Spawning the helper failed, so the native slot and its SerialThread
// are still alive with no reachable handle. Close it inline instead —
// that blocks, but only in this already-degraded path.
_debugLogService?.warn(
'Off-isolate USB port close failed ($error); closing inline',
tag: 'USB Serial',
);
try {
bindings.fl_close(flh);
} catch (_) {
// Ignore errors while closing.
}
}
try {
File(markerPath).deleteSync();
} catch (_) {}
final elapsed = DateTime.now().difference(startedAt);
if (elapsed > const Duration(seconds: 1)) {
_debugLogService?.warn(
'Native USB port close took ${elapsed.inMilliseconds}ms — the device '
'was not draining its serial input',
tag: 'USB Serial',
);
}
try {
await serial.onSerialData.close();
} catch (_) {
// Ignore errors while releasing Dart-side resources.
}
_releaseSerialBuffers(serial);
}
/// Waits for a native close left running by a previous isolate (hot
/// restart during a slow close). Bounded by the marker's age so a stale
/// marker — its helper isolate killed before deleting it — cannot block
/// forever.
Future<void> _waitForOrphanedNativeClose() async {
final marker = File(_pendingClosePath);
try {
if (!marker.existsSync()) return;
_debugLogService?.info(
'Waiting for a USB port close left over from a previous isolate',
tag: 'USB Serial',
);
final deadline = marker.lastModifiedSync().add(_maxPendingClose);
while (marker.existsSync() && DateTime.now().isBefore(deadline)) {
await Future<void>.delayed(const Duration(milliseconds: 250));
}
if (marker.existsSync()) marker.deleteSync();
} catch (_) {}
}
/// Frees the two calloc'd I/O buffers `openPort()` allocated and clears the
/// pointer fields. `FlSerial.closePort()` is never used for this: it tests
/// the buffers' first byte (`.value`) instead of their address, so it
/// usually leaks them.
void _releaseSerialBuffers(FlSerial serial) {
try {
if (serial.serialReadBuff.address != 0) {
calloc.free(serial.serialReadBuff);
}
serial.serialReadBuff = Pointer.fromAddress(0);
if (serial.serialWriteBuff.address != 0) {
calloc.free(serial.serialWriteBuff);
}
serial.serialWriteBuff = Pointer.fromAddress(0);
} catch (_) {
// Ignore errors while releasing Dart-side resources.
}
}
void dispose() {
// Synchronously close the native port so the SerialThread exits before
// the Dart isolate is torn down (e.g. on hot restart). The async
// disconnect() path via unawaited() offers no ordering guarantee — the
// isolate may die before the Future resolves, leaving the thread alive
// with a dangling NativeCallable pointer.
final pendingDisconnect = _activeDisconnect;
if (pendingDisconnect != null) {
// A disconnect is already running and owns the teardown ordering
// (native close first, subscription cancel after). Re-entering
// disconnect() here would cancel the subscription underneath it, so
// only chain the frame-controller cleanup onto that teardown.
unawaited(pendingDisconnect.whenComplete(_closeFrameController));
return;
}
if (_useDesktopFlSerial) {
final serial = _serial;
try {
if (serial?.isOpen() == FlOpenStatus.open) {
serial?.setDTR(false);
serial?.closePort(); // synchronous C call — kills the SerialThread
_serial = null;
if (serial != null) {
// Close on any live handle, not only when isOpen() reports `open`:
// flserial keeps a valid slot (and a running SerialThread) when the
// port is in an I/O error state, and _serial is already unreachable.
final flh = serial.flh;
if (flh >= 0) {
try {
serial.setDTR(false);
} catch (_) {
// Line-control failure must not skip the close below.
}
serial.flh = -1;
try {
bindings.fl_close(
flh,
); // synchronous C call — kills the SerialThread
} catch (_) {}
unawaited(serial.onSerialData.close());
}
} catch (_) {}
// _serial is gone, so the disconnect() below can no longer reach the
// buffers: release them here.
_releaseSerialBuffers(serial);
}
}
// Kick off the full async teardown for anything else (subscription cancel,
// stream controller close). These are best-effort at dispose time.
@@ -383,6 +574,14 @@ class UsbSerialService {
}
void _handleSerialData(FlSerialEventArgs event) {
if (_status == UsbSerialStatus.disconnecting ||
_status == UsbSerialStatus.disconnected) {
// Teardown already invalidated the native handle; a callback queued
// before that would make readList() throw and publish a spurious
// transport error that triggers another disconnect. Data that arrives
// while still `connecting` is kept — the decoder buffers it.
return;
}
try {
final bytes = event.serial.readList();
if (bytes.isNotEmpty) {
+1
View File
@@ -43,6 +43,7 @@ dependencies:
git:
url: https://github.com/MeshEnvy/flserial.git
ref: e1864de9b65cda9656dba804329bdd2890dd5a92
ffi: ^2.1.3 # calloc.free for flserial's native I/O buffers
provider: ^6.1.5+1
shared_preferences: ^2.2.2
uuid: ^4.3.3