feat: basic trainer support
This commit is contained in:
@ -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
183
lib/model/simulation.dart
Normal 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';
|
||||
}
|
||||
}
|
||||
94
lib/model/trainer_model.dart
Normal file
94
lib/model/trainer_model.dart
Normal 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(', ');
|
||||
}
|
||||
Reference in New Issue
Block a user