feat: basic trainer support

This commit is contained in:
2026-11-24 20:02:05 +01:00
parent 30b25784c1
commit 9dece10e29
17 changed files with 3048 additions and 58 deletions

View File

@ -5,6 +5,7 @@ A new Flutter project.
## Operational Docs ## Operational Docs
- [Bootloader OTA Operator Guide](docs/bootloader-ota-operator-guide.md) - [Bootloader OTA Operator Guide](docs/bootloader-ota-operator-guide.md)
- [Trainer setup and simulation](docs/trainer-setup-and-simulation.md)
## Getting Started ## Getting Started

1305
assets/trainer_models.json Normal file

File diff suppressed because it is too large Load Diff

View File

@ -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.

View File

@ -21,6 +21,14 @@ const String universalShifterDfuDataCharacteristicUuid =
const String universalShifterDfuStatusCharacteristicUuid = const String universalShifterDfuStatusCharacteristicUuid =
'0993826f-0ee4-4b37-9614-d13ecba4000a'; '0993826f-0ee4-4b37-9614-d13ecba4000a';
const String ftmsServiceUuid = '00001826-0000-1000-8000-00805f9b34fb'; 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 batteryServiceUuid = '0000180f-0000-1000-8000-00805f9b34fb';
const String batteryLevelCharacteristicUuid = const String batteryLevelCharacteristicUuid =
'00002a19-0000-1000-8000-00805f9b34fb'; '00002a19-0000-1000-8000-00805f9b34fb';
@ -65,6 +73,8 @@ const int errorFtmsMissing = 2;
const int errorPairingAuth = 3; const int errorPairingAuth = 3;
const int errorPairingEncrypt = 4; const int errorPairingEncrypt = 4;
const int errorFtmsRequiredCharMissing = 5; const int errorFtmsRequiredCharMissing = 5;
const int errorTrainerTimeout = 6;
const int errorTrainerProtocol = 7;
const int trainerScanProtocolVersion = 1; const int trainerScanProtocolVersion = 1;
@ -72,6 +82,7 @@ const int trainerScanDeviceFlagFtmsDetected = 0x01;
const int trainerScanDeviceFlagNameComplete = 0x02; const int trainerScanDeviceFlagNameComplete = 0x02;
const int trainerScanDeviceFlagScanResponseSeen = 0x04; const int trainerScanDeviceFlagScanResponseSeen = 0x04;
const int trainerScanDeviceFlagConnectable = 0x08; const int trainerScanDeviceFlagConnectable = 0x08;
const int trainerScanDeviceFlagSupported = 0x10;
enum DfuUpdateState { enum DfuUpdateState {
idle, idle,
@ -220,9 +231,9 @@ ShifterErrorInfo shifterErrorInfo(int code) {
case errorFtmsMissing: case errorFtmsMissing:
return const ShifterErrorInfo( return const ShifterErrorInfo(
code: errorFtmsMissing, code: errorFtmsMissing,
title: 'FTMS service missing', title: 'Trainer not detected',
details: 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: case errorPairingAuth:
return const ShifterErrorInfo( return const ShifterErrorInfo(
@ -241,10 +252,22 @@ ShifterErrorInfo shifterErrorInfo(int code) {
case errorFtmsRequiredCharMissing: case errorFtmsRequiredCharMissing:
return const ShifterErrorInfo( return const ShifterErrorInfo(
code: errorFtmsRequiredCharMissing, code: errorFtmsRequiredCharMissing,
title: 'Required FTMS characteristic missing', title: 'Trainer setup failed',
details: 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: default:
return ShifterErrorInfo( return ShifterErrorInfo(
code: code, code: code,
@ -336,6 +359,8 @@ class TrainerScanResult {
final String name; final String name;
bool get ftmsDetected => (flags & trainerScanDeviceFlagFtmsDetected) != 0; bool get ftmsDetected => (flags & trainerScanDeviceFlagFtmsDetected) != 0;
bool get supported =>
ftmsDetected || (flags & trainerScanDeviceFlagSupported) != 0;
bool get nameComplete => (flags & trainerScanDeviceFlagNameComplete) != 0; bool get nameComplete => (flags & trainerScanDeviceFlagNameComplete) != 0;
bool get scanResponseSeen => bool get scanResponseSeen =>
(flags & trainerScanDeviceFlagScanResponseSeen) != 0; (flags & trainerScanDeviceFlagScanResponseSeen) != 0;
@ -498,9 +523,9 @@ class TrainerStatus {
case TrainerConnectionState.connected: case TrainerConnectionState.connected:
return 'Connected'; return 'Connected';
case TrainerConnectionState.discoveringFtms: case TrainerConnectionState.discoveringFtms:
return 'Discovering FTMS'; return 'Detecting trainer';
case TrainerConnectionState.ftmsReady: case TrainerConnectionState.ftmsReady:
return 'FTMS Ready'; return 'Trainer ready';
case TrainerConnectionState.error: case TrainerConnectionState.error:
return 'Error${errorCode != null ? ' ($errorCode)' : ''}'; return 'Error${errorCode != null ? ' ($errorCode)' : ''}';
} }

183
lib/model/simulation.dart Normal file
View File

@ -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<int> 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<int> 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<int, String> decodeSimulationModels(List<int> bytes) {
final result = <int, String>{};
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<int> 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';
}
}

View File

@ -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<String> bundles;
final bool manual;
static Future<List<TrainerModel>> 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<String>.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(', ');
}

View File

@ -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/bike_scan_dialog.dart';
import 'package:abawo_bt_app/widgets/firmware_update_fullscreen.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/gear_ratio_editor_card.dart';
import 'package:abawo_bt_app/widgets/simulation_card.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
@ -494,27 +495,43 @@ class _DeviceDetailsPageState extends ConsumerState<DeviceDetailsPage> {
} }
_isAssignTrainerDialogOpen = true; _isAssignTrainerDialogOpen = true;
final TrainerScanResult? selectedTrainer; final TrainerAssignment? assignment;
try { try {
selectedTrainer = await BikeScanDialog.show( assignment = await BikeScanDialog.show(
context, context,
shifter: shifter, shifter: shifter,
); );
} finally { } finally {
_isAssignTrainerDialogOpen = false; _isAssignTrainerDialogOpen = false;
} }
if (selectedTrainer == null || !mounted) { if (assignment == null || !mounted) {
return; return;
} }
final selectedTrainer = assignment.trainer;
final result = final result = await shifter.connectButtonToTrainer(selectedTrainer.address,
await shifter.connectButtonToTrainer(selectedTrainer.address); protocol: assignment.protocol);
if (!mounted) { if (!mounted) {
return; return;
} }
if (result.isErr()) { if (result.isErr()) {
final err = result.unwrapErr(); final err = result.unwrapErr();
if (err.toString().contains('Firmware update required')) {
await showDialog<void>(
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( ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Connect request failed: $err')), SnackBar(content: Text('Connect request failed: $err')),
); );
@ -1124,6 +1141,13 @@ class _DeviceDetailsPageState extends ConsumerState<DeviceDetailsPage> {
), ),
], ],
), ),
const SizedBox(height: 16),
if (_shifterService != null)
SimulationCard(
key: ObjectKey(_shifterService),
shifter: _shifterService!,
enabled: !_isFirmwareUpdateBusy,
),
] else if (isCurrentConnected) ...[ ] else if (isCurrentConnected) ...[
_PairingRequiredCard( _PairingRequiredCard(
isChecking: _isPairingCheckRunning, isChecking: _isPairingCheckRunning,

View File

@ -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<List<TrainerModel>>? models;
@override
State<TrainerModelSearchPage> createState() => _TrainerModelSearchPageState();
}
class _TrainerModelSearchPageState extends State<TrainerModelSearchPage> {
late Future<List<TrainerModel>> _models =
widget.models ?? TrainerModel.load();
String _query = '';
Future<void> _select(TrainerModel model) async {
final selected = await showDialog<bool>(
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<List<TrainerModel>>(
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)));
});
})),
])),
);
}

View File

@ -1,8 +1,10 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert';
import 'package:abawo_bt_app/controller/bluetooth.dart'; import 'package:abawo_bt_app/controller/bluetooth.dart';
import 'package:abawo_bt_app/model/gear_ratio_codec.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/shifter_types.dart';
import 'package:abawo_bt_app/model/simulation.dart';
import 'package:anyhow/anyhow.dart'; import 'package:anyhow/anyhow.dart';
import 'package:logging/logging.dart'; import 'package:logging/logging.dart';
@ -77,9 +79,12 @@ class ShifterService {
); );
} }
Future<Result<void>> connectButtonToTrainer( Future<Result<void>> connectButtonToTrainer(TrainerAddress trainerAddress,
TrainerAddress trainerAddress, {String? protocol}) async {
) async { if (protocol != null) {
final selection = await writeTrainerProtocol(protocol);
if (selection.isErr()) return selection;
}
final addrRes = await writeConnectToTrainerAddress(trainerAddress); final addrRes = await writeConnectToTrainerAddress(trainerAddress);
if (addrRes.isErr()) { if (addrRes.isErr()) {
return addrRes; return addrRes;
@ -87,6 +92,82 @@ class ShifterService {
return writeCommand(UniversalShifterCommand.connectToDevice); return writeCommand(UniversalShifterCommand.connectToDevice);
} }
Future<Result<List<int>>> readSetting(String uuid) =>
_requireBluetooth.readCharacteristic(
buttonDeviceId, universalShifterControlServiceUuid, uuid);
Future<Result<String>> 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<Result<void>> 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<Result<SimulationConfig>> 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<Result<void>> 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<SimulationStatus> subscribeToSimulationStatus() => _requireBluetooth
.subscribeToCharacteristic(
buttonDeviceId,
universalShifterControlServiceUuid,
simulationStatusCharacteristicUuid)
.map(SimulationStatus.decode);
Future<Result<GearRatiosData>> readGearRatios() async { Future<Result<GearRatiosData>> readGearRatios() async {
final readRes = await _requireBluetooth.readCharacteristic( final readRes = await _requireBluetooth.readCharacteristic(
buttonDeviceId, buttonDeviceId,

View File

@ -1,9 +1,17 @@
import 'dart:async'; import 'dart:async';
import 'package:abawo_bt_app/model/shifter_types.dart'; 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/service/shifter_service.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class TrainerAssignment {
const TrainerAssignment(this.trainer, this.protocol);
final TrainerScanResult trainer;
final String? protocol;
}
class BikeScanDialog extends StatefulWidget { class BikeScanDialog extends StatefulWidget {
const BikeScanDialog({ const BikeScanDialog({
required this.shifter, required this.shifter,
@ -12,11 +20,11 @@ class BikeScanDialog extends StatefulWidget {
final ShifterService shifter; final ShifterService shifter;
static Future<TrainerScanResult?> show( static Future<TrainerAssignment?> show(
BuildContext context, { BuildContext context, {
required ShifterService shifter, required ShifterService shifter,
}) { }) {
return showDialog<TrainerScanResult>( return showDialog<TrainerAssignment>(
context: context, context: context,
barrierDismissible: true, barrierDismissible: true,
builder: (_) => BikeScanDialog(shifter: shifter), builder: (_) => BikeScanDialog(shifter: shifter),
@ -34,18 +42,88 @@ class _BikeScanDialogState extends State<BikeScanDialog> {
String? _scanError; String? _scanError;
final Map<String, TrainerScanResult> _resultsByAddress = {}; final Map<String, TrainerScanResult> _resultsByAddress = {};
StreamSubscription<TrainerScanEvent>? _scanSubscription; StreamSubscription<TrainerScanEvent>? _scanSubscription;
bool _protocolLoading = true;
bool _hasProtocolSelection = false;
String _protocol = 'auto';
String? _modelName;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
unawaited(_startScan()); unawaited(_startScan());
unawaited(_loadProtocol());
}
Future<void> _loadProtocol() async {
final result = await widget.shifter.readTrainerProtocol();
if (!mounted) return;
setState(() {
_protocolLoading = false;
_hasProtocolSelection = result.isOk();
if (result.isOk()) _protocol = result.unwrap();
});
}
Future<void> _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<TrainerModel>(
MaterialPageRoute(
builder: (_) =>
TrainerModelSearchPage(canSelect: _hasProtocolSelection)));
if (!mounted) return;
if (model != null) {
setState(() {
_protocol = model.id;
_modelName = model.name;
_showOnlyFtms = false;
});
}
await _startScan();
}
Future<void> _missingTrainer() async {
final search = await showDialog<bool>(
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<void> _startScan() async { Future<void> _startScan() async {
await _scanSubscription?.cancel(); await _scanSubscription?.cancel();
if (!mounted) return;
if (_isScanning) { if (_isScanning) {
await widget.shifter.stopTrainerScan(); await widget.shifter.stopTrainerScan();
} }
if (!mounted) return;
setState(() { setState(() {
_isStartingScan = true; _isStartingScan = true;
@ -70,6 +148,10 @@ class _BikeScanDialogState extends State<BikeScanDialog> {
); );
final startResult = await widget.shifter.startTrainerScan(); final startResult = await widget.shifter.startTrainerScan();
if (!mounted) {
if (startResult.isOk()) await widget.shifter.stopTrainerScan();
return;
}
if (startResult.isErr()) { if (startResult.isErr()) {
_scanError = startResult.unwrapErr().toString(); _scanError = startResult.unwrapErr().toString();
} else { } else {
@ -136,17 +218,51 @@ class _BikeScanDialogState extends State<BikeScanDialog> {
height: dialogHeight, height: dialogHeight,
child: Column( child: Column(
children: [ children: [
_DialogHeader( Expanded(
showOnlyFtms: _showOnlyFtms, child: CustomScrollView(slivers: [
isScanning: _isStartingScan || _isScanning, SliverToBoxAdapter(
onChanged: (value) { child: _DialogHeader(
setState(() { showOnlyFtms: _showOnlyFtms,
_showOnlyFtms = value; isScanning: _isStartingScan || _isScanning,
}); onChanged: (value) {
}, setState(() {
onRescan: _startScan, _showOnlyFtms = value;
), });
Expanded(child: _buildBody(context)), },
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<BikeScanDialog> {
Widget _buildBody(BuildContext context) { Widget _buildBody(BuildContext context) {
if (_scanError != null) { if (_scanError != null) {
return _ScanMessage( return SliverToBoxAdapter(
child: _ScanMessage(
message: 'Could not start shifter trainer scan: $_scanError', message: 'Could not start shifter trainer scan: $_scanError',
action: TextButton.icon( action: TextButton.icon(
onPressed: _startScan, onPressed: _startScan,
icon: const Icon(Icons.refresh), icon: const Icon(Icons.refresh),
label: const Text('Retry'), label: const Text('Retry'),
), ),
); ));
} }
if (_isStartingScan && _resultsByAddress.isEmpty) { 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(); final devices = _filteredDevices();
if (devices.isEmpty) { if (devices.isEmpty) {
return _ScanMessage( return SliverToBoxAdapter(
child: _ScanMessage(
message: _isScanning message: _isScanning
? 'The shifter is scanning. Nearby trainers will appear here as soon as the shifter reports them.' ? '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.', : '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), padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
itemCount: devices.length, sliver: SliverList(
separatorBuilder: (_, __) => const SizedBox(height: 12), delegate: SliverChildBuilderDelegate(
itemBuilder: (context, index) => _TrainerScanResultTile( (context, index) => Padding(
result: devices[index], padding: const EdgeInsets.only(bottom: 12),
onTap: () => Navigator.of(context).pop(devices[index]), child: _TrainerScanResultTile(
), result: devices[index],
onTap: () {
if (_protocolLoading) return;
Navigator.of(context).pop(TrainerAssignment(
devices[index],
_hasProtocolSelection ? _protocol : null));
},
)),
childCount: devices.length)),
); );
} }
List<TrainerScanResult> _filteredDevices() { List<TrainerScanResult> _filteredDevices() {
final devices = _resultsByAddress.values.where((device) { final devices = _resultsByAddress.values.where((device) {
return !_showOnlyFtms || device.ftmsDetected; return !_showOnlyFtms || device.supported;
}).toList(growable: false); }).toList(growable: false);
devices.sort((a, b) { 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) { if (ftmsCompare != 0) {
return ftmsCompare; return ftmsCompare;
} }
@ -258,21 +387,24 @@ class _DialogHeader extends StatelessWidget {
], ],
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
Row( Wrap(
spacing: 12,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [ children: [
Expanded( Row(
child: Row( mainAxisSize: MainAxisSize.min,
children: [ children: [
Text( Flexible(
'FTMS only', child: Text(
style: Theme.of(context).textTheme.bodyMedium?.copyWith( 'Supported trainers only',
fontWeight: FontWeight.w600, style: Theme.of(context).textTheme.bodyMedium?.copyWith(
), fontWeight: FontWeight.w600,
), ),
const SizedBox(width: 8), )),
Switch(value: showOnlyFtms, onChanged: onChanged), const SizedBox(width: 8),
], Switch(value: showOnlyFtms, onChanged: onChanged),
), ],
), ),
SizedBox( SizedBox(
width: 132, width: 132,
@ -312,7 +444,11 @@ class _TrainerScanResultTile extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme; final colorScheme = Theme.of(context).colorScheme;
final name = result.name.isEmpty ? 'Unknown Trainer' : result.name; 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); final addressText = _formatTrainerAddress(result.address);
return Material( return Material(
@ -416,7 +552,8 @@ class _ScanMessage extends StatelessWidget {
return Padding( return Padding(
padding: const EdgeInsets.all(20), padding: const EdgeInsets.all(20),
child: Center( child: Center(
child: Column( child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Text( Text(
@ -428,7 +565,7 @@ class _ScanMessage extends StatelessWidget {
SizedBox(width: 132, child: action!), SizedBox(width: 132, child: action!),
], ],
], ],
), )),
), ),
); );
} }

View File

@ -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<SimulationCard> createState() => _SimulationCardState();
}
class _SimulationCardState extends State<SimulationCard> {
final _form = GlobalKey<FormState>();
final _fields = List.generate(5, (_) => TextEditingController());
SimulationConfig _draft = const SimulationConfig();
Map<int, String> _models = {};
SimulationStatus? _status;
StreamSubscription<SimulationStatus>? _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<void> _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<int, String> 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<void> _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<SimulationPolicy>(
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<int>(
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<PowerPreviewChart> createState() => _PowerPreviewChartState();
}
class _PowerPreviewChartState extends State<PowerPreviewChart> {
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<double> 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;
}

View File

@ -92,6 +92,7 @@ flutter:
# - images/a_dot_burr.jpeg # - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg # - images/a_dot_ham.jpeg
assets: assets:
- assets/trainer_models.json
- assets/images/shifter-wireframe.png - assets/images/shifter-wireframe.png
- assets/images/gears/png/filled/ - assets/images/gears/png/filled/

View File

@ -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);
});
}

View File

@ -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);
});
}

View File

@ -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 = <String, List<int>>{
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 = <String>[];
final scan = StreamController<List<int>>.broadcast();
final simulation = StreamController<List<int>>.broadcast();
bool rejectWrites = false;
@override
Future<Result<List<int>>> 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<Result<void>> writeCharacteristic(
String deviceId, String serviceUuid, String uuid, List<int> value,
{bool withResponse = true}) async {
steps.add('write:$uuid');
if (!rejectWrites) values[uuid] = List.of(value);
return const Ok(null);
}
@override
Stream<List<int>> subscribeToCharacteristic(
String deviceId, String serviceUuid, String uuid) =>
uuid == universalShifterScanResultCharacteristicUuid
? scan.stream
: simulation.stream;
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
Future<void> close() async {
await scan.close();
await simulation.close();
}
}

190
test/trainer_ui_test.dart Normal file
View File

@ -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<FilledButton>(
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();
});
}

View File

@ -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}')