feat(click v2): keep the right puck awake, and say when it can't

The right puck switches itself off after a minute of not being used.
BikeControl now prevents that on its own, with no button to press. The
sequence lives in prop; this side supplies what only it knows and shows
the rider the one case they can fix.

- the gate reads raw adverts, not the device list: the sibling only has
  to be nearby, and a left puck the rider ignored — every left puck in
  right-side-only mode — still counts. Discovery is also the retrigger,
  since an ignored puck never completes a handshake
- an optional step on the controller card, and a note on the right puck's
  own card, when no left puck is in range. An offer, never a blocker
- drops the D-pad line from "use the right side only"

Fixes a related bug: the controller link counted every undone step,
optional or not, so an optional offer alone turned a working controller
amber and held back "Ready to ride". The other two links already
excluded optional steps.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jonas Bark
2026-08-20 14:55:15 +02:00
parent 4af3dbcddf
commit 1d1a0dbf72
19 changed files with 271 additions and 14 deletions

View File

@@ -9,6 +9,7 @@ import 'package:bike_control/bluetooth/devices/proxy/proxy_device.dart';
import 'package:bike_control/bluetooth/devices/wahoo/wahoo_kickr_climb.dart';
import 'package:bike_control/bluetooth/devices/wahoo/wahoo_kickr_headwind.dart';
import 'package:bike_control/bluetooth/devices/zwift/zwift_clickv2.dart';
import 'package:bike_control/bluetooth/devices/zwift/zwift_clickv2_left_side.dart';
import 'package:bike_control/bluetooth/inactivity_disconnector.dart';
import 'package:bike_control/bluetooth/incline/incline_controller.dart';
import 'package:bike_control/bluetooth/incline/incline_sink.dart';
@@ -90,6 +91,31 @@ class Connection {
return byserial.values;
}
/// Whether a Zwift Click V2 left puck is switched on within range.
///
/// Read from the raw adverts, not from [devices], and deliberately so: the
/// right puck only needs its sibling *nearby* to be kept awake, not paired.
/// In right-side-only mode the left puck is on the ignored list and so never
/// enters [devices] at all, yet it is still advertising and still counts.
bool get hasNearbyClickV2LeftSide {
if (_lastScanResult.any(isClickV2LeftSideAdvert)) return true;
// A left puck that connected before the scan list was last cleared no
// longer has an advert to find, but is plainly still there.
return devices.whereType<ZwiftClickV2LeftSide>().any((d) => d.isConnected);
}
/// Whether an advert is a Click V2 left puck, by the Zwift manufacturer
/// record's device-type byte. Split out from [hasNearbyClickV2LeftSide] so
/// the identification can be tested without a radio.
@visibleForTesting
static bool isClickV2LeftSideAdvert(BleDevice adv) {
final payload = adv.manufacturerDataList
.firstOrNullWhere((e) => e.companyId == ZwiftConstants.ZWIFT_MANUFACTURER_ID)
?.payload;
if (payload == null || payload.isEmpty) return false;
return ZwiftDeviceType.fromManufacturerData(payload.first) == ZwiftDeviceType.clickV2Left;
}
static Uint8List? _sramServiceDataRecord(Map<String, Uint8List> serviceData) {
for (final e in serviceData.entries) {
if (e.key.toLowerCase().contains('fe51')) return e.value;
@@ -381,6 +407,10 @@ class Connection {
}
};
// The right puck's keep-awake needs its sibling in range, and only this
// side can see what is in range.
ClickLogic.isLeftSideNearby = () => hasNearbyClickV2LeftSide;
UniversalBle.onAvailabilityChange = (available) {
_actionStreams.add(BluetoothAvailabilityNotification(available == AvailabilityState.poweredOn));
if (available == AvailabilityState.poweredOn && !kIsWeb) {
@@ -407,6 +437,12 @@ class Connection {
if (_lastScanResult.none((e) => e.deviceId == result.deviceId && e.services.contentEquals(result.services))) {
_lastScanResult.add(result);
// A left puck coming into range may be exactly what a right puck has
// been waiting for, and an ignored one never gets further than this —
// it is discovered and then dropped, so discovery is the only signal.
// No-op unless a right puck is actually waiting.
ClickLogic.startKeepAwakeIfPending();
if (kDebugMode) {
debugPrint('Scan result: ${result.name} - ${result.deviceId} - Services: ${result.services}');
}

View File

@@ -9,6 +9,7 @@ import 'package:bike_control/utils/keymap/apps/custom_app.dart';
import 'package:bike_control/utils/keymap/buttons.dart';
import 'package:bike_control/utils/keymap/keymap.dart';
import 'package:bike_control/utils/keymap/manager.dart';
import 'package:bike_control/widgets/click_v2/keep_awake_warning.dart';
import 'package:bike_control/widgets/controller/controller_layout.dart';
import 'package:bike_control/widgets/ui/toast.dart';
import 'package:bike_control/widgets/unlock_toggle.dart';
@@ -99,6 +100,14 @@ class ZwiftClickV2RightSide extends ZwiftRide {
ClickLogic.setupHandshake(services!, device.deviceId, isRight: true);
}
@override
Future<void> disconnect() async {
// Drops the remembered handle and the "connect the left side" prompt with
// it — there is no longer a right puck for the rider to fix.
ClickLogic.forgetKeepAwake();
await super.disconnect();
}
@override
List<Widget> showAdditionalInformation(BuildContext context) {
// Connected, not merely discovered: right-side-only mode holds the left
@@ -110,6 +119,7 @@ class ZwiftClickV2RightSide extends ZwiftRide {
// into the explainer belongs on either card — a rider looking at the
// right side shouldn't have to find the left one to change it.
const UnlockToggle(children: []),
if (isConnected && !screenshotMode) const ClickV2KeepAwakeWarning(),
if (hasLiveLeftSide) ...[
Text(context.i18n.unlock_useRightSideOnlyDescription).xSmall.normal,
SizedBox(

View File

@@ -190,7 +190,6 @@
"clickV2Onboarding_rightOnlyPro1": "Kein Zwift-Entsperren — nie",
"clickV2Onboarding_rightOnlyPro2": "Keine Neustarts, keine Aussetzer während der Fahrt",
"clickV2Onboarding_rightOnlyCon1": "Nur der rechte Controller sendet Tastendrücke",
"clickV2Onboarding_rightOnlyCon2": "Kein Steuerkreuz — keine Lenkung, keine Aktionsleiste",
"clickV2Onboarding_rightOnlyCta": "Rechte Seite nutzen",
"clickV2Onboarding_zwiftTitle": "Mit Zwift entsperren",
"clickV2Onboarding_zwiftPro1": "Beide Controller funktionieren",
@@ -708,6 +707,7 @@
"unlock_newMethod": "Neue Entsperrmethode verwenden",
"unlock_newMethodDescription": "Verbinde die linke und rechte Seite als getrennte Controller. Die rechte Seite muss nicht entsperrt werden. Deaktivieren, um einen einzelnen kombinierten Controller zu verwenden.",
"unlock_newMethodReconnecting": "Wird übernommen… dein Zwift Click wird neu verbunden.",
"clickV2_keepAwakeNeedsLeftSide": "Schalte die linke Seite ein, damit sich dieser Controller nicht nach einer Minute ohne Nutzung abschaltet. Sie muss nur in der Nähe sein – BikeControl muss sich nicht mit ihr verbinden.",
"unlock_useRightSideOnly": "Nur die rechte Seite verwenden",
"unlock_useRightSideOnlyDescription": "Die rechte Seite muss nicht entsperrt werden. Trenne die linke Seite und lass die rechte Seite das Schalten übernehmen – + schaltet hoch, B schaltet runter.",
"unlock_rightSideOnlyConfigured": "Fertig – es wird nur die rechte Seite verwendet. Du kannst die linke Seite jederzeit unter „Ignorierte Geräte“ wieder aktivieren.",
@@ -1584,6 +1584,8 @@
"chainStepSramSetupHint": "Noch schaltet das Schaltwerk selbst — übergib die Gänge an BikeControl, damit die Hebel Tastendrücke senden.",
"chainStepClickV2Setup": "Wähle die Entsperrmethode",
"chainStepClickV2SetupHint": "Zwift bindet den Click V2 an die eigene App. Wähle, wie BikeControl das umgeht — danach verbindet er sich sofort.",
"chainStepClickV2KeepAwake": "Linke Seite einschalten, damit der Controller anbleibt",
"chainStepClickV2KeepAwakeHint": "Allein schaltet sich die rechte Seite nach einer Minute ohne Nutzung ab. Mit eingeschalteter linker Seite in der Nähe kann BikeControl sie wach halten – sie muss nur in Reichweite sein, nicht verbunden.",
"chainStepTrainerPaired": "Trainer verbunden",
"chainStepTrainerPairedPending": "Verbinde deinen Trainer",
"chainStepOverlay": "Zeig deinen Gang auf dem Bildschirm",

View File

@@ -170,7 +170,6 @@
"clickV2Onboarding_rightOnlyPro1": "No Zwift unlock — ever",
"clickV2Onboarding_rightOnlyPro2": "No restarts, no drop-outs mid-ride",
"clickV2Onboarding_rightOnlyCon1": "Only the right controller sends button presses",
"clickV2Onboarding_rightOnlyCon2": "No D-pad — no steering, no action bar",
"clickV2Onboarding_rightOnlyCta": "Use the right side",
"clickV2Onboarding_zwiftTitle": "Unlock with Zwift",
"clickV2Onboarding_zwiftPro1": "Both controllers work",
@@ -1123,6 +1122,7 @@
"unlock_newMethod": "Use new unlock method",
"unlock_newMethodDescription": "Connect the left and right sides as separate controllers. The right side needs no unlocking. Turn off to use a single combined controller.",
"unlock_newMethodReconnecting": "Applying… reconnecting your Zwift Click.",
"clickV2_keepAwakeNeedsLeftSide": "Switch the left side on to stop this controller powering off after a minute of not being used. It only needs to be nearby — BikeControl does not have to connect to it.",
"unlock_useRightSideOnly": "Use the right side only",
"unlock_useRightSideOnlyDescription": "The right side needs no unlocking. Drop the left side and let the right side handle shifting — + shifts up, B shifts down.",
"unlock_rightSideOnlyConfigured": "Done — using the right side only. Re-enable the left side anytime under Ignored devices.",
@@ -1778,6 +1778,8 @@
"chainStepSramSetupHint": "Its own shifting still runs the gears — hand them to BikeControl so the paddles send button presses.",
"chainStepClickV2Setup": "Choose how it unlocks",
"chainStepClickV2SetupHint": "Zwift locks the Click V2 to their own app. Pick how BikeControl works around it and it connects straight away.",
"chainStepClickV2KeepAwake": "Switch the left side on to stop the controller powering off",
"chainStepClickV2KeepAwakeHint": "On its own, the right side switches itself off after a minute of not being used. With the left side switched on nearby, BikeControl can keep it awake — it only needs to be in range, not paired.",
"chainStepTrainerPaired": "Trainer connected",
"chainStepTrainerPairedPending": "Connect your trainer",
"chainStepOverlay": "Show your gear on screen",

View File

@@ -190,7 +190,6 @@
"clickV2Onboarding_rightOnlyPro1": "Sin desbloqueo de Zwift, nunca",
"clickV2Onboarding_rightOnlyPro2": "Sin reinicios ni cortes durante la sesión",
"clickV2Onboarding_rightOnlyCon1": "Solo el mando derecho envía pulsaciones",
"clickV2Onboarding_rightOnlyCon2": "Sin cruceta: sin dirección ni barra de acciones",
"clickV2Onboarding_rightOnlyCta": "Usar el lado derecho",
"clickV2Onboarding_zwiftTitle": "Desbloquear con Zwift",
"clickV2Onboarding_zwiftPro1": "Funcionan los dos mandos",
@@ -708,6 +707,7 @@
"unlock_newMethod": "Usar el nuevo método de desbloqueo",
"unlock_newMethodDescription": "Conecta los lados izquierdo y derecho como mandos independientes. El lado derecho no necesita desbloqueo. Desactívalo para usar un único mando combinado.",
"unlock_newMethodReconnecting": "Aplicando… reconectando tu Zwift Click.",
"clickV2_keepAwakeNeedsLeftSide": "Enciende el lado izquierdo para que este mando no se apague tras un minuto sin usarse. Solo tiene que estar cerca: BikeControl no necesita conectarse a él.",
"unlock_useRightSideOnly": "Usar solo el lado derecho",
"unlock_useRightSideOnlyDescription": "El lado derecho no necesita desbloqueo. Desconecta el lado izquierdo y deja que el derecho gestione el cambio de marchas: + sube y B baja.",
"unlock_rightSideOnlyConfigured": "Listo: se usa solo el lado derecho. Puedes volver a activar el lado izquierdo cuando quieras en Dispositivos ignorados.",
@@ -1584,6 +1584,8 @@
"chainStepSramSetupHint": "El desviador aún cambia por su cuenta: cédele las marchas a BikeControl para que las palancas envíen pulsaciones.",
"chainStepClickV2Setup": "Elige cómo se desbloquea",
"chainStepClickV2SetupHint": "Zwift limita el Click V2 a su propia aplicación. Elige cómo lo resuelve BikeControl y se conectará enseguida.",
"chainStepClickV2KeepAwake": "Enciende el lado izquierdo para que el mando no se apague",
"chainStepClickV2KeepAwakeHint": "Por sí solo, el lado derecho se apaga tras un minuto sin usarse. Con el lado izquierdo encendido cerca, BikeControl puede mantenerlo activo: solo tiene que estar al alcance, no emparejado.",
"chainStepTrainerPaired": "Rodillo conectado",
"chainStepTrainerPairedPending": "Conecta tu rodillo",
"chainStepOverlay": "Muestra tu marcha en pantalla",

View File

@@ -190,7 +190,6 @@
"clickV2Onboarding_rightOnlyPro1": "Aucun déverrouillage Zwift, jamais",
"clickV2Onboarding_rightOnlyPro2": "Aucun redémarrage, aucune coupure pendant la séance",
"clickV2Onboarding_rightOnlyCon1": "Seule la manette droite envoie les appuis",
"clickV2Onboarding_rightOnlyCon2": "Pas de croix directionnelle : ni direction ni barre d'actions",
"clickV2Onboarding_rightOnlyCta": "Utiliser le côté droit",
"clickV2Onboarding_zwiftTitle": "Déverrouiller avec Zwift",
"clickV2Onboarding_zwiftPro1": "Les deux manettes fonctionnent",
@@ -708,6 +707,7 @@
"unlock_newMethod": "Utiliser la nouvelle méthode de déverrouillage",
"unlock_newMethodDescription": "Connecte les côtés gauche et droit comme des manettes distinctes. Le côté droit ne nécessite aucun déverrouillage. Désactive pour utiliser une seule manette combinée.",
"unlock_newMethodReconnecting": "Application… reconnexion de ton Zwift Click.",
"clickV2_keepAwakeNeedsLeftSide": "Allume le côté gauche pour éviter que cette manette ne s'éteigne après une minute sans utilisation. Il suffit qu'il soit à proximité : BikeControl n'a pas besoin de s'y connecter.",
"unlock_useRightSideOnly": "Utiliser uniquement le côté droit",
"unlock_useRightSideOnlyDescription": "Le côté droit ne nécessite aucun déverrouillage. Déconnecte le côté gauche et laisse le côté droit gérer les changements de vitesse : + monte, B descend.",
"unlock_rightSideOnlyConfigured": "Terminé — seul le côté droit est utilisé. Tu peux réactiver le côté gauche à tout moment dans Appareils ignorés.",
@@ -1584,6 +1584,8 @@
"chainStepSramSetupHint": "Le dérailleur gère encore les vitesses lui-même : confie-les à BikeControl pour que les leviers envoient des appuis.",
"chainStepClickV2Setup": "Choisis le mode de déverrouillage",
"chainStepClickV2SetupHint": "Zwift réserve le Click V2 à sa propre application. Choisis comment BikeControl contourne cela et il se connecte aussitôt.",
"chainStepClickV2KeepAwake": "Allume le côté gauche pour que la manette reste allumée",
"chainStepClickV2KeepAwakeHint": "Seul, le côté droit s'éteint après une minute sans utilisation. Avec le côté gauche allumé à proximité, BikeControl peut le garder actif : il suffit qu'il soit à portée, sans être connecté.",
"chainStepTrainerPaired": "Home trainer connecté",
"chainStepTrainerPairedPending": "Connecte ton home trainer",
"chainStepOverlay": "Affiche ta vitesse à l'écran",

View File

@@ -190,7 +190,6 @@
"clickV2Onboarding_rightOnlyPro1": "Nessuno sblocco con Zwift, mai",
"clickV2Onboarding_rightOnlyPro2": "Nessun riavvio, nessuna interruzione durante l'uscita",
"clickV2Onboarding_rightOnlyCon1": "Solo il controller destro invia i comandi",
"clickV2Onboarding_rightOnlyCon2": "Niente crocetta: né sterzata né barra delle azioni",
"clickV2Onboarding_rightOnlyCta": "Usa il lato destro",
"clickV2Onboarding_zwiftTitle": "Sblocca con Zwift",
"clickV2Onboarding_zwiftPro1": "Funzionano entrambi i controller",
@@ -708,6 +707,7 @@
"unlock_newMethod": "Usa il nuovo metodo di sblocco",
"unlock_newMethodDescription": "Collega il lato sinistro e destro come controller separati. Il lato destro non richiede alcuno sblocco. Disattiva per usare un unico controller combinato.",
"unlock_newMethodReconnecting": "Applicazione… riconnessione del tuo Zwift Click.",
"clickV2_keepAwakeNeedsLeftSide": "Accendi il lato sinistro per evitare che questo controller si spenga dopo un minuto di inutilizzo. Basta che sia nelle vicinanze: BikeControl non deve collegarsi a esso.",
"unlock_useRightSideOnly": "Usa solo il lato destro",
"unlock_useRightSideOnlyDescription": "Il lato destro non richiede alcuno sblocco. Scollega il lato sinistro e lascia che il destro gestisca il cambio: + sale, B scende.",
"unlock_rightSideOnlyConfigured": "Fatto: viene usato solo il lato destro. Puoi riattivare il lato sinistro in qualsiasi momento in Dispositivi ignorati.",
@@ -1584,6 +1584,8 @@
"chainStepSramSetupHint": "Il cambio gestisce ancora le marce da solo: affidale a BikeControl così le leve inviano pressioni.",
"chainStepClickV2Setup": "Scegli come sbloccarlo",
"chainStepClickV2SetupHint": "Zwift vincola il Click V2 alla propria app. Scegli come BikeControl aggira il problema e si collegherà subito.",
"chainStepClickV2KeepAwake": "Accendi il lato sinistro per non far spegnere il controller",
"chainStepClickV2KeepAwakeHint": "Da solo, il lato destro si spegne dopo un minuto di inutilizzo. Con il lato sinistro acceso nelle vicinanze, BikeControl può tenerlo attivo: basta che sia a portata, non collegato.",
"chainStepTrainerPaired": "Rullo collegato",
"chainStepTrainerPairedPending": "Collega il tuo rullo",
"chainStepOverlay": "Mostra la marcia sullo schermo",

View File

@@ -190,7 +190,6 @@
"clickV2Onboarding_rightOnlyPro1": "Żadnego odblokowywania przez Zwift",
"clickV2Onboarding_rightOnlyPro2": "Bez restartów i przerw w trakcie jazdy",
"clickV2Onboarding_rightOnlyCon1": "Tylko prawy kontroler wysyła naciśnięcia przycisków",
"clickV2Onboarding_rightOnlyCon2": "Bez krzyżaka — bez sterowania i paska akcji",
"clickV2Onboarding_rightOnlyCta": "Używaj prawej strony",
"clickV2Onboarding_zwiftTitle": "Odblokuj przez Zwift",
"clickV2Onboarding_zwiftPro1": "Działają oba kontrolery",
@@ -708,6 +707,7 @@
"unlock_newMethod": "Użyj nowej metody odblokowania",
"unlock_newMethodDescription": "Połącz lewą i prawą stronę jako osobne kontrolery. Prawa strona nie wymaga odblokowywania. Wyłącz, aby używać jednego połączonego kontrolera.",
"unlock_newMethodReconnecting": "Stosowanie… ponowne łączenie z Zwift Click.",
"clickV2_keepAwakeNeedsLeftSide": "Włącz lewą stronę, aby ten kontroler nie wyłączał się po minucie bez używania. Musi być tylko w pobliżu — BikeControl nie musi się z nią łączyć.",
"unlock_useRightSideOnly": "Używaj tylko prawej strony",
"unlock_useRightSideOnlyDescription": "Prawa strona nie wymaga odblokowywania. Odłącz lewą stronę i pozwól prawej obsługiwać zmianę biegów — + w górę, B w dół.",
"unlock_rightSideOnlyConfigured": "Gotowe — używana jest tylko prawa strona. Lewą stronę możesz ponownie włączyć w dowolnej chwili w sekcji Ignorowane urządzenia.",
@@ -1584,6 +1584,8 @@
"chainStepSramSetupHint": "Przerzutka wciąż zmienia biegi sama — przekaż je BikeControl, aby manetki wysyłały naciśnięcia.",
"chainStepClickV2Setup": "Wybierz sposób odblokowania",
"chainStepClickV2SetupHint": "Zwift przypisuje Click V2 do własnej aplikacji. Wybierz, jak BikeControl to obchodzi — połączy się od razu.",
"chainStepClickV2KeepAwake": "Włącz lewą stronę, aby kontroler się nie wyłączał",
"chainStepClickV2KeepAwakeHint": "Sama prawa strona wyłącza się po minucie bez używania. Gdy lewa strona jest włączona w pobliżu, BikeControl może utrzymać ją aktywną — musi być tylko w zasięgu, nie sparowana.",
"chainStepTrainerPaired": "Trenażer połączony",
"chainStepTrainerPairedPending": "Połącz swój trenażer",
"chainStepOverlay": "Pokaż swój bieg na ekranie",

View File

@@ -144,7 +144,7 @@ class _ClickV2OnboardingPageState extends State<ClickV2OnboardingPage> with Sing
fromPage: 0,
title: l10n.clickV2Onboarding_rightOnlyTitle,
pros: [l10n.clickV2Onboarding_rightOnlyPro1, l10n.clickV2Onboarding_rightOnlyPro2],
cons: [l10n.clickV2Onboarding_rightOnlyCon1, l10n.clickV2Onboarding_rightOnlyCon2],
cons: [l10n.clickV2Onboarding_rightOnlyCon1],
),
_option(
heroPage: 1,

View File

@@ -88,11 +88,21 @@ List<ChainLink> _controllerLinks(ChainInputs inputs) {
hintArg: controller.unlockedUntil,
uncertain: controller.unlockUncertain,
),
// An offer, not work: the right puck functions perfectly without a
// left one, it just switches off after a minute idle. Only emitted
// while outstanding, so it never sits ticked on a card forever.
if (controller.clickV2NeedsLeftSide)
const SetupStep(
id: SetupStepId.controllerClickV2KeepAwake,
done: false,
optional: true,
),
];
// An unfinished checklist outranks a healthy connection: a connected
// controller with no buttons mapped does nothing, so it must not be green.
final incomplete = steps.any((s) => !s.done);
// Optional steps are offers and stay out of it — see [SetupStep.optional].
final incomplete = steps.any((s) => !s.done && !s.optional);
final presenceStatus = _presenceStatus(controller.presence);
final status = incomplete && presenceStatus == LinkStatus.ready ? LinkStatus.attention : presenceStatus;

View File

@@ -46,6 +46,7 @@ class ControllerInput {
this.unlockUncertain = false,
this.sramSetupDone,
this.needsUnlockModeChoice = false,
this.clickV2NeedsLeftSide = false,
});
final String deviceId;
@@ -97,6 +98,11 @@ class ControllerInput {
/// them; without it the card reported "never paired" and "bring it back in
/// range" about a controller sitting switched on beside the rider.
final bool needsUnlockModeChoice;
/// Whether this is a Click V2 right puck that would stop powering itself off
/// if a left puck were switched on nearby. An offer, never a requirement —
/// the controller works either way, it just switches off after a minute.
final bool clickV2NeedsLeftSide;
}
class TrainerInput {

View File

@@ -44,6 +44,7 @@ enum SetupStepId {
controllerUnlocked,
controllerSramSetup,
controllerClickV2Setup,
controllerClickV2KeepAwake,
trainerPaired,
trainerAppBridged,
trainerGearOverlay,

View File

@@ -43,7 +43,7 @@ import 'package:bike_control/widgets/ui/animated_button_widget.dart';
import 'package:bike_control/widgets/ui/connection_method.dart' show enableLocalControl;
import 'package:bike_control/widgets/ui/toast.dart';
import 'package:dartx/dartx.dart';
import 'package:prop/prop.dart' show LogLevel;
import 'package:prop/prop.dart' show ClickKeepAwakeStatus, ClickLogic, LogLevel;
import 'package:shadcn_flutter/shadcn_flutter.dart';
/// How much the chain card wants to talk about a given trainer. Lower wins.
@@ -142,6 +142,14 @@ class _HomePageState extends State<HomePage> {
_refreshBluetoothState();
IAPManager.instance.isPurchased.addListener(_onPurchaseChanged);
// The keep-awake resolves a few seconds after a left puck turns up, which
// is not a connection event — without this the offer would linger on the
// card after it had already been taken up.
ClickLogic.keepAwakeStatus.addListener(_onKeepAwakeChanged);
}
void _onKeepAwakeChanged() {
if (mounted) setState(() {});
}
/// Whether the bridge is running and whether the trainer app holds it are
@@ -174,6 +182,7 @@ class _HomePageState extends State<HomePage> {
_actionListener.cancel();
_metricsTicker?.cancel();
IAPManager.instance.isPurchased.removeListener(_onPurchaseChanged);
ClickLogic.keepAwakeStatus.removeListener(_onKeepAwakeChanged);
super.dispose();
}
@@ -312,6 +321,9 @@ class _HomePageState extends State<HomePage> {
sramSetupDone: device is SramAxs ? !device.needsGuidedSetup : null,
needsUnlockModeChoice:
(device is ZwiftClickV2 || device is ZwiftClickV2RightSide) && ClickV2Onboarding.isPending,
clickV2NeedsLeftSide:
device is ZwiftClickV2RightSide &&
ClickLogic.keepAwakeStatus.value == ClickKeepAwakeStatus.waitingForLeftSide,
),
],
trainer: trainer,

View File

@@ -0,0 +1,33 @@
import 'package:bike_control/utils/i18n_extension.dart';
import 'package:bike_control/widgets/ui/warning.dart';
import 'package:prop/prop.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart';
/// Tells the rider why their right puck is still going to power itself off.
///
/// Keeping it awake needs both pucks on the air once. When only the right one
/// is connected there is nothing the app can do about it, and nothing on the
/// card would otherwise say so — the puck simply switches off a minute later
/// and looks broken. Shown only in that state; the moment the left puck
/// connects the sequence runs and this goes away on its own.
class ClickV2KeepAwakeWarning extends StatelessWidget {
const ClickV2KeepAwakeWarning({super.key});
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<ClickKeepAwakeStatus>(
valueListenable: ClickLogic.keepAwakeStatus,
builder: (context, status, _) {
if (status != ClickKeepAwakeStatus.waitingForLeftSide) {
return const SizedBox.shrink();
}
return Warning(
important: false,
children: [
Text(context.i18n.clickV2_keepAwakeNeedsLeftSide).xSmall,
],
);
},
);
}
}

View File

@@ -51,6 +51,13 @@ ChainStepText chainStepText(BuildContext context, SetupStep step, {String? appNa
l.chainStepClickV2Setup,
l.chainStepClickV2SetupHint,
),
// Optional, so it is only ever emitted while outstanding — the hint carries
// the whole point, since "switch the left side on" makes no sense without
// the reason.
SetupStepId.controllerClickV2KeepAwake => ChainStepText(
l.chainStepClickV2KeepAwake,
l.chainStepClickV2KeepAwakeHint,
),
SetupStepId.controllerSramSetup => step.done
? ChainStepText(l.chainStepSramSetup)
: ChainStepText(l.sramSetup, l.chainStepSramSetupHint),

2
prop

Submodule prop updated: 885acd22d4...cde67ebabe

View File

@@ -0,0 +1,83 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:bike_control/bluetooth/connection.dart';
import 'package:bike_control/bluetooth/devices/zwift/constants.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:universal_ble/universal_ble.dart';
BleDevice _advert({int? zwiftTypeByte, int companyId = ZwiftConstants.ZWIFT_MANUFACTURER_ID}) => BleDevice(
deviceId: 'puck',
name: 'Zwift Click',
manufacturerDataList: [
if (zwiftTypeByte != null) ManufacturerData(companyId, Uint8List.fromList([zwiftTypeByte])),
],
);
void main() {
group('left-puck identification', () {
test('recognises a left puck from its advert', () {
expect(Connection.isClickV2LeftSideAdvert(_advert(zwiftTypeByte: ZwiftConstants.CLICK_V2_LEFT_SIDE)), isTrue);
});
test('does not mistake the right puck for its sibling', () {
// The whole point is "is the *other* one here", so confusing the two
// would make a lone right puck believe it had company.
expect(Connection.isClickV2LeftSideAdvert(_advert(zwiftTypeByte: ZwiftConstants.CLICK_V2_RIGHT_SIDE)), isFalse);
});
test('ignores other Zwift controllers', () {
expect(Connection.isClickV2LeftSideAdvert(_advert(zwiftTypeByte: ZwiftConstants.BC1)), isFalse);
expect(Connection.isClickV2LeftSideAdvert(_advert(zwiftTypeByte: ZwiftConstants.RIDE_LEFT_SIDE)), isFalse);
expect(Connection.isClickV2LeftSideAdvert(_advert(zwiftTypeByte: ZwiftConstants.RC1_LEFT_SIDE)), isFalse);
});
test('ignores the same byte from another vendor', () {
expect(
Connection.isClickV2LeftSideAdvert(_advert(zwiftTypeByte: ZwiftConstants.CLICK_V2_LEFT_SIDE, companyId: 0x004C)),
isFalse,
);
});
test('survives adverts with no manufacturer data at all', () {
expect(Connection.isClickV2LeftSideAdvert(_advert()), isFalse);
expect(Connection.isClickV2LeftSideAdvert(BleDevice(deviceId: 'bare', name: null)), isFalse);
});
});
group('keep-awake strings', () {
const keys = [
'clickV2_keepAwakeNeedsLeftSide',
'chainStepClickV2KeepAwake',
'chainStepClickV2KeepAwakeHint',
];
const locales = ['en', 'de', 'fr', 'es', 'it', 'pl'];
test('are translated in every shipped language', () {
for (final locale in locales) {
final arb = jsonDecode(File('lib/i10n/intl_$locale.arb').readAsStringSync()) as Map<String, dynamic>;
for (final key in keys) {
expect(arb.containsKey(key), isTrue, reason: '$locale is missing $key');
expect(
(arb[key] as String).trim(),
isNotEmpty,
reason: '$locale has an empty $key',
);
}
}
});
test('are not left as untranslated copies of the English', () {
// A placeholder that was never translated is worse than a missing key:
// it passes the presence check and ships English to every rider.
final en = jsonDecode(File('lib/i10n/intl_en.arb').readAsStringSync()) as Map<String, dynamic>;
for (final locale in locales.where((l) => l != 'en')) {
final arb = jsonDecode(File('lib/i10n/intl_$locale.arb').readAsStringSync()) as Map<String, dynamic>;
for (final key in keys) {
expect(arb[key], isNot(en[key]), reason: '$locale still carries the English $key');
}
}
});
});
}

View File

@@ -25,16 +25,16 @@ void main() {
arbMaps[entry.key] = jsonDecode(content);
}
// Get the reference set from English (exactly 25 keys)
// Get the reference set from English (exactly 24 keys)
final enKeys = arbMaps['en']!
.keys
.where((k) => k.startsWith('clickV2Onboarding_'))
.toSet();
expect(
enKeys.length,
25,
24,
reason:
'English arb should have exactly 25 clickV2Onboarding_ keys, but has ${enKeys.length}',
'English arb should have exactly 24 clickV2Onboarding_ keys, but has ${enKeys.length}',
);
// Verify all other locales have the same key set
@@ -85,7 +85,6 @@ void main() {
l10n.clickV2Onboarding_rightOnlyPro1,
l10n.clickV2Onboarding_rightOnlyPro2,
l10n.clickV2Onboarding_rightOnlyCon1,
l10n.clickV2Onboarding_rightOnlyCon2,
l10n.clickV2Onboarding_rightOnlyCta,
l10n.clickV2Onboarding_zwiftTitle,
l10n.clickV2Onboarding_zwiftPro1,

View File

@@ -22,6 +22,7 @@ ControllerInput controller({
bool unlockUncertain = false,
bool? sramSetupDone,
bool needsUnlockModeChoice = false,
bool clickV2NeedsLeftSide = false,
}) {
return ControllerInput(
deviceId: deviceId,
@@ -34,6 +35,7 @@ ControllerInput controller({
unlockUncertain: unlockUncertain,
sramSetupDone: sramSetupDone,
needsUnlockModeChoice: needsUnlockModeChoice,
clickV2NeedsLeftSide: clickV2NeedsLeftSide,
);
}
@@ -231,6 +233,52 @@ void main() {
expect(link.steps.any((s) => s.id == SetupStepId.controllerSramSetup), isFalse);
});
test('offers the keep-awake step when a right puck has no left one in range', () {
final chain = buildChain(
ChainInputs(controllers: [controller(clickV2NeedsLeftSide: true)], app: _readyApp),
);
final link = chain.byKey(ChainLinkKey.controller);
final step = link.steps.firstWhere((s) => s.id == SetupStepId.controllerClickV2KeepAwake);
expect(step.optional, isTrue, reason: 'the controller works without it; it is an offer, not work');
expect(step.done, isFalse);
});
test('the keep-awake offer is absent once it is no longer outstanding', () {
// Emitted only while waiting, so it never sits ticked on the card forever.
final chain = buildChain(ChainInputs(controllers: [controller()], app: _readyApp));
final link = chain.byKey(ChainLinkKey.controller);
expect(_hasStep(link, SetupStepId.controllerClickV2KeepAwake), isFalse);
});
test('the keep-awake offer never colours the card or blocks riding', () {
// The regression this guards: the controller link used to count every
// undone step, optional or not, so this offer alone turned a working
// controller amber and held back "Ready to ride".
final chain = buildChain(
ChainInputs(
controllers: [controller(clickV2NeedsLeftSide: true)],
trainer: trainer(),
app: _readyApp,
),
);
final link = chain.byKey(ChainLinkKey.controller);
expect(link.status, LinkStatus.ready);
expect(link.steps.where((s) => !s.done && !s.optional), isEmpty);
});
test('a real outstanding step still outranks the optional offer', () {
// The optional step must not mask a genuine one sitting beside it.
final chain = buildChain(
ChainInputs(
controllers: [controller(hasMappedButtons: false, clickV2NeedsLeftSide: true)],
app: _readyApp,
),
);
final link = chain.byKey(ChainLinkKey.controller);
expect(link.status, LinkStatus.attention);
expect(link.activeStep?.id, SetupStepId.controllerButtonsMapped);
});
test('a controller with no unlock concept has no unlock step at all', () {
final chain = buildChain(ChainInputs(controllers: [controller()], app: _readyApp));
final link = chain.byKey(ChainLinkKey.controller);