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

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