From 8a2d83139bd606fce01bd0d8c895b87c3676dfe2 Mon Sep 17 00:00:00 2001 From: Jonas Bark Date: Thu, 20 Aug 2026 15:33:57 +0200 Subject: [PATCH] feat(trainer): cycle the bridge connection when the control protocol changes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Trainers latch their control session to the protocol live at connect time, so a switch only takes real effect on a fresh connection (Jonas verified on hardware via the manual Bridge disconnect/reconnect). Both switch sites — the VS-options selector and the self-test verdict CTA — now run ProxyDevice.reconnectUpstream(), which mirrors the ConnectionCard cycle and waits for the reseeded definition. Inert picks (same effective delivery) skip the cycle. Co-Authored-By: Claude Fable 5 --- lib/bluetooth/devices/proxy/proxy_device.dart | 19 ++++++++ .../proxy_device_details/self_test_card.dart | 16 ++++++- .../trainer_settings_section.dart | 17 ++++++- .../control_protocol_select_test.dart | 45 ++++++++++++++++++- .../self_test_card_test.dart | 10 ++++- 5 files changed, 101 insertions(+), 6 deletions(-) diff --git a/lib/bluetooth/devices/proxy/proxy_device.dart b/lib/bluetooth/devices/proxy/proxy_device.dart index eb19c123..e3a0b9c5 100644 --- a/lib/bluetooth/devices/proxy/proxy_device.dart +++ b/lib/bluetooth/devices/proxy/proxy_device.dart @@ -855,6 +855,25 @@ class ProxyDevice extends BluetoothDevice { @override Future disconnectUpstream() => transport.disconnect(); + /// Tears the upstream trainer connection down and brings it back up — the + /// programmatic twin of picking "No connection" and then the bridge mode + /// again in the ConnectionCard. A control-protocol change only takes real + /// effect on a fresh connection: trainers latch their control session to + /// the protocol that was live at connect time, so the cycle re-runs + /// discovery, reseeds the definition (re-applying the persisted override) + /// and performs the new protocol's handshakes from scratch. + Future reconnectUpstream() async { + if (!isConnected && !isStartedListenable.value) return; + await core.connection.disconnect(this, forget: false, persistForget: false, keepInList: true); + await core.connection.connectDevice(this); + // connectDevice resolves before discovery finishes on some transports — + // wait for the rebuilt definition so callers can start using it. + final deadline = DateTime.now().add(const Duration(seconds: 15)); + while ((!isConnected || fitnessBike == null) && DateTime.now().isBefore(deadline)) { + await Future.delayed(const Duration(milliseconds: 200)); + } + } + void _onWifiDisconnected() { if (!isConnected) return; isConnected = false; diff --git a/lib/pages/proxy_device_details/self_test_card.dart b/lib/pages/proxy_device_details/self_test_card.dart index 973336ae..3c3f6e79 100644 --- a/lib/pages/proxy_device_details/self_test_card.dart +++ b/lib/pages/proxy_device_details/self_test_card.dart @@ -34,7 +34,11 @@ class SelfTestCard extends StatefulWidget { /// Wired by the page to its overlay-section reveal; used by the PASS CTA. final VoidCallback? onShowOverlaySettings; - const SelfTestCard({super.key, required this.device, this.engineFactory, this.onShowOverlaySettings}); + /// Test seam: the connection cycle a protocol switch triggers; defaults to + /// [ProxyDevice.reconnectUpstream]. + final Future Function()? reconnectDevice; + + const SelfTestCard({super.key, required this.device, this.engineFactory, this.onShowOverlaySettings, this.reconnectDevice}); @override State createState() => _SelfTestCardState(); @@ -411,6 +415,16 @@ class _SelfTestCardState extends State { /// [ShiftingConfig]. Future _switchProtocolAndRerun(String protocol) async { _engine?.harness.setProtocol(protocol); + // The trainer only honors the new delivery on a fresh connection (it + // latches its control session at connect time) — cycle the bridge the way + // the ConnectionCard's manual disconnect/reconnect does, then rerun on + // the rebuilt definition. [ProxyDevice.reconnectUpstream] itself waits + // for the definition to come back. + try { + await (widget.reconnectDevice ?? widget.device.reconnectUpstream)(); + } catch (e, s) { + recordError(e, s, context: 'self-test protocol switch reconnect'); + } await _start(); } diff --git a/lib/pages/proxy_device_details/trainer_settings_section.dart b/lib/pages/proxy_device_details/trainer_settings_section.dart index ecda0f79..98f42ddc 100644 --- a/lib/pages/proxy_device_details/trainer_settings_section.dart +++ b/lib/pages/proxy_device_details/trainer_settings_section.dart @@ -14,7 +14,12 @@ import 'package:shadcn_flutter/shadcn_flutter.dart'; class TrainerSettingsSection extends StatefulWidget { final FitnessBikeDefinition definition; final ProxyDevice device; - const TrainerSettingsSection({super.key, required this.definition, required this.device}); + + /// Test seam: the connection cycle a protocol change triggers; defaults to + /// [ProxyDevice.reconnectUpstream]. + final Future Function()? reconnectDevice; + + const TrainerSettingsSection({super.key, required this.definition, required this.device, this.reconnectDevice}); @override State createState() => _TrainerSettingsSectionState(); @@ -110,11 +115,21 @@ class _TrainerSettingsSectionState extends State { Text(protocol == null ? context.i18n.controlProtocolAuto : _protocolLabel(protocol)), placeholder: Text(context.i18n.controlProtocolAuto), onChanged: (protocol) async { + final before = def.controlProtocol; def.setControlProtocolOverride(protocol); await core.settings.setControlProtocolOverride(widget.device.trainerKey, protocol?.name); // The override is plain state on the definition, not a listenable — // nothing else would repaint the select with the new value. if (mounted) setState(() {}); + // The trainer latches its control session to the protocol that was + // live at connect time, so an effective change only takes hold on a + // fresh connection — cycle the bridge like the ConnectionCard's + // manual disconnect/reconnect would. Inert picks (same effective + // delivery, e.g. forcing zwiftHub on an auto-zwiftHub trainer) + // skip the cycle. + if (def.controlProtocol != before) { + await (widget.reconnectDevice ?? widget.device.reconnectUpstream)(); + } }, ), ); diff --git a/test/pages/proxy_device_details/control_protocol_select_test.dart b/test/pages/proxy_device_details/control_protocol_select_test.dart index a1e181b9..e7cdf72e 100644 --- a/test/pages/proxy_device_details/control_protocol_select_test.dart +++ b/test/pages/proxy_device_details/control_protocol_select_test.dart @@ -116,7 +116,11 @@ Future main() async { return device; } - Future pumpSection(WidgetTester tester, ProxyDevice device) async { + Future pumpSection( + WidgetTester tester, + ProxyDevice device, { + Future Function()? reconnect, + }) async { await tester.pumpWidget( ShadcnApp( localizationsDelegates: const [AppLocalizations.delegate], @@ -125,7 +129,12 @@ Future main() async { child: SingleChildScrollView( child: SizedBox( width: 380, - child: TrainerSettingsSection(definition: device.fitnessBike!, device: device), + child: TrainerSettingsSection( + definition: device.fitnessBike!, + device: device, + // Keep widget tests off the real connection manager. + reconnectDevice: reconnect ?? () async {}, + ), ), ), ), @@ -166,6 +175,38 @@ Future main() async { expect(core.settings.getControlProtocolOverride(device.trainerKey), 'zwiftHub'); }); + testWidgets('switching to a different effective protocol cycles the connection', (tester) async { + final device = trainer(dualProtocolServices()); + var reconnects = 0; + await pumpSection(tester, device, reconnect: () async => reconnects++); + + await tester.tap(find.byType(Select)); + await tester.pumpAndSettle(); + // Auto on this fixture is zwiftHub, so forcing FTMS changes the delivery. + await tester.tap(find.text(AppLocalizations.current.controlProtocolFtms).last); + await tester.pumpAndSettle(); + + expect(device.fitnessBike!.controlProtocol, TrainerControlProtocol.ftms); + expect(reconnects, 1); + await tester.pump(const Duration(seconds: 1)); + }); + + testWidgets('an inert selection (same effective protocol) does not cycle the connection', (tester) async { + final device = trainer(dualProtocolServices()); + var reconnects = 0; + await pumpSection(tester, device, reconnect: () async => reconnects++); + + await tester.tap(find.byType(Select)); + await tester.pumpAndSettle(); + // Explicitly picking "Zwift protocol" on an auto-zwiftHub trainer is the + // documented inert choice — no delivery change, so no reconnect. + await tester.tap(find.text(AppLocalizations.current.controlProtocolZwift).last); + await tester.pumpAndSettle(); + + expect(device.fitnessBike!.controlProtocol, TrainerControlProtocol.zwiftHub); + expect(reconnects, 0); + }); + testWidgets('picking Auto again clears the stored override', (tester) async { final device = trainer(dualProtocolServices()); final def = device.fitnessBike!; diff --git a/test/pages/proxy_device_details/self_test_card_test.dart b/test/pages/proxy_device_details/self_test_card_test.dart index 0f1b9a5a..1c08d530 100644 --- a/test/pages/proxy_device_details/self_test_card_test.dart +++ b/test/pages/proxy_device_details/self_test_card_test.dart @@ -71,6 +71,7 @@ Future main() async { ProxyDevice device, FakeSelfTestHarness harness, { VoidCallback? onShowOverlaySettings, + Future Function()? reconnect, }) async { await tester.pumpWidget( ShadcnApp( @@ -81,6 +82,8 @@ Future main() async { device: device, engineFactory: () => engineOver(harness), onShowOverlaySettings: onShowOverlaySettings, + // Keep widget tests off the real connection manager. + reconnectDevice: reconnect ?? () async {}, ), ), ), @@ -276,7 +279,8 @@ Future main() async { ..obeysShift = false ..supportedProtocolNames = ['ftms', 'zwiftHub']; - await pumpCard(tester, connectedTrainer(), harness); + var reconnects = 0; + await pumpCard(tester, connectedTrainer(), harness, reconnect: () async => reconnects++); await tester.tap(find.text('Test resistance control')); await tester.pumpAndSettle(); @@ -288,8 +292,10 @@ Future main() async { await tester.tap(find.text('Try via Zwift protocol & run again')); await tester.pump(); - // The tap flips the fake's recorded protocol before the fresh run starts. + // The tap flips the fake's recorded protocol and cycles the trainer + // connection before the fresh run starts. expect(harness.protocolName, 'zwiftHub'); + expect(reconnects, 1); expect(find.text('Stop test'), findsOneWidget); await tester.pumpAndSettle();