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

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

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/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<DeviceDetailsPage> {
}
_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<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(
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) ...[
_PairingRequiredCard(
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: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<Result<void>> connectButtonToTrainer(
TrainerAddress trainerAddress,
) async {
Future<Result<void>> 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<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 {
final readRes = await _requireBluetooth.readCharacteristic(
buttonDeviceId,

View File

@ -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<TrainerScanResult?> show(
static Future<TrainerAssignment?> show(
BuildContext context, {
required ShifterService shifter,
}) {
return showDialog<TrainerScanResult>(
return showDialog<TrainerAssignment>(
context: context,
barrierDismissible: true,
builder: (_) => BikeScanDialog(shifter: shifter),
@ -34,18 +42,88 @@ class _BikeScanDialogState extends State<BikeScanDialog> {
String? _scanError;
final Map<String, TrainerScanResult> _resultsByAddress = {};
StreamSubscription<TrainerScanEvent>? _scanSubscription;
bool _protocolLoading = true;
bool _hasProtocolSelection = false;
String _protocol = 'auto';
String? _modelName;
@override
void initState() {
super.initState();
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 {
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<BikeScanDialog> {
);
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<BikeScanDialog> {
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<BikeScanDialog> {
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<TrainerScanResult> _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!),
],
],
),
)),
),
);
}

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