From 9dece10e29db58d6691012ea5b981c3f861b5980 Mon Sep 17 00:00:00 2001 From: Yandrik Date: Tue, 24 Nov 2026 20:02:05 +0100 Subject: [PATCH] feat: basic trainer support --- README.md | 1 + assets/trainer_models.json | 1305 ++++++++++++++++++++++ docs/trainer-setup-and-simulation.md | 63 ++ lib/model/shifter_types.dart | 37 +- lib/model/simulation.dart | 183 +++ lib/model/trainer_model.dart | 94 ++ lib/pages/device_details_page.dart | 34 +- lib/pages/trainer_model_search_page.dart | 119 ++ lib/service/shifter_service.dart | 87 +- lib/widgets/bike_scan_dialog.dart | 225 +++- lib/widgets/simulation_card.dart | 553 +++++++++ pubspec.yaml | 1 + test/model/simulation_test.dart | 71 ++ test/service/shifter_settings_test.dart | 65 ++ test/support/settings_bluetooth.dart | 52 + test/trainer_ui_test.dart | 190 ++++ tool/import_trainer_catalog.py | 26 + 17 files changed, 3048 insertions(+), 58 deletions(-) create mode 100644 assets/trainer_models.json create mode 100644 docs/trainer-setup-and-simulation.md create mode 100644 lib/model/simulation.dart create mode 100644 lib/model/trainer_model.dart create mode 100644 lib/pages/trainer_model_search_page.dart create mode 100644 lib/widgets/simulation_card.dart create mode 100644 test/model/simulation_test.dart create mode 100644 test/service/shifter_settings_test.dart create mode 100644 test/support/settings_bluetooth.dart create mode 100644 test/trainer_ui_test.dart create mode 100644 tool/import_trainer_catalog.py diff --git a/README.md b/README.md index 2cf8d10..f889827 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ A new Flutter project. ## Operational Docs - [Bootloader OTA Operator Guide](docs/bootloader-ota-operator-guide.md) +- [Trainer setup and simulation](docs/trainer-setup-and-simulation.md) ## Getting Started diff --git a/assets/trainer_models.json b/assets/trainer_models.json new file mode 100644 index 0000000..e5c535e --- /dev/null +++ b/assets/trainer_models.json @@ -0,0 +1,1305 @@ +[ + { + "id": "ftms", + "name": "FTMS bike", + "family": "ftms", + "equipment": "Bike", + "manual": false, + "bundles": [ + "standard", + "legacy", + "ifit", + "vendor" + ] + }, + { + "id": "ftms-cross-trainer", + "name": "FTMS cross-trainer", + "family": "ftms", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard", + "legacy", + "ifit", + "vendor" + ] + }, + { + "id": "schwinn-ic4", + "name": "Schwinn IC4 / IC8", + "family": "ftms", + "equipment": "Bike", + "manual": false, + "bundles": [ + "standard", + "legacy", + "ifit", + "vendor" + ] + }, + { + "id": "yesoul", + "name": "Yesoul bike", + "family": "yesoul", + "equipment": "Bike", + "manual": false, + "bundles": [ + "standard" + ] + }, + { + "id": "cycling-sensors", + "name": "Cycling power / speed and cadence sensors", + "family": "sensors", + "equipment": "Bike", + "manual": true, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "tacx-fec", + "name": "Tacx Neo / Flux BLE FE-C", + "family": "tacx", + "equipment": "Bike", + "manual": false, + "bundles": [ + "standard" + ] + }, + { + "id": "elite-legacy", + "name": "Elite legacy trainer", + "family": "elite", + "equipment": "Bike", + "manual": false, + "bundles": [ + "standard" + ] + }, + { + "id": "elite-dr", + "name": "Elite DR trainer", + "family": "elite", + "equipment": "Bike", + "manual": false, + "bundles": [ + "standard" + ] + }, + { + "id": "elite-misuro", + "name": "Elite Misuro B+ (read-only)", + "family": "elite", + "equipment": "Bike", + "manual": false, + "bundles": [ + "standard" + ] + }, + { + "id": "wahoo-legacy", + "name": "Wahoo KICKR legacy", + "family": "wahoo", + "equipment": "Bike", + "manual": false, + "bundles": [ + "standard" + ] + }, + { + "id": "keiser-m3i", + "name": "Keiser M3i (broadcast)", + "family": "keiser", + "equipment": "Bike", + "manual": false, + "bundles": [ + "standard" + ] + }, + { + "id": "echelon", + "name": "Echelon Connect Sport", + "family": "echelon", + "equipment": "Bike", + "manual": false, + "bundles": [ + "standard" + ] + }, + { + "id": "domyos", + "name": "Domyos / Decathlon bike", + "family": "domyos", + "equipment": "Bike", + "manual": false, + "bundles": [ + "standard" + ] + }, + { + "id": "domyos-el", + "name": "Domyos / Decathlon elliptical", + "family": "domyos", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard" + ] + }, + { + "id": "fitplus-bike", + "name": "FitPlus bike", + "family": "fitplus", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "fitplus-etappe", + "name": "Virtufit Etappe", + "family": "fitplus", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "fitplus-merach", + "name": "Merach MRK", + "family": "fitplus", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "fitplus-h9110", + "name": "H9110 Osaka", + "family": "fitplus", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "fitplus-sx600", + "name": "Sportstech SX600", + "family": "fitplus", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "snode-bike", + "name": "S-Node FTMS bike", + "family": "fitplus", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-tc", + "name": "trx-bike-tc", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-tun", + "name": "Tunturi bike", + "family": "toorx", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-fhw", + "name": "FitHiWay", + "family": "toorx", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-vfit", + "name": "VirtuFit", + "family": "toorx", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-irun", + "name": "trx-bike-irun", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-adc1", + "name": "Adidas C1", + "family": "toorx", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-chy", + "name": "trx-bike-chy", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-icon", + "name": "trx-bike-icon", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-casall", + "name": "trx-bike-casall", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-reebok", + "name": "trx-bike-reebok", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-dkn", + "name": "trx-bike-dkn", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-fal", + "name": "trx-bike-fal", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-hertz", + "name": "trx-bike-hertz", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-enerfit", + "name": "trx-bike-enerfit", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-hammer", + "name": "trx-bike-hammer", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-jll", + "name": "trx-bike-jll", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-fytter", + "name": "trx-bike-fytter", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-asviva", + "name": "trx-bike-asviva", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-hop", + "name": "trx-bike-hop", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-srx500", + "name": "trx-bike-srx500", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-bike-taurua", + "name": "trx-bike-taurua", + "family": "toorx", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-ell", + "name": "FAL-SPORTS elliptical", + "family": "toorx", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-ell-toorx", + "name": "trx-ell-toorx", + "family": "toorx", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "trx-ell-dct", + "name": "trx-ell-dct", + "family": "toorx", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "ifit-bike", + "name": "iFit bike", + "family": "ifit", + "equipment": "Bike", + "manual": false, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-freestride", + "name": "iFit FreeStride", + "family": "ifit", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-elliptical", + "name": "iFit elliptical", + "family": "ifit", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-el-trainer", + "name": "iFit elliptical trainer", + "family": "ifit", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-1", + "name": "proformbike", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-2", + "name": "freemotion coachbike b22 7", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-3", + "name": "nordictrack GX4 5 bike", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-4", + "name": "nordictrack gx 2 7", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-5", + "name": "nordictrack gx 44 pro", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-6", + "name": "nordictrack gx 4 5 pro", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-7", + "name": "nordictrack vr21", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-8", + "name": "proform 225 csx PFEX32925 INT 0", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-9", + "name": "proform bike 225 csx", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-10", + "name": "proform bike 325 csx", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-11", + "name": "proform bike 325 csx PFEX439210INT 0", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-12", + "name": "proform bike PFEVEX71316 0", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-13", + "name": "proform bike PFEVEX71316 1", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-14", + "name": "proform bike sb", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-15", + "name": "proform csx210", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-16", + "name": "proform cycle trainer 300 ci", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-17", + "name": "proform cycle trainer 400", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-18", + "name": "proform hybrid trainer PFEL03815", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-19", + "name": "proform studio", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-20", + "name": "proform studio NTEX71021", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-21", + "name": "proform tdf 10", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-22", + "name": "proform tour de france clc", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-23", + "name": "proform xbike", + "family": "ifit", + "equipment": "Bike", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-84", + "name": "proformelliptical", + "family": "ifit", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-85", + "name": "nordictrackelliptical", + "family": "ifit", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-86", + "name": "nordictrack elliptical c7 5", + "family": "ifit", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-87", + "name": "proform hybrid trainer xt", + "family": "ifit", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-88", + "name": "proformellipticaltrainer", + "family": "ifit", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-89", + "name": "nordictrack se7i", + "family": "ifit", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "ifit-model-90", + "name": "nordictrack elliptical s700", + "family": "ifit", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "ifit" + ] + }, + { + "id": "sportstech-bike", + "name": "Sportstech bike", + "family": "sportsplus", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "sportstech-ellip", + "name": "Sportstech elliptical", + "family": "sportsplus", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "sportsplus-bike", + "name": "SportsPlus bike", + "family": "sportsplus", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "sportsplus-ht", + "name": "SportsPlus HT", + "family": "sportsplus", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "carefit-bike", + "name": "Carefitness bike", + "family": "sportsplus", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "sp-ht-9600ie", + "name": "SportsPlus HT-9600iE", + "family": "sportsplus", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "pafers-bike", + "name": "Pafers bike", + "family": "sportsplus", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "nautilus-bike", + "name": "Nautilus bike (B628)", + "family": "nautilus", + "equipment": "Bike", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "nautilus-ellip", + "name": "Nautilus elliptical (E616/E618)", + "family": "nautilus", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "nautilus-m7", + "name": "Nautilus M7 elliptical", + "family": "nautilus", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "legacy" + ] + }, + { + "id": "nautilus-el-v2", + "name": "Nautilus elliptical (7df7a3f7 service)", + "family": "nautilus", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "nautilus-b616-mi", + "name": "Nautilus B616 bike (mph console)", + "family": "nautilus", + "equipment": "Bike", + "manual": true, + "bundles": [ + "legacy" + ] + }, + { + "id": "flywheel", + "name": "Flywheel bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "lifefit-ic5", + "name": "Life Fitness IC5", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": true, + "bundles": [ + "vendor" + ] + }, + { + "id": "sole-bike", + "name": "Sole LCB/LCR", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "sole-r92", + "name": "Sole R92", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "kettler-c12", + "name": "Kettler C12", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "technogym", + "name": "Technogym MyCycling", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "inspire", + "name": "Inspire IC", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "keep-bike", + "name": "Keep bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "mcf-bike", + "name": "MCF bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "volava", + "name": "Volava bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "ultrasport", + "name": "Ultrasport X-bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "skandika-wiri", + "name": "Skandika Wiri", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "skandika-x2000", + "name": "Skandika X2000", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "pitpat-bike", + "name": "PitPat bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "freebeat-boom", + "name": "Freebeat Boom", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "apex-bike", + "name": "Apex bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "npe-cable", + "name": "NPE CABLE bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "cycleops", + "name": "CycleOps Phantom / Magnus", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "csc-bike", + "name": "Joroto / BGYM CSC bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "lifespan-bike", + "name": "LifeSpan bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": true, + "bundles": [ + "vendor" + ] + }, + { + "id": "xcx-bike", + "name": "XCX bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "chrono-bike", + "name": "Chrono bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "mepanel", + "name": "MEPANEL bike", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "renpho", + "name": "Renpho bike (FTMS)", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "horizon-gr7", + "name": "Horizon GR7 bike (FTMS)", + "family": "vendor-bikes", + "equipment": "Bike", + "manual": false, + "bundles": [ + "vendor" + ] + }, + { + "id": "bh-elliptical", + "name": "BH Fitness elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "ypoo-u3", + "name": "YPOO U3 / Merach elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "ypoo-ftms-el", + "name": "YPOO FTMS elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "ypoo-sch411", + "name": "Schwinn 411/510E elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "ypoo-feier", + "name": "FEIER elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "ypoo-sole-e25", + "name": "Sole E25 FTMS elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "ypoo-true-el", + "name": "TRUE elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "ypoo-iconsole", + "name": "iConsole elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "gymstick-gx60", + "name": "Gymstick GX6.0 elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "sole-elliptical", + "name": "Sole elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "xterra-xe88", + "name": "Xterra XE88 elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "sole-e55", + "name": "Sole E55 elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": true, + "bundles": [ + "standard", + "vendor" + ] + }, + { + "id": "octane-q37", + "name": "Octane Q37 elliptical", + "family": "vendor-cross-trainers", + "equipment": "CrossTrainer", + "manual": false, + "bundles": [ + "standard", + "vendor" + ] + } +] diff --git a/docs/trainer-setup-and-simulation.md b/docs/trainer-setup-and-simulation.md new file mode 100644 index 0000000..abcd623 --- /dev/null +++ b/docs/trainer-setup-and-simulation.md @@ -0,0 +1,63 @@ +# Trainer setup and simulation + +The app can assign FTMS and proprietary trainers through Universal Shifters. +Scanning uses the button's radio, not a separate phone scan. + +## Trainer assignment + +- Supported trainers only includes FTMS advertisements and the firmware's + recognized-protocol flag (`0x10`). Non-connectable broadcast trainers remain + selectable, including Keiser. +- Turn the filter off to choose a device requiring manual profile selection. +- Find trainer model searches the offline model catalog by model, brand, family + and stable profile ID. A catalog entry does not prove support in the installed + firmware or hardware-tested interoperability. +- Automatic detection and manual profile selection are confirmed by read-back + before writing the trainer address and connect command. +- Old firmware can still connect without the optional selection characteristic. + Manual selection requires firmware exposing that characteristic. +- A profile rejected by the installed firmware never proceeds to connecting. + The app explains the firmware requirement. There are no automatic firmware + downloads or bundle changes in this implementation. + +Refresh the bundled catalog after reviewing firmware registry changes: + +```sh +python3 tool/import_trainer_catalog.py ../kettler2ant-rs +``` + +The importer uses `universal-shifters/trainer-build-matrix.md`. Configured-only +profiles are excluded. It intentionally requires review if the profile count +changes. Control descriptions in `lib/model/trainer_model.dart` also need review +when protocol capabilities change. + +## Simulation + +The optional version-1 simulation characteristics supply configuration, a model +catalog and runtime status. Older firmware shows an unavailable message and retry +instead of exposing writable settings that cannot be saved. + +- Defaults match firmware: Auto, FE-C model, 75 kg rider, 10 kg bike, multipliers 1. +- ANT+ weights override configured mass until the trainer session ends. They do + not overwrite the app's saved configuration fields. +- Save changes writes all 14 bytes, then requires identical read-back. +- Advanced settings start collapsed. Preview changes are local until saved. +- Graphs use percent gradient. The first covers 0 to 50 km/h at 0%. + The second covers -5% to +5% at 15 km/h. +- Preview equations mirror `biketrainer-sim-mode/src/model.rs` at ratio 1, + Crr 0.004, Cw 0.51, no headwind, drafting multiplier 1 and a zero-watt floor. + Trainer power bounds and effective ANT+ weights are not exposed by the current + API and cannot be included. Native trainer response is not predicted. +- Future model IDs can be displayed and preserved, but unknown equations are not + invented for their previews. +- Target power in runtime status is commanded emulation power, not measured + rider power. Stale speed and trainer faults have separate messages. + +## Before release + +Validate Android and iOS BLE behavior with actual older and newer firmware, +including bonding, a proprietary trainer, a broadcast trainer, profile rejection, +simulation notifications, disconnect/reconnect, ANT+ weight precedence and DFU. +Confirm the exact factory-shipped firmware support list before publishing claims +about shipped units. Board identity and bundle capabilities cannot currently be +reliably inferred from the firmware version string. diff --git a/lib/model/shifter_types.dart b/lib/model/shifter_types.dart index fc3f25a..33e0e67 100644 --- a/lib/model/shifter_types.dart +++ b/lib/model/shifter_types.dart @@ -21,6 +21,14 @@ const String universalShifterDfuDataCharacteristicUuid = const String universalShifterDfuStatusCharacteristicUuid = '0993826f-0ee4-4b37-9614-d13ecba4000a'; const String ftmsServiceUuid = '00001826-0000-1000-8000-00805f9b34fb'; +const String trainerProtocolCharacteristicUuid = + '0993826f-0ee4-4b37-9614-d13ecba4000c'; +const String simulationConfigCharacteristicUuid = + '0993826f-0ee4-4b37-9614-d13ecba4000d'; +const String simulationModelsCharacteristicUuid = + '0993826f-0ee4-4b37-9614-d13ecba4000e'; +const String simulationStatusCharacteristicUuid = + '0993826f-0ee4-4b37-9614-d13ecba4000f'; const String batteryServiceUuid = '0000180f-0000-1000-8000-00805f9b34fb'; const String batteryLevelCharacteristicUuid = '00002a19-0000-1000-8000-00805f9b34fb'; @@ -65,6 +73,8 @@ const int errorFtmsMissing = 2; const int errorPairingAuth = 3; const int errorPairingEncrypt = 4; const int errorFtmsRequiredCharMissing = 5; +const int errorTrainerTimeout = 6; +const int errorTrainerProtocol = 7; const int trainerScanProtocolVersion = 1; @@ -72,6 +82,7 @@ const int trainerScanDeviceFlagFtmsDetected = 0x01; const int trainerScanDeviceFlagNameComplete = 0x02; const int trainerScanDeviceFlagScanResponseSeen = 0x04; const int trainerScanDeviceFlagConnectable = 0x08; +const int trainerScanDeviceFlagSupported = 0x10; enum DfuUpdateState { idle, @@ -220,9 +231,9 @@ ShifterErrorInfo shifterErrorInfo(int code) { case errorFtmsMissing: return const ShifterErrorInfo( code: errorFtmsMissing, - title: 'FTMS service missing', + title: 'Trainer not detected', details: - 'The selected bike does not expose the FTMS service (UUID 0x1826), so pairing cannot continue.', + 'No compatible trainer service was found. Check the selected model and installed firmware.', ); case errorPairingAuth: return const ShifterErrorInfo( @@ -241,10 +252,22 @@ ShifterErrorInfo shifterErrorInfo(int code) { case errorFtmsRequiredCharMissing: return const ShifterErrorInfo( code: errorFtmsRequiredCharMissing, - title: 'Required FTMS characteristic missing', + title: 'Trainer setup failed', details: - 'The bike has FTMS but is missing required characteristics (for example Indoor Bike Data), so control cannot start.', + 'The trainer is missing required data or control features. Check the selected model and disconnect other training apps.', ); + case errorTrainerTimeout: + return const ShifterErrorInfo( + code: errorTrainerTimeout, + title: 'Trainer timed out', + details: + 'The trainer did not respond during setup. Wake it up, move closer, and try again.'); + case errorTrainerProtocol: + return const ShifterErrorInfo( + code: errorTrainerProtocol, + title: 'Protocol unavailable', + details: + 'The selected model is not supported by the installed firmware. Choose Automatic detection or install compatible firmware.'); default: return ShifterErrorInfo( code: code, @@ -336,6 +359,8 @@ class TrainerScanResult { final String name; bool get ftmsDetected => (flags & trainerScanDeviceFlagFtmsDetected) != 0; + bool get supported => + ftmsDetected || (flags & trainerScanDeviceFlagSupported) != 0; bool get nameComplete => (flags & trainerScanDeviceFlagNameComplete) != 0; bool get scanResponseSeen => (flags & trainerScanDeviceFlagScanResponseSeen) != 0; @@ -498,9 +523,9 @@ class TrainerStatus { case TrainerConnectionState.connected: return 'Connected'; case TrainerConnectionState.discoveringFtms: - return 'Discovering FTMS'; + return 'Detecting trainer'; case TrainerConnectionState.ftmsReady: - return 'FTMS Ready'; + return 'Trainer ready'; case TrainerConnectionState.error: return 'Error${errorCode != null ? ' ($errorCode)' : ''}'; } diff --git a/lib/model/simulation.dart b/lib/model/simulation.dart new file mode 100644 index 0000000..9a9fb7f --- /dev/null +++ b/lib/model/simulation.dart @@ -0,0 +1,183 @@ +import 'dart:convert'; +import 'dart:math' as math; +import 'dart:typed_data'; + +enum SimulationPolicy { + auto('Auto'), + force('Force emulation'), + native('Native only'); + + const SimulationPolicy(this.label); + final String label; +} + +class SimulationConfig { + const SimulationConfig({ + this.policy = SimulationPolicy.auto, + this.modelId = 1, + this.riderWeight = 75, + this.bikeWeight = 10, + this.gradeMultiplier = 1, + this.rollingMultiplier = 1, + this.windMultiplier = 1, + }); + + final SimulationPolicy policy; + final int modelId; + final double riderWeight; + final double bikeWeight; + final double gradeMultiplier; + final double rollingMultiplier; + final double windMultiplier; + + SimulationConfig copyWith( + {SimulationPolicy? policy, + int? modelId, + double? riderWeight, + double? bikeWeight, + double? gradeMultiplier, + double? rollingMultiplier, + double? windMultiplier}) => + SimulationConfig( + policy: policy ?? this.policy, + modelId: modelId ?? this.modelId, + riderWeight: riderWeight ?? this.riderWeight, + bikeWeight: bikeWeight ?? this.bikeWeight, + gradeMultiplier: gradeMultiplier ?? this.gradeMultiplier, + rollingMultiplier: rollingMultiplier ?? this.rollingMultiplier, + windMultiplier: windMultiplier ?? this.windMultiplier); + + List encode() { + final values = [ + riderWeight, + bikeWeight, + gradeMultiplier, + rollingMultiplier, + windMultiplier + ]; + final limits = [300.0, 100.0, 3.0, 3.0, 3.0]; + for (var i = 0; i < values.length; i++) { + if (!values[i].isFinite || + values[i] < (i == 0 ? 1 : 0) || + values[i] > limits[i]) { + throw const FormatException('Simulation setting is out of range.'); + } + } + if (modelId < 1 || modelId > 255) { + throw const FormatException('Invalid simulation model.'); + } + final data = ByteData(14); + data.setUint8(0, 1); + data.setUint8(1, policy.index); + data.setUint8(2, modelId); + for (var i = 0; i < values.length; i++) { + data.setUint16( + 4 + i * 2, (values[i] * (i < 2 ? 100 : 1000)).round(), Endian.little); + } + return data.buffer.asUint8List(); + } + + static SimulationConfig decode(List bytes) { + if (bytes.any((byte) => byte < 0 || byte > 255) || + bytes.length != 14 || + bytes[0] != 1 || + bytes[1] > 2 || + bytes[2] == 0 || + bytes[3] != 0) { + throw const FormatException('Unsupported simulation configuration.'); + } + final data = ByteData.sublistView(Uint8List.fromList(bytes)); + final config = SimulationConfig( + policy: SimulationPolicy.values[bytes[1]], + modelId: bytes[2], + riderWeight: data.getUint16(4, Endian.little) / 100, + bikeWeight: data.getUint16(6, Endian.little) / 100, + gradeMultiplier: data.getUint16(8, Endian.little) / 1000, + rollingMultiplier: data.getUint16(10, Endian.little) / 1000, + windMultiplier: data.getUint16(12, Endian.little) / 1000); + config.encode(); + return config; + } + + /// Mirrors biketrainer-sim-mode::model at ratio 1, default Crr/Cw, + /// no headwind or drafting. This is not native trainer power prediction. + double previewWatts(double speedKmh, double gradePercent) { + if (modelId != 1 && modelId != 2) { + throw const FormatException('Preview unavailable for this model.'); + } + final v = speedKmh / 3.6; + if (!v.isFinite || v <= 0) return 0; + final mass = riderWeight + bikeWeight; + final force = mass * + (gradePercent / 100 * 9.81 * gradeMultiplier + + 0.004 * 9.8 * rollingMultiplier) + + (modelId == 2 ? 0 : 0.5 * 0.51 * windMultiplier * v * v); + return math.max(0, force) * v; + } +} + +Map decodeSimulationModels(List bytes) { + final result = {}; + for (final entry in utf8.decode(bytes).split(';')) { + final parts = entry.split(':'); + final id = parts.length == 2 ? int.tryParse(parts[0]) : null; + if (id == null || + id < 1 || + id > 255 || + parts[1].isEmpty || + result.containsKey(id)) { + throw const FormatException('Invalid simulation model catalog.'); + } + result[id] = parts[1]; + } + return result; +} + +enum SimulationMode { inactive, native, emulated, fault } + +class SimulationStatus { + const SimulationStatus(this.mode, this.speedFresh, this.error, this.watts); + final SimulationMode mode; + final bool speedFresh; + final int error; + final int? watts; + + static SimulationStatus decode(List bytes) { + if (bytes.any((byte) => byte < 0 || byte > 255) || + bytes.length != 6 || + bytes[0] != 1 || + bytes[1] > 3) { + throw const FormatException('Unsupported simulation status.'); + } + final watts = bytes[4] | bytes[5] << 8; + return SimulationStatus(SimulationMode.values[bytes[1]], bytes[2] & 1 != 0, + bytes[3], watts == 0xffff ? null : watts); + } + + String get label => switch (mode) { + SimulationMode.inactive => 'Inactive', + SimulationMode.native => 'Native simulation', + SimulationMode.emulated => 'Emulated simulation', + SimulationMode.fault => 'Simulation fault', + }; + + String? get details { + if (mode == SimulationMode.fault) { + return switch (error) { + 2 => + 'The trainer does not support the requested control. Check the simulation mode.', + 3 => 'The trainer rejected the target value. Check your settings.', + 4 => + 'The trainer could not apply the target power. Reconnect and try again.', + 5 => 'Trainer control was denied. Disconnect other apps and try again.', + _ => + 'Simulation stopped after a trainer error ($error). Reconnect and try again.', + }; + } + if (mode != SimulationMode.emulated) return null; + if (!speedFresh) return 'Waiting for trainer speed'; + return watts == null + ? 'Waiting for target power' + : 'Target power: $watts W'; + } +} diff --git a/lib/model/trainer_model.dart b/lib/model/trainer_model.dart new file mode 100644 index 0000000..18c00c7 --- /dev/null +++ b/lib/model/trainer_model.dart @@ -0,0 +1,94 @@ +import 'dart:convert'; +import 'package:flutter/services.dart'; + +class TrainerModel { + const TrainerModel( + {required this.id, + required this.name, + required this.family, + required this.bundles, + required this.manual}); + final String id; + final String name; + final String family; + final List bundles; + final bool manual; + + static Future> load() async { + final data = + jsonDecode(await rootBundle.loadString('assets/trainer_models.json')) + as List; + return data + .map((entry) => TrainerModel( + id: entry['id'] as String, + name: entry['name'] as String, + family: entry['family'] as String, + bundles: List.from(entry['bundles'] as List), + manual: entry['manual'] as bool)) + .toList(); + } + + bool matches(String query) { + final text = + '$name $family $id ${family == 'ifit' ? 'ProForm NordicTrack' : ''}' + .toLowerCase(); + return query + .toLowerCase() + .trim() + .split(RegExp(r'\s+')) + .every(text.contains); + } + + String get limitations { + if ([ + 'schwinn-ic4', + 'yesoul', + 'cycling-sensors', + 'elite-misuro', + 'keiser-m3i', + 'ifit-freestride', + 'flywheel', + 'lifefit-ic5', + 'sole-bike', + 'sole-r92', + 'kettler-c12', + 'inspire', + 'keep-bike', + 'mcf-bike', + 'volava', + 'ultrasport', + 'apex-bike', + 'npe-cable', + 'csc-bike', + 'lifespan-bike', + 'xcx-bike', + 'chrono-bike', + 'mepanel', + 'octane-q37', + 'fitplus-bike', + 'snode-bike' + ].contains(id) || + family == 'nautilus') { + return 'Data only'; + } + if (family == 'ftms' || id == 'renpho' || id == 'horizon-gr7') { + return 'Controls depend on trainer features'; + } + if (['tacx', 'elite', 'wahoo'].contains(family)) { + return 'Power control. Simulation support varies'; + } + if (id == 'cycleops') return 'Power control'; + if (id == 'technogym') return 'Power and resistance control'; + return 'Resistance control. Features vary by model'; + } + + String get bundleLabel => bundles + .map((b) => switch (b) { + 'standard' => 'Standard', + 'legacy' => 'Legacy fitness equipment', + 'ifit' => 'iFit / ProForm / NordicTrack', + 'vendor' => 'Vendor bikes / ellipticals', + _ => b, + }) + .join(', '); +} diff --git a/lib/pages/device_details_page.dart b/lib/pages/device_details_page.dart index c02bef5..791954d 100644 --- a/lib/pages/device_details_page.dart +++ b/lib/pages/device_details_page.dart @@ -10,6 +10,7 @@ import 'package:abawo_bt_app/util/bluetooth_settings.dart'; import 'package:abawo_bt_app/widgets/bike_scan_dialog.dart'; import 'package:abawo_bt_app/widgets/firmware_update_fullscreen.dart'; import 'package:abawo_bt_app/widgets/gear_ratio_editor_card.dart'; +import 'package:abawo_bt_app/widgets/simulation_card.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; @@ -494,27 +495,43 @@ class _DeviceDetailsPageState extends ConsumerState { } _isAssignTrainerDialogOpen = true; - final TrainerScanResult? selectedTrainer; + final TrainerAssignment? assignment; try { - selectedTrainer = await BikeScanDialog.show( + assignment = await BikeScanDialog.show( context, shifter: shifter, ); } finally { _isAssignTrainerDialogOpen = false; } - if (selectedTrainer == null || !mounted) { + if (assignment == null || !mounted) { return; } + final selectedTrainer = assignment.trainer; - final result = - await shifter.connectButtonToTrainer(selectedTrainer.address); + final result = await shifter.connectButtonToTrainer(selectedTrainer.address, + protocol: assignment.protocol); if (!mounted) { return; } if (result.isErr()) { final err = result.unwrapErr(); + if (err.toString().contains('Firmware update required')) { + await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Firmware update required'), + content: const Text( + 'This trainer model is not available in the installed firmware. Choose Automatic detection if your trainer supports FTMS, or contact abawo support for compatible firmware. Automatic firmware downloads are not available yet.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close')) + ], + )); + return; + } ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Connect request failed: $err')), ); @@ -1124,6 +1141,13 @@ class _DeviceDetailsPageState extends ConsumerState { ), ], ), + const SizedBox(height: 16), + if (_shifterService != null) + SimulationCard( + key: ObjectKey(_shifterService), + shifter: _shifterService!, + enabled: !_isFirmwareUpdateBusy, + ), ] else if (isCurrentConnected) ...[ _PairingRequiredCard( isChecking: _isPairingCheckRunning, diff --git a/lib/pages/trainer_model_search_page.dart b/lib/pages/trainer_model_search_page.dart new file mode 100644 index 0000000..ff0b415 --- /dev/null +++ b/lib/pages/trainer_model_search_page.dart @@ -0,0 +1,119 @@ +import 'package:abawo_bt_app/model/trainer_model.dart'; +import 'package:flutter/material.dart'; + +class TrainerModelSearchPage extends StatefulWidget { + const TrainerModelSearchPage({super.key, this.canSelect = true, this.models}); + final bool canSelect; + final Future>? models; + + @override + State createState() => _TrainerModelSearchPageState(); +} + +class _TrainerModelSearchPageState extends State { + late Future> _models = + widget.models ?? TrainerModel.load(); + String _query = ''; + + Future _select(TrainerModel model) async { + final selected = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(model.name), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(model.limitations), + const SizedBox(height: 12), + Text('Compatible firmware: ${model.bundleLabel}'), + const SizedBox(height: 12), + const Text( + 'Your installed firmware must include this model. FTMS versions of this trainer may also work with Automatic detection.'), + const SizedBox(height: 12), + const Text( + 'Support depends on the exact model and firmware revision. Not every listed model has been tested on hardware.'), + if (!widget.canSelect) ...[ + const SizedBox(height: 12), + const Text('Firmware update required', + style: TextStyle(fontWeight: FontWeight.w600)), + const SizedBox(height: 6), + const Text( + 'Model selection requires newer firmware. Automatic firmware downloads are not available yet. Contact abawo support for compatible firmware.'), + ], + ])), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Back')), + if (widget.canSelect) + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('Find nearby trainer')), + ], + )); + if (selected == true && mounted) Navigator.pop(context, model); + } + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('Find trainer model')), + body: SafeArea( + child: Column(children: [ + Padding( + padding: const EdgeInsets.all(18), + child: TextField( + autofocus: true, + decoration: const InputDecoration( + labelText: 'Search brand or model', + prefixIcon: Icon(Icons.search), + hintText: 'For example, Kettler C12'), + onChanged: (value) => setState(() => _query = value), + )), + Expanded( + child: FutureBuilder>( + future: _models, + builder: (context, snapshot) { + if (snapshot.hasError) { + return Center( + child: TextButton( + onPressed: () => + setState(() => _models = TrainerModel.load()), + child: + const Text('Could not load models. Retry'))); + } + if (!snapshot.hasData) { + return const Center(child: CircularProgressIndicator()); + } + final models = snapshot.data! + .where((model) => model.matches(_query)) + .toList(); + if (models.isEmpty) { + return const Center( + child: Padding( + padding: EdgeInsets.all(24), + child: Text( + 'No matching model found. Try the brand name or check whether your trainer supports FTMS.'))); + } + return ListView.separated( + padding: const EdgeInsets.fromLTRB(18, 0, 18, 18), + itemCount: models.length, + separatorBuilder: (_, __) => const SizedBox(height: 10), + itemBuilder: (context, index) { + final model = models[index]; + return Card( + child: ListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 18, vertical: 8), + title: Text(model.name), + subtitle: + Text('${model.limitations}\n${model.id}'), + isThreeLine: true, + trailing: const Icon(Icons.chevron_right), + onTap: () => _select(model))); + }); + })), + ])), + ); +} diff --git a/lib/service/shifter_service.dart b/lib/service/shifter_service.dart index 78d133d..ad44329 100644 --- a/lib/service/shifter_service.dart +++ b/lib/service/shifter_service.dart @@ -1,8 +1,10 @@ import 'dart:async'; +import 'dart:convert'; import 'package:abawo_bt_app/controller/bluetooth.dart'; import 'package:abawo_bt_app/model/gear_ratio_codec.dart'; import 'package:abawo_bt_app/model/shifter_types.dart'; +import 'package:abawo_bt_app/model/simulation.dart'; import 'package:anyhow/anyhow.dart'; import 'package:logging/logging.dart'; @@ -77,9 +79,12 @@ class ShifterService { ); } - Future> connectButtonToTrainer( - TrainerAddress trainerAddress, - ) async { + Future> connectButtonToTrainer(TrainerAddress trainerAddress, + {String? protocol}) async { + if (protocol != null) { + final selection = await writeTrainerProtocol(protocol); + if (selection.isErr()) return selection; + } final addrRes = await writeConnectToTrainerAddress(trainerAddress); if (addrRes.isErr()) { return addrRes; @@ -87,6 +92,82 @@ class ShifterService { return writeCommand(UniversalShifterCommand.connectToDevice); } + Future>> readSetting(String uuid) => + _requireBluetooth.readCharacteristic( + buttonDeviceId, universalShifterControlServiceUuid, uuid); + + Future> readTrainerProtocol() async { + final result = await readSetting(trainerProtocolCharacteristicUuid); + if (result.isErr()) return Err(result.unwrapErr()); + try { + final value = utf8.decode(result.unwrap()); + return Ok(value.isEmpty ? 'auto' : value); + } catch (e) { + return bail('Could not read trainer protocol: $e'); + } + } + + Future> writeTrainerProtocol(String protocol) async { + final bytes = utf8.encode(protocol); + if (bytes.isEmpty || bytes.length > 32) { + return bail('Invalid trainer protocol.'); + } + final write = await _requireBluetooth.writeCharacteristic( + buttonDeviceId, + universalShifterControlServiceUuid, + trainerProtocolCharacteristicUuid, + bytes); + if (write.isErr()) return write; + final read = await readTrainerProtocol(); + if (read.isErr()) return Err(read.unwrapErr()); + if (read.unwrap() != protocol) { + return bail( + 'Firmware update required. This model is not available in the installed firmware. Choose Automatic detection or install compatible firmware.'); + } + return const Ok(null); + } + + Future> readSimulationConfig() async { + final result = await readSetting(simulationConfigCharacteristicUuid); + if (result.isErr()) return Err(result.unwrapErr()); + try { + return Ok(SimulationConfig.decode(result.unwrap())); + } catch (e) { + return bail('Could not decode simulation settings: $e'); + } + } + + Future> writeSimulationConfig(SimulationConfig config) async { + try { + final bytes = config.encode(); + final write = await _requireBluetooth.writeCharacteristic( + buttonDeviceId, + universalShifterControlServiceUuid, + simulationConfigCharacteristicUuid, + bytes); + if (write.isErr()) return write; + final read = await readSetting(simulationConfigCharacteristicUuid); + if (read.isErr()) return Err(read.unwrapErr()); + final actual = read.unwrap(); + if (actual.length != bytes.length || + List.generate(bytes.length, (i) => i) + .any((i) => actual[i] != bytes[i])) { + return bail( + 'The button did not accept the simulation settings. Read them again and retry.'); + } + return const Ok(null); + } catch (e) { + return bail('Could not save simulation settings: $e'); + } + } + + Stream subscribeToSimulationStatus() => _requireBluetooth + .subscribeToCharacteristic( + buttonDeviceId, + universalShifterControlServiceUuid, + simulationStatusCharacteristicUuid) + .map(SimulationStatus.decode); + Future> readGearRatios() async { final readRes = await _requireBluetooth.readCharacteristic( buttonDeviceId, diff --git a/lib/widgets/bike_scan_dialog.dart b/lib/widgets/bike_scan_dialog.dart index 1446a22..328a074 100644 --- a/lib/widgets/bike_scan_dialog.dart +++ b/lib/widgets/bike_scan_dialog.dart @@ -1,9 +1,17 @@ import 'dart:async'; import 'package:abawo_bt_app/model/shifter_types.dart'; +import 'package:abawo_bt_app/model/trainer_model.dart'; +import 'package:abawo_bt_app/pages/trainer_model_search_page.dart'; import 'package:abawo_bt_app/service/shifter_service.dart'; import 'package:flutter/material.dart'; +class TrainerAssignment { + const TrainerAssignment(this.trainer, this.protocol); + final TrainerScanResult trainer; + final String? protocol; +} + class BikeScanDialog extends StatefulWidget { const BikeScanDialog({ required this.shifter, @@ -12,11 +20,11 @@ class BikeScanDialog extends StatefulWidget { final ShifterService shifter; - static Future show( + static Future show( BuildContext context, { required ShifterService shifter, }) { - return showDialog( + return showDialog( context: context, barrierDismissible: true, builder: (_) => BikeScanDialog(shifter: shifter), @@ -34,18 +42,88 @@ class _BikeScanDialogState extends State { String? _scanError; final Map _resultsByAddress = {}; StreamSubscription? _scanSubscription; + bool _protocolLoading = true; + bool _hasProtocolSelection = false; + String _protocol = 'auto'; + String? _modelName; @override void initState() { super.initState(); unawaited(_startScan()); + unawaited(_loadProtocol()); + } + + Future _loadProtocol() async { + final result = await widget.shifter.readTrainerProtocol(); + if (!mounted) return; + setState(() { + _protocolLoading = false; + _hasProtocolSelection = result.isOk(); + if (result.isOk()) _protocol = result.unwrap(); + }); + } + + Future _chooseModel() async { + // Keep phone navigation separate from the button's scan session. + if (_isScanning) await widget.shifter.stopTrainerScan(); + if (!mounted) return; + final model = await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => + TrainerModelSearchPage(canSelect: _hasProtocolSelection))); + if (!mounted) return; + if (model != null) { + setState(() { + _protocol = model.id; + _modelName = model.name; + _showOnlyFtms = false; + }); + } + await _startScan(); + } + + Future _missingTrainer() async { + final search = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text("I can't find my trainer"), + content: const SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Wake up your trainer and keep it close to your Universal Shifters. Disconnect other training apps, then scan again.'), + SizedBox(height: 12), + Text( + 'You may need compatible firmware to connect your trainer with your Universal Shifters.'), + SizedBox(height: 12), + Text( + 'Standard firmware supports FTMS trainers and selected Yesoul, Keiser, Tacx, Elite, Wahoo, Echelon, Domyos and elliptical models. Older shipped firmware may support FTMS only.'), + SizedBox(height: 12), + Text( + 'For other trainers, search for the exact model to check the required firmware and start a connection.'), + ])), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Back')), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('Find trainer model')), + ], + )); + if (search == true && mounted) await _chooseModel(); } Future _startScan() async { await _scanSubscription?.cancel(); + if (!mounted) return; if (_isScanning) { await widget.shifter.stopTrainerScan(); } + if (!mounted) return; setState(() { _isStartingScan = true; @@ -70,6 +148,10 @@ class _BikeScanDialogState extends State { ); final startResult = await widget.shifter.startTrainerScan(); + if (!mounted) { + if (startResult.isOk()) await widget.shifter.stopTrainerScan(); + return; + } if (startResult.isErr()) { _scanError = startResult.unwrapErr().toString(); } else { @@ -136,17 +218,51 @@ class _BikeScanDialogState extends State { height: dialogHeight, child: Column( children: [ - _DialogHeader( - showOnlyFtms: _showOnlyFtms, - isScanning: _isStartingScan || _isScanning, - onChanged: (value) { - setState(() { - _showOnlyFtms = value; - }); - }, - onRescan: _startScan, - ), - Expanded(child: _buildBody(context)), + Expanded( + child: CustomScrollView(slivers: [ + SliverToBoxAdapter( + child: _DialogHeader( + showOnlyFtms: _showOnlyFtms, + isScanning: _isStartingScan || _isScanning, + onChanged: (value) { + setState(() { + _showOnlyFtms = value; + }); + }, + onRescan: _startScan, + )), + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: Column(children: [ + ListTile( + contentPadding: EdgeInsets.zero, + title: Text(_protocol == 'auto' + ? 'Automatic detection' + : _modelName ?? _protocol), + subtitle: Text(_protocolLoading + ? 'Reading trainer selection' + : 'Trainer model'), + trailing: const Icon(Icons.search), + onTap: _protocolLoading ? null : _chooseModel), + if (_protocol != 'auto' && _hasProtocolSelection) + Align( + alignment: Alignment.centerLeft, + child: TextButton( + onPressed: () => setState(() { + _protocol = 'auto'; + _modelName = null; + }), + child: + const Text('Use Automatic detection'))), + ]))), + _buildBody(context), + ])), + Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), + child: TextButton( + onPressed: _missingTrainer, + child: const Text("I can't find my trainer"))), ], ), ), @@ -155,46 +271,59 @@ class _BikeScanDialogState extends State { Widget _buildBody(BuildContext context) { if (_scanError != null) { - return _ScanMessage( + return SliverToBoxAdapter( + child: _ScanMessage( message: 'Could not start shifter trainer scan: $_scanError', action: TextButton.icon( onPressed: _startScan, icon: const Icon(Icons.refresh), label: const Text('Retry'), ), - ); + )); } if (_isStartingScan && _resultsByAddress.isEmpty) { - return const Center(child: CircularProgressIndicator()); + return const SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.all(24), + child: Center(child: CircularProgressIndicator()))); } final devices = _filteredDevices(); if (devices.isEmpty) { - return _ScanMessage( + return SliverToBoxAdapter( + child: _ScanMessage( message: _isScanning ? 'The shifter is scanning. Nearby trainers will appear here as soon as the shifter reports them.' : 'No matching trainers were reported by the shifter. Rescan with the trainer nearby and awake.', - ); + )); } - return ListView.separated( + return SliverPadding( padding: const EdgeInsets.fromLTRB(20, 0, 20, 20), - itemCount: devices.length, - separatorBuilder: (_, __) => const SizedBox(height: 12), - itemBuilder: (context, index) => _TrainerScanResultTile( - result: devices[index], - onTap: () => Navigator.of(context).pop(devices[index]), - ), + sliver: SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) => Padding( + padding: const EdgeInsets.only(bottom: 12), + child: _TrainerScanResultTile( + result: devices[index], + onTap: () { + if (_protocolLoading) return; + Navigator.of(context).pop(TrainerAssignment( + devices[index], + _hasProtocolSelection ? _protocol : null)); + }, + )), + childCount: devices.length)), ); } List _filteredDevices() { final devices = _resultsByAddress.values.where((device) { - return !_showOnlyFtms || device.ftmsDetected; + return !_showOnlyFtms || device.supported; }).toList(growable: false); devices.sort((a, b) { - final ftmsCompare = (b.ftmsDetected ? 1 : 0) - (a.ftmsDetected ? 1 : 0); + final ftmsCompare = (b.supported ? 1 : 0) - (a.supported ? 1 : 0); if (ftmsCompare != 0) { return ftmsCompare; } @@ -258,21 +387,24 @@ class _DialogHeader extends StatelessWidget { ], ), const SizedBox(height: 16), - Row( + Wrap( + spacing: 12, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, children: [ - Expanded( - child: Row( - children: [ - Text( - 'FTMS only', - style: Theme.of(context).textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(width: 8), - Switch(value: showOnlyFtms, onChanged: onChanged), - ], - ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + 'Supported trainers only', + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + )), + const SizedBox(width: 8), + Switch(value: showOnlyFtms, onChanged: onChanged), + ], ), SizedBox( width: 132, @@ -312,7 +444,11 @@ class _TrainerScanResultTile extends StatelessWidget { Widget build(BuildContext context) { final colorScheme = Theme.of(context).colorScheme; final name = result.name.isEmpty ? 'Unknown Trainer' : result.name; - final typeLabel = result.ftmsDetected ? 'FTMS trainer' : 'Nearby device'; + final typeLabel = result.ftmsDetected + ? 'FTMS' + : result.supported + ? 'Supported' + : 'Nearby device'; final addressText = _formatTrainerAddress(result.address); return Material( @@ -416,7 +552,8 @@ class _ScanMessage extends StatelessWidget { return Padding( padding: const EdgeInsets.all(20), child: Center( - child: Column( + child: SingleChildScrollView( + child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( @@ -428,7 +565,7 @@ class _ScanMessage extends StatelessWidget { SizedBox(width: 132, child: action!), ], ], - ), + )), ), ); } diff --git a/lib/widgets/simulation_card.dart b/lib/widgets/simulation_card.dart new file mode 100644 index 0000000..c825737 --- /dev/null +++ b/lib/widgets/simulation_card.dart @@ -0,0 +1,553 @@ +import 'dart:async'; + +import 'package:abawo_bt_app/model/shifter_types.dart'; +import 'package:abawo_bt_app/model/simulation.dart'; +import 'package:abawo_bt_app/service/shifter_service.dart'; +import 'package:flutter/material.dart'; + +class SimulationCard extends StatefulWidget { + const SimulationCard( + {super.key, required this.shifter, required this.enabled}); + final ShifterService shifter; + final bool enabled; + + @override + State createState() => _SimulationCardState(); +} + +class _SimulationCardState extends State { + final _form = GlobalKey(); + final _fields = List.generate(5, (_) => TextEditingController()); + SimulationConfig _draft = const SimulationConfig(); + Map _models = {}; + SimulationStatus? _status; + StreamSubscription? _subscription; + bool _loading = true; + bool _saving = false; + bool _loaded = false; + bool _dirty = false; + String? _error; + String? _statusError; + int _loadGeneration = 0; + + @override + void initState() { + super.initState(); + if (widget.enabled) unawaited(_load()); + } + + @override + void didUpdateWidget(covariant SimulationCard oldWidget) { + super.didUpdateWidget(oldWidget); + if (!widget.enabled && oldWidget.enabled) { + _loadGeneration++; + unawaited(_subscription?.cancel()); + _subscription = null; + _status = null; + } else if (widget.enabled && !oldWidget.enabled) { + unawaited(_load()); + } + } + + @override + void dispose() { + _loadGeneration++; + _subscription?.cancel(); + for (final field in _fields) { + field.dispose(); + } + super.dispose(); + } + + void _setDraft(SimulationConfig config) { + _draft = config; + final values = [ + config.riderWeight, + config.bikeWeight, + config.gradeMultiplier, + config.rollingMultiplier, + config.windMultiplier + ]; + for (var i = 0; i < values.length; i++) { + _fields[i].text = values[i].toStringAsFixed(i < 2 ? 2 : 3); + } + } + + Future _load() async { + final generation = ++_loadGeneration; + setState(() { + _loading = true; + _error = null; + _statusError = null; + }); + await _subscription?.cancel(); + _subscription = null; + final config = await widget.shifter.readSimulationConfig(); + if (!mounted || generation != _loadGeneration) return; + if (config.isErr()) { + setState(() { + _loading = false; + _loaded = false; + _error = + 'Simulation settings could not be read. Older firmware may not support this feature.'; + }); + return; + } + final catalog = + await widget.shifter.readSetting(simulationModelsCharacteristicUuid); + if (!mounted || generation != _loadGeneration) return; + Map models = {}; + if (catalog.isOk()) { + try { + models = decodeSimulationModels(catalog.unwrap()); + } on FormatException {/* Keep current model. */} + } + final current = config.unwrap(); + models.putIfAbsent(current.modelId, () => 'Model ${current.modelId}'); + setState(() { + _setDraft(current); + _models = models; + _loading = false; + _loaded = true; + _dirty = false; + }); + _subscription = + widget.shifter.subscribeToSimulationStatus().listen((status) { + if (mounted && generation == _loadGeneration) { + setState(() { + _status = status; + _statusError = null; + }); + } + }, onError: (Object error) { + if (mounted && generation == _loadGeneration) { + setState(() { + _status = null; + _statusError = 'Live simulation status is unavailable.'; + }); + } + }); + final status = + await widget.shifter.readSetting(simulationStatusCharacteristicUuid); + if (!mounted || generation != _loadGeneration || _status != null) return; + try { + if (status.isErr()) throw const FormatException(); + setState(() => _status = SimulationStatus.decode(status.unwrap())); + } on FormatException { + setState(() => _statusError = 'Live simulation status is unavailable.'); + } + } + + String? _validate(String? raw, int index) { + final value = double.tryParse((raw ?? '').replaceAll(',', '.')); + final min = index == 0 ? 1 : 0; + final max = index == 0 + ? 300 + : index == 1 + ? 100 + : 3; + if (value == null || !value.isFinite || value < min || value > max) { + return 'Enter $min to $max'; + } + return null; + } + + void _updatePreview() { + setState(() => _dirty = true); + if (List.generate(5, (i) => _validate(_fields[i].text, i)) + .any((error) => error != null)) { + return; + } + final values = + _fields.map((f) => double.parse(f.text.replaceAll(',', '.'))).toList(); + setState(() => _draft = _draft.copyWith( + riderWeight: values[0], + bikeWeight: values[1], + gradeMultiplier: values[2], + rollingMultiplier: values[3], + windMultiplier: values[4])); + } + + Future _save() async { + if (!_form.currentState!.validate() || !widget.enabled) return; + if (List.generate(5, (i) => _validate(_fields[i].text, i)) + .any((e) => e != null)) { + setState(() => + _error = 'Check your weight and advanced settings before saving.'); + return; + } + _updatePreview(); + setState(() { + _saving = true; + _error = null; + }); + final result = await widget.shifter.writeSimulationConfig(_draft); + if (!mounted) return; + setState(() { + _saving = false; + if (result.isErr()) { + _error = result.unwrapErr().toString(); + } else { + _dirty = false; + } + }); + if (result.isOk()) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Simulation settings saved.'))); + } + } + + Widget _field(int index, String label, String unit) => TextFormField( + controller: _fields[index], + enabled: widget.enabled && !_saving, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: InputDecoration(labelText: label, suffixText: unit), + autovalidateMode: AutovalidateMode.onUserInteraction, + validator: (value) => _validate(value, index), + onChanged: (_) => _updatePreview(), + ); + + @override + Widget build(BuildContext context) { + final canEdit = widget.enabled && !_saving; + return Card( + child: Padding( + padding: const EdgeInsets.all(18), + child: Form( + key: _form, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row(children: [ + Icon(Icons.landscape_outlined, + color: Theme.of(context).colorScheme.primary), + const SizedBox(width: 10), + Text('Simulation', + style: Theme.of(context).textTheme.titleLarge) + ]), + const SizedBox(height: 14), + if (_loading) + const Center( + child: Padding( + padding: EdgeInsets.all(16), + child: CircularProgressIndicator())), + if (_error != null) ...[ + Text(_error!, + style: TextStyle( + color: Theme.of(context).colorScheme.error)), + const SizedBox(height: 8), + ], + if (!_loaded && !_loading) + TextButton( + onPressed: widget.enabled ? _load : null, + child: const Text('Retry')), + if (_loaded && !_loading) ...[ + Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: Theme.of(context) + .colorScheme + .surfaceContainerHighest + .withValues(alpha: 0.54), + borderRadius: BorderRadius.circular(18)), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _status?.label ?? + 'Waiting for simulation status', + style: const TextStyle( + fontWeight: FontWeight.w600)), + if (_status?.details != null) ...[ + const SizedBox(height: 4), + Text(_status!.details!) + ], + if (_statusError != null) Text(_statusError!), + ])), + const SizedBox(height: 16), + DropdownButtonFormField( + key: ValueKey(_draft.policy), + initialValue: _draft.policy, + isExpanded: true, + decoration: const InputDecoration( + labelText: 'Simulation mode'), + items: SimulationPolicy.values + .map((p) => DropdownMenuItem( + value: p, child: Text(p.label))) + .toList(), + onChanged: canEdit + ? (policy) => setState(() { + _draft = _draft.copyWith(policy: policy); + _dirty = true; + }) + : null), + const SizedBox(height: 8), + Text(switch (_draft.policy) { + SimulationPolicy.auto => + 'Use native simulation when available. Otherwise emulate through target power.', + SimulationPolicy.force => + 'Emulate simulation through target power, even when native simulation is available.', + SimulationPolicy.native => + 'Use native simulation only. Do not emulate through target power.', + }), + const SizedBox(height: 6), + const Text( + 'Emulation requires target-power control and fresh trainer speed. It cannot add control to a read-only trainer.'), + const SizedBox(height: 18), + LayoutBuilder(builder: (context, constraints) { + if (constraints.maxWidth < 340) { + return Column(children: [ + _field(0, 'Rider weight', 'kg'), + const SizedBox(height: 16), + _field(1, 'Bike weight', 'kg') + ]); + } + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: _field(0, 'Rider weight', 'kg')), + const SizedBox(width: 12), + Expanded(child: _field(1, 'Bike weight', 'kg')) + ]); + }), + const SizedBox(height: 10), + const Text( + 'ANT+ defaults: 75 kg rider and 10 kg bike. Weight received over ANT+ takes priority until the trainer disconnects. Saved weights are not changed.'), + const SizedBox(height: 8), + ExpansionTile( + tilePadding: EdgeInsets.zero, + childrenPadding: const EdgeInsets.only(bottom: 16), + title: const Text('Advanced settings'), + subtitle: + const Text('Model, tuning and power preview'), + children: [ + const Text( + 'These settings affect local emulation, not native simulation.'), + const SizedBox(height: 16), + DropdownButtonFormField( + key: ValueKey(_draft.modelId), + initialValue: _draft.modelId, + isExpanded: true, + decoration: const InputDecoration( + labelText: 'Simulation model'), + items: _models.entries + .map((entry) => DropdownMenuItem( + value: entry.key, + child: Text(switch (entry.value) { + 'fe-c' => 'ANT+ FE-C', + 'track-only' => 'Track only', + _ => entry.value + }))) + .toList(), + onChanged: canEdit + ? (id) => setState(() { + _draft = _draft.copyWith(modelId: id); + _dirty = true; + }) + : null), + const SizedBox(height: 16), + _field(2, 'Grade multiplier', 'x'), + const SizedBox(height: 16), + _field(3, 'Rolling resistance multiplier', 'x'), + const SizedBox(height: 16), + _field(4, 'Wind resistance multiplier', 'x'), + const SizedBox(height: 18), + if (_draft.modelId == 1 || _draft.modelId == 2) ...[ + const Align( + alignment: Alignment.centerLeft, + child: Text( + "Estimated simulation power with no wind and a gear ratio of 1. Limited by your trainer's power limits.")), + const SizedBox(height: 8), + if (List.generate( + 5, (i) => _validate(_fields[i].text, i)) + .any((e) => e != null)) + const Text( + 'Enter valid values to update the preview.'), + PowerPreviewChart( + config: _draft, gradeChart: false), + const SizedBox(height: 20), + PowerPreviewChart( + config: _draft, gradeChart: true), + const SizedBox(height: 8), + const Text( + 'Preview uses the weight fields above, default rolling resistance and no drafting. It does not include live ANT+ weight or trainer power limits.'), + ] else + const Text( + 'Power preview is not available for this model.'), + ]), + const SizedBox(height: 12), + Wrap( + spacing: 10, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + FilledButton( + onPressed: canEdit && _dirty ? _save : null, + child: Text(_saving + ? 'Saving changes' + : 'Save changes')), + TextButton( + onPressed: canEdit + ? () => setState(() { + _setDraft(SimulationConfig( + modelId: _models.containsKey(1) + ? 1 + : _draft.modelId)); + _dirty = true; + }) + : null, + child: const Text('Reset to defaults')), + ]), + ], + ]), + ))); + } +} + +class PowerPreviewChart extends StatefulWidget { + const PowerPreviewChart( + {super.key, required this.config, required this.gradeChart}); + final SimulationConfig config; + final bool gradeChart; + + @override + State createState() => _PowerPreviewChartState(); +} + +class _PowerPreviewChartState extends State { + double _position = 0.5; + + @override + Widget build(BuildContext context) { + final grade = widget.gradeChart; + final min = grade ? -5.0 : 0.0; + final max = grade ? 5.0 : 50.0; + final unit = grade ? '%' : 'km/h'; + final x = min + (max - min) * _position; + double watts(double x) => + widget.config.previewWatts(grade ? 15 : x, grade ? x : 0); + final top = + ((watts(max) / 50).ceil() * 50).clamp(50, double.infinity).toDouble(); + final color = Theme.of(context).colorScheme.primary; + final muted = + Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.65); + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(grade ? 'Power by slope' : 'Power by speed', + style: Theme.of(context).textTheme.titleMedium), + Text(grade ? 'At 15 km/h' : 'At 0% slope', + style: TextStyle(color: muted)), + const SizedBox(height: 12), + Text('${x.toStringAsFixed(1)} $unit: ${watts(x).round()} W', + style: TextStyle(color: color, fontWeight: FontWeight.w600)), + const SizedBox(height: 8), + Row(children: [ + SizedBox( + width: 48, + height: 150, + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('${top.round()} W', + style: TextStyle(fontSize: 11, color: muted)), + Text('${(top / 2).round()}', + style: TextStyle(fontSize: 11, color: muted)), + Text('0', style: TextStyle(fontSize: 11, color: muted)) + ])), + Expanded( + child: LayoutBuilder( + builder: (context, constraints) => GestureDetector( + onTapDown: (event) => setState(() => _position = + (event.localPosition.dx / constraints.maxWidth) + .clamp(0.0, 1.0)), + onHorizontalDragUpdate: (event) => setState(() => + _position = + (event.localPosition.dx / constraints.maxWidth) + .clamp(0.0, 1.0)), + child: SizedBox( + height: 150, + width: double.infinity, + child: CustomPaint( + painter: _PowerCurvePainter( + values: List.generate( + 101, + (i) => + watts(min + (max - min) * i / 100)), + top: top, + position: _position, + color: color, + grid: Theme.of(context) + .colorScheme + .outlineVariant))), + ))), + ]), + Padding( + padding: const EdgeInsets.only(left: 48), + child: + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text('${min.round()} $unit'), + Text('${((min + max) / 2).round()} $unit'), + Text('${max.round()} $unit') + ])), + Slider( + value: _position, + onChanged: (value) => setState(() => _position = value), + semanticFormatterCallback: (_) => + '${x.toStringAsFixed(1)} $unit, ${watts(x).round()} watts'), + ]); + } +} + +class _PowerCurvePainter extends CustomPainter { + _PowerCurvePainter( + {required this.values, + required this.top, + required this.position, + required this.color, + required this.grid}); + final List values; + final double top; + final double position; + final Color color; + final Color grid; + + @override + void paint(Canvas canvas, Size size) { + final gridPaint = Paint() + ..color = grid.withValues(alpha: 0.5) + ..strokeWidth = 1; + for (var i = 0; i <= 4; i++) { + final y = size.height * i / 4; + canvas.drawLine(Offset(0, y), Offset(size.width, y), gridPaint); + } + final path = Path(); + for (var i = 0; i < values.length; i++) { + final x = size.width * i / (values.length - 1); + final y = size.height * (1 - values[i] / top); + if (i == 0) { + path.moveTo(x, y); + } else { + path.lineTo(x, y); + } + } + canvas.drawPath( + path, + Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = 2.5); + final x = position * size.width; + canvas.drawLine(Offset(x, 0), Offset(x, size.height), gridPaint); + final index = position * (values.length - 1); + final lower = index.floor(); + final upper = index.ceil(); + final value = + values[lower] + (values[upper] - values[lower]) * (index - lower); + canvas.drawCircle( + Offset(x, size.height * (1 - value / top)), 4, Paint()..color = color); + } + + @override + bool shouldRepaint(covariant _PowerCurvePainter oldDelegate) => true; +} diff --git a/pubspec.yaml b/pubspec.yaml index 26f2cca..a433c77 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -92,6 +92,7 @@ flutter: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg assets: + - assets/trainer_models.json - assets/images/shifter-wireframe.png - assets/images/gears/png/filled/ diff --git a/test/model/simulation_test.dart b/test/model/simulation_test.dart new file mode 100644 index 0000000..26ef277 --- /dev/null +++ b/test/model/simulation_test.dart @@ -0,0 +1,71 @@ +import 'dart:convert'; +import 'package:abawo_bt_app/model/simulation.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('default configuration matches firmware bytes', () { + const config = SimulationConfig(); + expect(config.encode(), + [1, 0, 1, 0, 0x4c, 0x1d, 0xe8, 3, 0xe8, 3, 0xe8, 3, 0xe8, 3]); + expect(SimulationConfig.decode(config.encode()).encode(), config.encode()); + }); + + test('configuration validates schema, reserved byte and ranges', () { + for (final change in [(0, 2), (1, 3), (2, 0), (3, 1), (5, 255), (9, 255)]) { + final bytes = const SimulationConfig().encode().toList(); + bytes[change.$1] = change.$2; + expect(() => SimulationConfig.decode(bytes), throwsFormatException); + } + expect(() => SimulationConfig.decode([1]), throwsFormatException); + expect(() => const SimulationConfig(riderWeight: double.nan).encode(), + throwsFormatException); + expect(() => const SimulationConfig(bikeWeight: 101).encode(), + throwsFormatException); + expect(() => const SimulationConfig(gradeMultiplier: 3.001).encode(), + throwsFormatException); + const boundary = + SimulationConfig(riderWeight: 1, bikeWeight: 100, windMultiplier: 3); + expect( + SimulationConfig.decode(boundary.encode()).encode(), boundary.encode()); + }); + + test('preview follows firmware FE-C formula and percent grade', () { + const config = SimulationConfig(); + final expected = + (85 * 0.05 * 9.81 + 85 * 0.004 * 9.8 + 0.5 * 0.51 * 100) * 10; + expect(config.previewWatts(36, 5), closeTo(expected, 0.00001)); + expect(config.previewWatts(0, 5), 0); + expect(config.previewWatts(15, -5), 0); + expect(config.previewWatts(15, 0), closeTo(32.3295138889, 0.0001)); + expect(const SimulationConfig(modelId: 2).previewWatts(36, 0), + closeTo(33.32, 0.00001)); + expect(config.copyWith(windMultiplier: 0).previewWatts(36, 0), + closeTo(33.32, 0.00001)); + expect(config.copyWith(gradeMultiplier: 0).previewWatts(15, 5), + config.previewWatts(15, 0)); + }); + + test('model catalog supports stable future IDs without inventing previews', + () { + expect(decodeSimulationModels(utf8.encode('1:fe-c;2:track-only;9:future')), + {1: 'fe-c', 2: 'track-only', 9: 'future'}); + expect(() => decodeSimulationModels(utf8.encode('1:fe-c;1:other')), + throwsFormatException); + expect(() => const SimulationConfig(modelId: 9).previewWatts(15, 0), + throwsFormatException); + }); + + test('runtime status handles sentinels, faults and stale speed', () { + final inactive = SimulationStatus.decode([1, 0, 0, 0, 255, 255]); + expect(inactive.watts, isNull); + expect(inactive.label, 'Inactive'); + final running = SimulationStatus.decode([1, 2, 1, 0, 145, 0]); + expect(running.details, 'Target power: 145 W'); + expect(SimulationStatus.decode([1, 2, 0, 0, 145, 0]).details, + 'Waiting for trainer speed'); + expect(SimulationStatus.decode([1, 3, 0, 5, 255, 255]).details, + contains('denied')); + expect(() => SimulationStatus.decode([2, 0, 0, 0, 0, 0]), + throwsFormatException); + }); +} diff --git a/test/service/shifter_settings_test.dart b/test/service/shifter_settings_test.dart new file mode 100644 index 0000000..b2b886b --- /dev/null +++ b/test/service/shifter_settings_test.dart @@ -0,0 +1,65 @@ +import 'dart:convert'; +import 'package:abawo_bt_app/model/shifter_types.dart'; +import 'package:abawo_bt_app/model/simulation.dart'; +import 'package:abawo_bt_app/service/shifter_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import '../support/settings_bluetooth.dart'; + +void main() { + late SettingsBluetooth bluetooth; + late ShifterService service; + setUp(() { + bluetooth = SettingsBluetooth(); + service = ShifterService(bluetooth: bluetooth, buttonDeviceId: 'test'); + }); + tearDown(() async { + await service.dispose(); + await bluetooth.close(); + }); + + test('selection is confirmed before address and connection command', + () async { + final result = await service.connectButtonToTrainer( + const TrainerAddress(flags: 0, bytes: [1, 2, 3, 4, 5, 6]), + protocol: 'yesoul'); + expect(result.isOk(), isTrue); + expect(bluetooth.steps, [ + 'write:$trainerProtocolCharacteristicUuid', + 'read:$trainerProtocolCharacteristicUuid', + 'write:$universalShifterConnectToAddrCharacteristicUuid', + 'write:$universalShifterCommandCharacteristicUuid' + ]); + }); + test('rejected protocol does not connect or write address', () async { + bluetooth.rejectWrites = true; + final result = await service.connectButtonToTrainer( + const TrainerAddress(flags: 0, bytes: [1, 2, 3, 4, 5, 6]), + protocol: 'yesoul'); + expect(result.isErr(), isTrue); + expect(bluetooth.steps.length, 2); + expect(utf8.decode(bluetooth.values[trainerProtocolCharacteristicUuid]!), + 'auto'); + }); + test('legacy connection does not require optional protocol characteristic', + () async { + bluetooth.values.remove(trainerProtocolCharacteristicUuid); + final result = await service.connectButtonToTrainer( + const TrainerAddress(flags: 0, bytes: [1, 2, 3, 4, 5, 6])); + expect(result.isOk(), isTrue); + expect(bluetooth.steps.length, 2); + }); + test('simulation saves require matching read-back', () async { + const config = + SimulationConfig(policy: SimulationPolicy.force, riderWeight: 80.25); + expect((await service.writeSimulationConfig(config)).isOk(), isTrue); + expect((await service.readSimulationConfig()).unwrap().riderWeight, 80.25); + bluetooth.rejectWrites = true; + expect( + (await service.writeSimulationConfig(const SimulationConfig())).isErr(), + isTrue); + }); + test('malformed configuration is a recoverable read error', () async { + bluetooth.values[simulationConfigCharacteristicUuid] = [1]; + expect((await service.readSimulationConfig()).isErr(), isTrue); + }); +} diff --git a/test/support/settings_bluetooth.dart b/test/support/settings_bluetooth.dart new file mode 100644 index 0000000..e4bea25 --- /dev/null +++ b/test/support/settings_bluetooth.dart @@ -0,0 +1,52 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:abawo_bt_app/controller/bluetooth.dart'; +import 'package:abawo_bt_app/model/shifter_types.dart'; +import 'package:abawo_bt_app/model/simulation.dart'; +import 'package:anyhow/anyhow.dart'; + +class SettingsBluetooth implements BluetoothController { + final values = >{ + trainerProtocolCharacteristicUuid: utf8.encode('auto'), + simulationConfigCharacteristicUuid: const SimulationConfig().encode(), + simulationModelsCharacteristicUuid: utf8.encode('1:fe-c;2:track-only'), + simulationStatusCharacteristicUuid: [1, 2, 1, 0, 145, 0], + }; + final steps = []; + final scan = StreamController>.broadcast(); + final simulation = StreamController>.broadcast(); + bool rejectWrites = false; + + @override + Future>> readCharacteristic( + String deviceId, String serviceUuid, String uuid) async { + steps.add('read:$uuid'); + return values.containsKey(uuid) + ? Ok(values[uuid]!) + : bail('Characteristic not found'); + } + + @override + Future> writeCharacteristic( + String deviceId, String serviceUuid, String uuid, List value, + {bool withResponse = true}) async { + steps.add('write:$uuid'); + if (!rejectWrites) values[uuid] = List.of(value); + return const Ok(null); + } + + @override + Stream> subscribeToCharacteristic( + String deviceId, String serviceUuid, String uuid) => + uuid == universalShifterScanResultCharacteristicUuid + ? scan.stream + : simulation.stream; + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); + + Future close() async { + await scan.close(); + await simulation.close(); + } +} diff --git a/test/trainer_ui_test.dart b/test/trainer_ui_test.dart new file mode 100644 index 0000000..479c793 --- /dev/null +++ b/test/trainer_ui_test.dart @@ -0,0 +1,190 @@ +import 'package:abawo_bt_app/model/shifter_types.dart'; +import 'package:abawo_bt_app/model/trainer_model.dart'; +import 'package:abawo_bt_app/pages/trainer_model_search_page.dart'; +import 'package:abawo_bt_app/service/shifter_service.dart'; +import 'package:abawo_bt_app/theme/app_theme.dart'; +import 'package:abawo_bt_app/widgets/bike_scan_dialog.dart'; +import 'package:abawo_bt_app/widgets/simulation_card.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'support/settings_bluetooth.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + test('offline catalog includes all selectable profiles and search aliases', + () async { + final models = await TrainerModel.load(); + expect(models.length, 128); + expect(models.map((m) => m.id).toSet().length, 128); + expect( + models.where((m) => m.matches('kettler c12')).single.id, 'kettler-c12'); + expect( + models.where((m) => m.matches('NordicTrack')).length, greaterThan(1)); + expect(models.any((m) => m.id == 'schwinn-170' || m.id == 'ifit-model-97'), + isFalse); + }); + + testWidgets( + 'scan includes proprietary and broadcast trainers on a small phone', + (tester) async { + tester.view.physicalSize = const Size(360, 740); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final bluetooth = SettingsBluetooth(); + final service = + ShifterService(bluetooth: bluetooth, buttonDeviceId: 'test'); + await tester.pumpWidget(MaterialApp( + theme: AppTheme.light(), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => + BikeScanDialog.show(context, shifter: service), + child: const Text('Open')))))); + await tester.tap(find.text('Open')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + bluetooth.scan.add( + [1, 1, 0, 0, 1, 2, 3, 4, 5, 6, 190, 0x10, 6, ...'Keiser'.codeUnits]); + await tester.pump(); + expect(find.text('Keiser'), findsOneWidget); + expect(find.text('Supported'), findsOneWidget); + expect(find.text("I can't find my trainer"), findsOneWidget); + expect(tester.takeException(), isNull); + bluetooth.scan.add([1, 2, 0]); + await tester.pump(); + await tester.tap(find.text("I can't find my trainer")); + await tester.pumpAndSettle(); + expect(find.text('Find trainer model'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + await service.dispose(); + await bluetooth.close(); + }); + + testWidgets( + 'simulation loads status, collapses advanced settings and saves weight', + (tester) async { + final bluetooth = SettingsBluetooth(); + final service = + ShifterService(bluetooth: bluetooth, buttonDeviceId: 'test'); + await tester.pumpWidget(MaterialApp( + theme: AppTheme.light(), + home: Scaffold( + body: SingleChildScrollView( + child: SimulationCard(shifter: service, enabled: true))))); + await tester.pumpAndSettle(); + expect(find.text('Emulated simulation'), findsOneWidget); + expect(find.text('Target power: 145 W'), findsOneWidget); + expect(find.byType(PowerPreviewChart), findsNothing); + await tester.enterText( + find.widgetWithText(TextFormField, 'Rider weight'), '80'); + await tester.pump(); + await tester.ensureVisible(find.text('Save changes')); + await tester.tap(find.text('Save changes')); + await tester.pumpAndSettle(); + expect(find.text('Simulation settings saved.'), findsOneWidget); + await tester.ensureVisible(find.text('Advanced settings')); + await tester.tap(find.text('Advanced settings')); + await tester.pumpAndSettle(); + expect(find.byType(PowerPreviewChart), findsNWidgets(2)); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + await service.dispose(); + await bluetooth.close(); + }); + + testWidgets('older firmware keeps unsupported settings non-editable', + (tester) async { + final bluetooth = SettingsBluetooth() + ..values.remove(simulationConfigCharacteristicUuid); + final service = + ShifterService(bluetooth: bluetooth, buttonDeviceId: 'test'); + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: SimulationCard(shifter: service, enabled: true)))); + await tester.pumpAndSettle(); + expect(find.textContaining('Older firmware'), findsOneWidget); + expect(find.text('Save changes'), findsNothing); + await tester.pumpWidget(const SizedBox()); + await service.dispose(); + await bluetooth.close(); + }); + + testWidgets('model search shows exact model and firmware requirements', + (tester) async { + final models = await tester.runAsync(() => TrainerModel.load()); + await tester.pumpWidget(MaterialApp( + theme: AppTheme.light(), + home: TrainerModelSearchPage( + canSelect: false, models: Future.value(models!)))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await tester.enterText(find.byType(TextField), 'Kettler C12'); + await tester.pump(); + expect(find.text('Kettler C12'), findsWidgets); + await tester.tap(find.byType(ListTile)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(find.text('Firmware update required'), findsOneWidget); + expect(find.text('Data only'), findsOneWidget); + expect(find.text('Find nearby trainer'), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('scan controls remain reachable in landscape with larger text', + (tester) async { + tester.view.physicalSize = const Size(740, 360); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final bluetooth = SettingsBluetooth(); + final service = + ShifterService(bluetooth: bluetooth, buttonDeviceId: 'test'); + await tester.pumpWidget(MaterialApp( + theme: AppTheme.dark(), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context) + .copyWith(textScaler: const TextScaler.linear(1.4)), + child: child!), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => + BikeScanDialog.show(context, shifter: service), + child: const Text('Open')))))); + await tester.tap(find.text('Open')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(find.text("I can't find my trainer"), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + await service.dispose(); + await bluetooth.close(); + }); + + testWidgets('simulation changes are disabled during firmware update', + (tester) async { + final bluetooth = SettingsBluetooth(); + final service = + ShifterService(bluetooth: bluetooth, buttonDeviceId: 'test'); + Widget app(bool enabled) => MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: SimulationCard(shifter: service, enabled: enabled)))); + await tester.pumpWidget(app(true)); + await tester.pumpAndSettle(); + await tester.enterText( + find.widgetWithText(TextFormField, 'Rider weight'), '82'); + await tester.pumpWidget(app(false)); + await tester.pump(); + final save = tester.widget( + find.widgetWithText(FilledButton, 'Save changes')); + expect(save.onPressed, isNull); + final count = bluetooth.steps.length; + await tester.pump(const Duration(seconds: 1)); + expect(bluetooth.steps.length, count); + await tester.pumpWidget(const SizedBox()); + await service.dispose(); + await bluetooth.close(); + }); +} diff --git a/tool/import_trainer_catalog.py b/tool/import_trainer_catalog.py new file mode 100644 index 0000000..423cef4 --- /dev/null +++ b/tool/import_trainer_catalog.py @@ -0,0 +1,26 @@ +"""Import selectable profiles from the firmware's measured model matrix. + +Usage: python3 tool/import_trainer_catalog.py ../kettler2ant-rs +The catalog is bundled offline. It is not proof of installed firmware support. +""" +import json +from pathlib import Path +import sys + +source = Path(sys.argv[1]) / 'universal-shifters/trainer-build-matrix.md' +profiles = [] +for line in source.read_text().splitlines(): + cells = [cell.strip() for cell in line.split('|')[1:-1]] + if len(cells) != 6 or not cells[1].startswith('`'): + continue + family, profile_id, name, equipment, selection, bundles = cells + if 'configured' in selection or profile_id.strip('`') in ('schwinn-170', 'ifit-model-97'): + continue + profiles.append(dict(id=profile_id.strip('`'), name=name.replace('_', ' '), + family=family, equipment=equipment, + manual=selection == 'manual', bundles=bundles.split(', '))) +if len(profiles) != 128: + raise SystemExit(f'Expected 128 selectable profiles, found {len(profiles)}. Review registry changes.') +target = Path(__file__).resolve().parents[1] / 'assets/trainer_models.json' +target.write_text(json.dumps(profiles, indent=2) + '\n') +print(f'Imported {len(profiles)} profiles to {target}')