Merge pull request #557 from M0Rf30/fix/usb-serial-nonblocking-close
Close USB serial port off the UI isolate
This commit is contained in:
4 files changed
+310
-9
No files matched your search
@@ -7,6 +7,15 @@
|
|||||||
|
|
||||||
# The following line activates a set of recommended lints for Flutter apps,
|
# The following line activates a set of recommended lints for Flutter apps,
|
||||||
# packages, and plugins designed to encourage good coding practices.
|
# packages, and plugins designed to encourage good coding practices.
|
||||||
|
analyzer:
|
||||||
|
exclude:
|
||||||
|
- build/**
|
||||||
|
- android/**
|
||||||
|
- ios/**
|
||||||
|
- web/**
|
||||||
|
- windows/**
|
||||||
|
- macos/**
|
||||||
|
- linux/**
|
||||||
include: package:flutter_lints/flutter.yaml
|
include: package:flutter_lints/flutter.yaml
|
||||||
|
|
||||||
linter:
|
linter:
|
||||||
|
|||||||
@@ -189,6 +189,18 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
String? _lastDeviceId;
|
String? _lastDeviceId;
|
||||||
String? _lastDeviceDisplayName;
|
String? _lastDeviceDisplayName;
|
||||||
bool _manualDisconnect = false;
|
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 MeshCoreUsbManager _usbManager = MeshCoreUsbManager();
|
||||||
final LinuxBlePairingService _linuxBlePairingService =
|
final LinuxBlePairingService _linuxBlePairingService =
|
||||||
LinuxBlePairingService();
|
LinuxBlePairingService();
|
||||||
@@ -1820,6 +1832,18 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
tag: 'USB',
|
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();
|
await stopScan();
|
||||||
_cancelReconnectTimer();
|
_cancelReconnectTimer();
|
||||||
_manualDisconnect = false;
|
_manualDisconnect = false;
|
||||||
@@ -1918,6 +1942,18 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
|
|
||||||
_appDebugLogService?.info('connectTcp: endpoint=$host:$port', tag: 'TCP');
|
_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();
|
await stopScan();
|
||||||
_cancelReconnectTimer();
|
_cancelReconnectTimer();
|
||||||
_manualDisconnect = false;
|
_manualDisconnect = false;
|
||||||
@@ -2070,6 +2106,14 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
return;
|
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;
|
_activeTransport = MeshCoreTransportType.bluetooth;
|
||||||
|
|
||||||
await stopScan();
|
await stopScan();
|
||||||
@@ -2759,6 +2803,7 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool get _shouldAutoReconnect =>
|
bool get _shouldAutoReconnect =>
|
||||||
|
!_disposed &&
|
||||||
!_manualDisconnect &&
|
!_manualDisconnect &&
|
||||||
_lastDeviceId != null &&
|
_lastDeviceId != null &&
|
||||||
_activeTransport == MeshCoreTransportType.bluetooth;
|
_activeTransport == MeshCoreTransportType.bluetooth;
|
||||||
@@ -2811,8 +2856,51 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
Future<void> disconnect({
|
Future<void> disconnect({
|
||||||
bool manual = true,
|
bool manual = true,
|
||||||
bool skipBleDeviceDisconnect = false,
|
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 {
|
}) async {
|
||||||
if (_state == MeshCoreConnectionState.disconnecting) return;
|
|
||||||
final transportAtDisconnect = _activeTransport;
|
final transportAtDisconnect = _activeTransport;
|
||||||
final transportLabel = switch (transportAtDisconnect) {
|
final transportLabel = switch (transportAtDisconnect) {
|
||||||
MeshCoreTransportType.bluetooth => 'BLE',
|
MeshCoreTransportType.bluetooth => 'BLE',
|
||||||
@@ -7219,6 +7307,7 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void _setState(MeshCoreConnectionState newState) {
|
void _setState(MeshCoreConnectionState newState) {
|
||||||
|
if (_disposed) return;
|
||||||
if (_state != newState) {
|
if (_state != newState) {
|
||||||
_state = newState;
|
_state = newState;
|
||||||
if (newState == MeshCoreConnectionState.connected) {
|
if (newState == MeshCoreConnectionState.connected) {
|
||||||
@@ -7231,6 +7320,7 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void markNotifyDirty() {
|
void markNotifyDirty() {
|
||||||
|
if (_disposed) return;
|
||||||
if (_notifyListenersDirty && _notifyListenersTimer != null) {
|
if (_notifyListenersDirty && _notifyListenersTimer != null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -7261,11 +7351,13 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
void notifyListeners() {
|
void notifyListeners() {
|
||||||
|
if (_disposed) return;
|
||||||
markNotifyDirty();
|
markNotifyDirty();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
_disposed = true;
|
||||||
_scanSubscription?.cancel();
|
_scanSubscription?.cancel();
|
||||||
_isScanningSubscription?.cancel();
|
_isScanningSubscription?.cancel();
|
||||||
_connectionSubscription?.cancel();
|
_connectionSubscription?.cancel();
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
import 'dart:ffi';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
import 'dart:isolate';
|
||||||
|
|
||||||
|
import 'package:ffi/ffi.dart';
|
||||||
import 'package:flserial/flserial.dart';
|
import 'package:flserial/flserial.dart';
|
||||||
import 'package:flserial/flserial_exception.dart';
|
import 'package:flserial/flserial_exception.dart';
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
@@ -32,6 +35,18 @@ class UsbSerialService {
|
|||||||
String? _connectedPortKey;
|
String? _connectedPortKey;
|
||||||
String? _connectedPortLabel;
|
String? _connectedPortLabel;
|
||||||
FlSerial? _serial;
|
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;
|
AppDebugLogService? _debugLogService;
|
||||||
Object? _lastError;
|
Object? _lastError;
|
||||||
|
|
||||||
@@ -120,6 +135,33 @@ class UsbSerialService {
|
|||||||
throw UnsupportedError('USB serial is not supported on this platform.');
|
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;
|
_status = UsbSerialStatus.connecting;
|
||||||
var normalizedPortName = normalizeUsbPortName(portName);
|
var normalizedPortName = normalizeUsbPortName(portName);
|
||||||
_frameDecoder.reset();
|
_frameDecoder.reset();
|
||||||
@@ -157,6 +199,9 @@ class UsbSerialService {
|
|||||||
//
|
//
|
||||||
// This must happen before we register any new NativeCallable, so it must
|
// This must happen before we register any new NativeCallable, so it must
|
||||||
// be the very first thing we do in the desktop branch.
|
// be the very first thing we do in the desktop branch.
|
||||||
|
// (the previous teardown was already awaited above)
|
||||||
|
await _waitForOrphanedNativeClose();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
bindings.fl_free();
|
bindings.fl_free();
|
||||||
bindings.fl_init(16);
|
bindings.fl_init(16);
|
||||||
@@ -289,9 +334,23 @@ class UsbSerialService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> disconnect() async {
|
/// Tears the transport down. Re-entrant calls (e.g. the `onDone` handler
|
||||||
if (_status == UsbSerialStatus.disconnected) return;
|
/// 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;
|
final portLabel = _connectedPortLabel ?? _connectedPortKey;
|
||||||
_debugLogService?.info(
|
_debugLogService?.info(
|
||||||
'USB disconnect starting port=${portLabel ?? 'unknown'}',
|
'USB disconnect starting port=${portLabel ?? 'unknown'}',
|
||||||
@@ -322,11 +381,13 @@ class UsbSerialService {
|
|||||||
try {
|
try {
|
||||||
if (serial?.isOpen() == FlOpenStatus.open) {
|
if (serial?.isOpen() == FlOpenStatus.open) {
|
||||||
serial?.setDTR(false);
|
serial?.setDTR(false);
|
||||||
serial?.closePort();
|
|
||||||
}
|
}
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
// Ignore errors while closing.
|
// Ignore errors while closing.
|
||||||
}
|
}
|
||||||
|
if (serial != null) {
|
||||||
|
await _closePortOffUiIsolate(serial);
|
||||||
|
}
|
||||||
// Note: we do NOT call free() here; that would globally reset native
|
// Note: we do NOT call free() here; that would globally reset native
|
||||||
// state for all ports. The global reset is done in connect() instead,
|
// state for all ports. The global reset is done in connect() instead,
|
||||||
// before the next open, which is the safer place to do it.
|
// 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() {
|
void dispose() {
|
||||||
// Synchronously close the native port so the SerialThread exits before
|
// Synchronously close the native port so the SerialThread exits before
|
||||||
// the Dart isolate is torn down (e.g. on hot restart). The async
|
// the Dart isolate is torn down (e.g. on hot restart). The async
|
||||||
// disconnect() path via unawaited() offers no ordering guarantee — the
|
// disconnect() path via unawaited() offers no ordering guarantee — the
|
||||||
// isolate may die before the Future resolves, leaving the thread alive
|
// isolate may die before the Future resolves, leaving the thread alive
|
||||||
// with a dangling NativeCallable pointer.
|
// 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) {
|
if (_useDesktopFlSerial) {
|
||||||
final serial = _serial;
|
final serial = _serial;
|
||||||
try {
|
_serial = null;
|
||||||
if (serial?.isOpen() == FlOpenStatus.open) {
|
if (serial != null) {
|
||||||
serial?.setDTR(false);
|
// Close on any live handle, not only when isOpen() reports `open`:
|
||||||
serial?.closePort(); // synchronous C call — kills the SerialThread
|
// 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,
|
// Kick off the full async teardown for anything else (subscription cancel,
|
||||||
// stream controller close). These are best-effort at dispose time.
|
// stream controller close). These are best-effort at dispose time.
|
||||||
@@ -383,6 +574,14 @@ class UsbSerialService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void _handleSerialData(FlSerialEventArgs event) {
|
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 {
|
try {
|
||||||
final bytes = event.serial.readList();
|
final bytes = event.serial.readList();
|
||||||
if (bytes.isNotEmpty) {
|
if (bytes.isNotEmpty) {
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ dependencies:
|
|||||||
git:
|
git:
|
||||||
url: https://github.com/MeshEnvy/flserial.git
|
url: https://github.com/MeshEnvy/flserial.git
|
||||||
ref: e1864de9b65cda9656dba804329bdd2890dd5a92
|
ref: e1864de9b65cda9656dba804329bdd2890dd5a92
|
||||||
|
ffi: ^2.1.3 # calloc.free for flserial's native I/O buffers
|
||||||
provider: ^6.1.5+1
|
provider: ^6.1.5+1
|
||||||
shared_preferences: ^2.2.2
|
shared_preferences: ^2.2.2
|
||||||
uuid: ^4.3.3
|
uuid: ^4.3.3
|
||||||
|
|||||||
Reference in new issue
Block a user