@@ -72,12 +72,14 @@ class PbleConnection implements Connection, ConnectionDirectoryListingSource {
7272 required String appVersion,
7373 Duration dataTimeout = const Duration (seconds: 8 ),
7474 }) {
75+ final BleByteTransport transport = BleByteTransport (link);
7576 final PbleConnection conn = PbleConnection (
76- engine: PbleEngine (BleByteTransport (link) ),
77+ engine: PbleEngine (transport ),
7778 appName: appName,
7879 appVersion: appVersion,
7980 dataTimeout: dataTimeout,
8081 );
82+ conn._ownedTransport = transport;
8183 conn._observeLink (link);
8284 return conn;
8385 }
@@ -97,21 +99,29 @@ class PbleConnection implements Connection, ConnectionDirectoryListingSource {
9799
98100 // fromLink observation (null when constructed directly over a transport).
99101 BleLink ? _observedLink;
102+ BleByteTransport ? _ownedTransport;
100103 VoidCallback ? _linkListener;
104+ bool _disposed = false ;
105+ Future <void >? _disposeFuture;
106+ int _handshakeGeneration = 0 ;
101107
102108 void _observeLink (BleLink link) {
103109 _observedLink = link;
104110 _linkListener = () {
111+ if (_disposed) return ;
105112 switch (link.linkState.value) {
106113 case BleLinkState .connecting:
107114 case BleLinkState .reconnecting:
115+ _handshakeGeneration++ ;
108116 _state.value = ConnState .connecting;
109117 case BleLinkState .connected:
110118 // Re-negotiate HELLO on every (re)connect (TDD §7.3). A failed
111119 // handshake surfaces as ConnState.disconnected; the typed error is
112120 // deliberately not rethrown here — nothing awaits a link callback.
113121 unawaited (handshake ().catchError ((_) {}));
114122 case BleLinkState .disconnected:
123+ _handshakeGeneration++ ;
124+ _hello = null ;
115125 _state.value = ConnState .disconnected;
116126 // Abort any in-flight transfer NOW: a reconnect re-HELLOs and the
117127 // board clears its transfer context on disconnect, so an orphaned
@@ -173,12 +183,28 @@ class PbleConnection implements Connection, ConnectionDirectoryListingSource {
173183 /// `ready` ; on any failure it returns to `disconnected` and the typed error
174184 /// (e.g. [UnsupportedProtocolException] , a §8 subtype) is rethrown.
175185 Future <void > handshake () async {
186+ _ensureActive ();
187+ final int generation = ++ _handshakeGeneration;
176188 _state.value = ConnState .connecting;
177189 try {
178- _hello = await _negotiator.negotiate ();
190+ final HelloResult hello = await _negotiator.negotiate ();
191+ if (_disposed || generation != _handshakeGeneration) {
192+ throw const NotConnectedException ('connection changed during HELLO' );
193+ }
194+ _hello = hello;
179195 _state.value = ConnState .ready;
180196 } catch (_) {
181- _state.value = ConnState .disconnected;
197+ if (! _disposed && generation == _handshakeGeneration) {
198+ _state.value = ConnState .disconnected;
199+ if (_observedLink != null ) {
200+ // An unusable owned session must not leave the radio connected.
201+ // Keep the negotiation error as this operation's original failure;
202+ // a close error remains available from the shared dispose future.
203+ try {
204+ await dispose ();
205+ } catch (_) {}
206+ }
207+ }
182208 rethrow ;
183209 }
184210 }
@@ -424,6 +450,7 @@ class PbleConnection implements Connection, ConnectionDirectoryListingSource {
424450 /// runs while a REAL error is propagating, and a dead link (the common cause)
425451 /// would otherwise replace the caller's honest error with a timeout.
426452 Future <void > _releaseBoardTransfer (int crc) async {
453+ if (_disposed) return ;
427454 try {
428455 await _engine
429456 .request (
@@ -484,22 +511,55 @@ class PbleConnection implements Connection, ConnectionDirectoryListingSource {
484511 }
485512
486513 @override
487- Future <void > dispose () async {
488- _downloadStallTimer? .cancel ();
489- _putStallTimer? .cancel ();
490- if (_linkListener != null ) {
491- _observedLink? .linkState.removeListener (_linkListener! );
514+ Future <void > dispose () {
515+ if (_disposeFuture case final Future <void > pending) return pending;
516+ _disposed = true ;
517+ _handshakeGeneration++ ;
518+ // Store the shared future before notifying listeners or closing the link:
519+ // either can re-enter dispose synchronously.
520+ return _disposeFuture = Future <void >.microtask (_disposeResources);
521+ }
522+
523+ Future <void > _disposeResources () async {
524+ Object ? firstError;
525+ StackTrace ? firstStack;
526+ Future <void > attempt (FutureOr <void > Function () action) async {
527+ try {
528+ await action ();
529+ } catch (error, stack) {
530+ firstError ?? = error;
531+ firstStack ?? = stack;
532+ }
533+ }
534+
535+ _hello = null ;
536+ _state.value = ConnState .disconnected;
537+ _abortTransfers (const NotConnectedException ('connection disposed' ));
538+ await attempt (() {
539+ if (_linkListener != null ) {
540+ _observedLink? .linkState.removeListener (_linkListener! );
541+ }
542+ });
543+ // Begin protocol retirement and the exact owned physical close together;
544+ // a failing subscription cleanup must not skip physical disconnect.
545+ await Future .wait (< Future <void >> [
546+ attempt (_eventsSub.cancel),
547+ attempt (_engine.dispose),
548+ if (_observedLink case final BleLink link) attempt (link.disconnect),
549+ ]);
550+ await attempt (() => _ownedTransport? .dispose ());
551+ await attempt (_runStateController.close);
552+ await attempt (_consoleController.close);
553+ await attempt (_state.dispose);
554+ if (firstError != null ) {
555+ Error .throwWithStackTrace (firstError! , firstStack! );
492556 }
493- await _eventsSub.cancel ();
494- await _engine.dispose ();
495- await _runStateController.close ();
496- await _consoleController.close ();
497- _state.dispose ();
498557 }
499558
500559 // --- inbound EVT routing (protocol.md §6 / §5) -----------------------------
501560
502561 void _onEvent (PbleFrame frame) {
562+ if (_disposed) return ;
503563 final int op = frame.opcode;
504564 final Uint8List p = frame.payload;
505565
@@ -593,12 +653,19 @@ class PbleConnection implements Connection, ConnectionDirectoryListingSource {
593653 // --- helpers ---------------------------------------------------------------
594654
595655 /// Builds a CMD frame on [op] with a fresh correlation ID.
596- PbleFrame _cmd (PbleOpcode op, List <int > payload) => PbleFrame (
597- type: Pble .typeCmd,
598- opcode: op.code,
599- id: _engine.nextId (),
600- payload: Uint8List .fromList (payload),
601- );
656+ PbleFrame _cmd (PbleOpcode op, List <int > payload) {
657+ _ensureActive ();
658+ return PbleFrame (
659+ type: Pble .typeCmd,
660+ opcode: op.code,
661+ id: _engine.nextId (),
662+ payload: Uint8List .fromList (payload),
663+ );
664+ }
665+
666+ void _ensureActive () {
667+ if (_disposed) throw const NotConnectedException ('connection disposed' );
668+ }
602669
603670 /// Throws the typed §8 exception for a non-OK RSP `[status]` byte; OK returns.
604671 void _checkStatus (PbleFrame rsp) {
@@ -619,6 +686,7 @@ class PbleConnection implements Connection, ConnectionDirectoryListingSource {
619686 /// Claims the single active-transfer slot (SEC-2 / FR-CONN-9); a concurrent
620687 /// transfer is refused with [EBusy] BEFORE any BEGIN frame is sent.
621688 void _beginTransfer () {
689+ _ensureActive ();
622690 if (_transferActive) {
623691 throw const EBusy ('another file transfer is already active' );
624692 }
0 commit comments