Skip to content

Commit fd95a3b

Browse files
committed
[green] close owned BLE sessions and retire stale connections
Signed-off-by: Viwat Vchirawongkwin <viwat.v@chula.ac.th>
1 parent 54d07cd commit fd95a3b

2 files changed

Lines changed: 180 additions & 38 deletions

File tree

‎app/lib/pble/connection_manager.dart‎

Lines changed: 93 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,9 @@ class PbleConnectionManager implements ConnectionManager {
160160
ScanHit? _selected;
161161
Object? _lastError;
162162
bool _disposed = false;
163+
int _intent = 0;
164+
Future<void>? _disposeFuture;
165+
final Set<Future<void>> _retirements = <Future<void>>{};
163166

164167
@override
165168
Connection get connection => _facade;
@@ -181,6 +184,7 @@ class PbleConnectionManager implements ConnectionManager {
181184

182185
@override
183186
Future<void> startScan({Duration? timeout}) async {
187+
_ensureActive();
184188
// Fire-and-forget: a broadcast-subscription cancel() future never completes
185189
// under `tester.pump()` (FakeAsync), which would stall connect/stopScan in
186190
// every widget test. The listener is removed synchronously either way; the
@@ -199,6 +203,7 @@ class PbleConnectionManager implements ConnectionManager {
199203

200204
@override
201205
Future<void> stopScan() async {
206+
_ensureActive();
202207
// Fire-and-forget: a broadcast-subscription cancel() future never completes
203208
// under `tester.pump()` (FakeAsync), which would stall connect/stopScan in
204209
// every widget test. The listener is removed synchronously either way; the
@@ -208,75 +213,144 @@ class PbleConnectionManager implements ConnectionManager {
208213
await _scanner.stopScan();
209214
// Only fall back to idle when no board is live (a connected session keeps
210215
// its connected/connecting phase).
211-
if (_liveBoard == null && _phase.value == ConnectPhase.scanning) {
216+
if (!_disposed &&
217+
_liveBoard == null &&
218+
_phase.value == ConnectPhase.scanning) {
212219
_phase.value = ConnectPhase.idle;
213220
}
214221
}
215222

216223
@override
217224
Future<void> connect(String id) async {
225+
_ensureActive();
226+
final int intent = ++_intent;
227+
_detachAndRetire();
218228
// Scanning and GATT do not run together — stop the scan first (FR-BLE-5).
219229
// Fire-and-forget: a broadcast-subscription cancel() future never completes
220230
// under `tester.pump()` (FakeAsync), which would stall connect/stopScan in
221231
// every widget test. The listener is removed synchronously either way; the
222232
// completion signal is not needed here (matches _StableFacade.detach below).
223233
unawaited(_scanSub?.cancel());
224234
_scanSub = null;
225-
await _scanner.stopScan();
226-
227235
_selected = _hits[id] ?? ScanHit(id: id, name: '', rssi: 0);
228236
_lastError = null;
229237
_phase.value = ConnectPhase.connecting;
230238
try {
239+
await _scanner.stopScan();
240+
// A previous Disconnect/replacement may still own a physical close.
241+
// Do not open another board until those exact retirements complete.
242+
await Future.wait(_retirements.toList());
243+
if (!_isCurrent(intent)) return;
231244
final Connection board = await _connectionFactory(id);
245+
if (!_isCurrent(intent)) {
246+
await _retire(board);
247+
return;
248+
}
232249
_liveBoard = board;
233250
_facade.attach(board);
234251
// Derive the phase from the freshly attached board's live state (the
235252
// listener also fires on the sync-up, but re-derive to cover a board that
236253
// attaches already-ready with no state change).
237254
_phase.value = _phaseForConn(_facade.state.value);
238255
} catch (error) {
239-
_lastError = error;
240-
_phase.value = ConnectPhase.failed;
256+
if (_isCurrent(intent)) {
257+
_lastError = error;
258+
_phase.value = ConnectPhase.failed;
259+
}
241260
rethrow;
242261
}
243262
}
244263

245264
@override
246265
Future<void> disconnect() async {
247-
final Connection? board = _liveBoard;
248-
// Null the live board BEFORE detaching so the facade's reset to
249-
// disconnected does not drive the phase (we set it to idle explicitly).
250-
_liveBoard = null;
251-
_facade.detach();
252-
await board?.dispose();
266+
_ensureActive();
267+
final int intent = ++_intent;
268+
_detachAndRetire();
253269
_selected = null;
254-
_phase.value = ConnectPhase.idle;
270+
try {
271+
await Future.wait(_retirements.toList());
272+
if (_isCurrent(intent)) {
273+
_lastError = null;
274+
_phase.value = ConnectPhase.idle;
275+
}
276+
} catch (error) {
277+
if (_isCurrent(intent)) {
278+
_lastError = error;
279+
_phase.value = ConnectPhase.failed;
280+
}
281+
rethrow;
282+
}
255283
}
256284

257285
@override
258-
Future<void> dispose() async {
259-
if (_disposed) return;
286+
Future<void> dispose() {
287+
if (_disposeFuture case final Future<void> pending) return pending;
260288
_disposed = true;
289+
_intent++;
290+
return _disposeFuture = Future<void>.microtask(_disposeResources);
291+
}
292+
293+
Future<void> _disposeResources() async {
294+
Object? firstError;
295+
StackTrace? firstStack;
296+
Future<void> attempt(FutureOr<void> Function() action) async {
297+
try {
298+
await action();
299+
} catch (error, stack) {
300+
firstError ??= error;
301+
firstStack ??= stack;
302+
}
303+
}
304+
261305
// Fire-and-forget: a broadcast-subscription cancel() future never completes
262306
// under `tester.pump()` (FakeAsync), which would stall connect/stopScan in
263307
// every widget test. The listener is removed synchronously either way; the
264308
// completion signal is not needed here (matches _StableFacade.detach below).
265309
unawaited(_scanSub?.cancel());
266310
_scanSub = null;
267311
_facade.state.removeListener(_onFacadeState);
312+
_detachAndRetire();
313+
_selected = null;
314+
await attempt(() => Future.wait(_retirements.toList()));
315+
await attempt(_scanResults.close);
316+
await attempt(_facade.dispose);
317+
await attempt(_phase.dispose);
318+
if (firstError != null) {
319+
Error.throwWithStackTrace(firstError!, firstStack!);
320+
}
321+
}
322+
323+
bool _isCurrent(int intent) => !_disposed && _intent == intent;
324+
325+
void _ensureActive() {
326+
if (_disposed) throw StateError('connection manager disposed');
327+
}
328+
329+
void _detachAndRetire() {
268330
final Connection? board = _liveBoard;
269331
_liveBoard = null;
270-
await board?.dispose();
271-
await _scanResults.close();
272-
await _facade.dispose();
273-
_phase.dispose();
332+
_facade.detach();
333+
if (board != null) _retire(board);
334+
}
335+
336+
Future<void> _retire(Connection board) {
337+
final Future<void> closing = Future<void>.sync(board.dispose);
338+
_retirements.add(closing);
339+
// The original future retains any error for its owning operation; this
340+
// bookkeeping branch must not create a second unhandled error future.
341+
unawaited(
342+
closing.then<void>(
343+
(_) => _retirements.remove(closing),
344+
onError: (Object _, StackTrace __) => _retirements.remove(closing),
345+
),
346+
);
347+
return closing;
274348
}
275349

276350
// Track the session phase off the stable facade's live ConnState. Only
277351
// meaningful while a board is attached; scan/failure phases own the idle path.
278352
void _onFacadeState() {
279-
if (_liveBoard == null) return;
353+
if (_disposed || _liveBoard == null) return;
280354
_phase.value = _phaseForConn(_facade.state.value);
281355
}
282356

‎app/lib/pble/pble_connection.dart‎

Lines changed: 87 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)