fix(sram): reconnect when setup/restore finds the link unresponsive

A GATT call that never completes (universal_ble's 10 s timeout) during
SRAM setup/restore left the connection wedged: every retry on the same
link timed out again, the bond handshake included, and the guided sheet
then asked the rider to hold the AXS button, which can't help.

- setupControl/restoreShifting: on a timeout (plain, or a bond handshake
  that timed out waiting for the derailleur) tear the link down through
  Connection.disconnect + rescan, the same path a genuine drop takes.
  isResetting keeps this instance listed so the rescan reconnects it and
  the open sheet retries on the fresh link. A create-bond decrypt failure
  (authorization refused) leaves the link up. The saved backup and key
  are never touched; the error is still rethrown.
- Guided sheet: a link timeout now shows an error explaining that the
  derailleur is reconnecting instead of the authorize hero.
- SramBleTransport: read/write/subscribe failures carry the operation
  and characteristic UUID ("... (read d905ee53-...)"); timeouts stay
  TimeoutException, other errors become SramTransportException(cause).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jonas Acker
2026-10-12 19:47:42 +02:00
parent e4b459a460
commit 07f388bbe0
14 changed files with 420 additions and 15 deletions

View File

@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:bike_control/bluetooth/messages/notification.dart';
import 'package:bike_control/main.dart' show recordError;
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/i18n_extension.dart';
import 'package:bike_control/utils/keymap/buttons.dart';
@@ -17,6 +18,7 @@ import 'package:universal_ble/universal_ble.dart';
import '../bluetooth_device.dart';
import 'sram_ble_transport.dart';
import 'sram_link_errors.dart';
import 'sram_setup_sheet.dart';
class SramAxs extends BluetoothDevice {
@@ -30,6 +32,16 @@ class SramAxs extends BluetoothDevice {
SramAxsLogic? _logic;
Timer? _keepAliveTimer;
/// Set when setup/restore found the link wedged (see [_resetWedgedLink])
/// and tore it down; cleared once the device is back ([handleServices]).
/// While set the entry stays listed (greyed) and Connection re-queues this
/// same instance when the scan sees the derailleur again — so the guided
/// sheet, which holds this instance, retries on the fresh link.
bool _linkResetting = false;
@override
bool get isResetting => _linkResetting;
/// Logged once per connection when a press can't be decoded, so it's clear
/// from the logs whether the session key is active this session.
bool _loggedDegradedPress = false;
@@ -165,6 +177,7 @@ class SramAxs extends BluetoothDevice {
@override
Future<void> handleServices(List<BleService> services) async {
_resetGesture(); // clear any gesture timers/state left over from a prior connection
_linkResetting = false; // back on a fresh link
final transport = SramBleTransport(device.deviceId, services);
final logic = SramAxsLogic(transport);
_transport = transport;
@@ -381,6 +394,7 @@ class SramAxs extends BluetoothDevice {
final logic = _logic;
if (logic == null) return;
try {
if (_linkResetting) throw const SramLinkResettingException();
// Ensure a working bond (re-bonds if a persisted key went stale).
await logic.ensureBonded();
await core.settings.setSramKey(_serialKey, _bytesToHex(logic.sessionKey!));
@@ -396,6 +410,7 @@ class SramAxs extends BluetoothDevice {
core.connection.signalChange(this);
} catch (e, st) {
actionStreamInternal.add(LogNotification('SramAxs setup failed: $e\n$st'));
await _resetWedgedLink(e);
rethrow;
}
}
@@ -405,6 +420,7 @@ class SramAxs extends BluetoothDevice {
final backup = core.settings.getSramBackup(_serialKey);
if (logic == null || backup == null) return;
try {
if (_linkResetting) throw const SramLinkResettingException();
await logic.restoreConfig(backup);
await core.settings.setSramKey(_serialKey, _bytesToHex(logic.sessionKey!)); // persist any re-bond
await core.settings.setSramShiftingDisabled(_serialKey, false);
@@ -412,10 +428,33 @@ class SramAxs extends BluetoothDevice {
core.connection.signalChange(this);
} catch (e, st) {
actionStreamInternal.add(LogNotification('SramAxs restore failed: $e\n$st'));
await _resetWedgedLink(e);
rethrow;
}
}
/// A GATT call or the bond handshake timing out means the derailleur stopped
/// answering on this connection, and every later attempt on it times out
/// too — it never recovers without a reconnect. So tear the link down the
/// same way a genuine drop is handled (Connection.disconnect + a rescan),
/// with [isResetting] keeping this instance listed so the rescan reconnects
/// it rather than creating a new one. A refused authorization
/// (`create-bond decrypt failed`) is not a link problem and leaves it up.
/// The persisted backup/key are untouched.
Future<void> _resetWedgedLink(Object error) async {
if (error is SramLinkResettingException || !isSramLinkUnresponsive(error) || !isConnected) return;
_linkResetting = true;
actionStreamInternal.add(
LogNotification('SramAxs: derailleur stopped responding on this connection — reconnecting for a fresh link'),
);
try {
await core.connection.disconnect(this, forget: false, persistForget: false);
unawaited(core.connection.performScanning());
} catch (e, st) {
await recordError(e, st, context: 'SramAxs: resetting an unresponsive link');
}
}
bool get isBonded => _logic?.isBonded ?? false;
bool get isShiftingDisabled => core.settings.getSramShiftingDisabled(_serialKey);

View File

@@ -5,9 +5,29 @@ import 'package:dartx/dartx.dart';
import 'package:prop/prop.dart';
import 'package:universal_ble/universal_ble.dart';
/// A non-timeout GATT failure from [SramBleTransport], annotated with the
/// operation and characteristic that failed so a diagnostics line says what
/// broke (`… (read d905ee53-…)`). The original error stays in [cause].
class SramTransportException implements Exception {
SramTransportException(this.operation, this.characteristic, this.cause);
final String operation;
final String characteristic;
final Object cause;
@override
String toString() => '$cause ($operation $characteristic)';
}
/// `universal_ble`-backed [SramTransport]. Notifications flow through the app's
/// existing pipeline; the owning device calls [onNotification] from its
/// `processCharacteristic` callback.
///
/// Every GATT call rethrows its failure with the operation and characteristic
/// attached. A [TimeoutException] (universal_ble gives up on a command after
/// 10 s) stays a [TimeoutException] — `SramAxs` keys its wedged-link recovery
/// off the type — with the context appended to its message; anything else is
/// wrapped in a [SramTransportException].
class SramBleTransport implements SramTransport {
SramBleTransport(this.deviceId, this.services);
@@ -28,26 +48,43 @@ class SramBleTransport implements SramTransport {
.firstOrNullWhere((s) => s.characteristics.any((c) => c.uuid == characteristic.toLowerCase()))
?.uuid;
Future<T> _withContext<T>(String operation, String characteristic, Future<T> Function() call) async {
try {
return await call();
} on TimeoutException catch (e, st) {
final message = '${e.message ?? 'timed out'} ($operation $characteristic)';
Error.throwWithStackTrace(TimeoutException(message, e.duration), st);
} catch (e, st) {
Error.throwWithStackTrace(SramTransportException(operation, characteristic, e), st);
}
}
@override
Future<void> subscribe(String characteristic) async {
final service = _serviceFor(characteristic);
final char = characteristic.toLowerCase();
final service = _serviceFor(char);
if (service == null) return;
await UniversalBle.subscribeNotifications(deviceId, service, characteristic.toLowerCase());
await _withContext('subscribe', char, () => UniversalBle.subscribeNotifications(deviceId, service, char));
}
@override
Future<void> write(String characteristic, Uint8List data, {bool withoutResponse = false}) async {
final service = _serviceFor(characteristic);
final char = characteristic.toLowerCase();
final service = _serviceFor(char);
if (service == null) throw StateError('SRAM: no service for $characteristic');
await UniversalBle.write(deviceId, service, characteristic.toLowerCase(), data,
withoutResponse: withoutResponse);
await _withContext(
'write',
char,
() => UniversalBle.write(deviceId, service, char, data, withoutResponse: withoutResponse),
);
}
@override
Future<Uint8List> read(String characteristic) async {
final service = _serviceFor(characteristic);
final char = characteristic.toLowerCase();
final service = _serviceFor(char);
if (service == null) throw StateError('SRAM: no service for $characteristic');
return UniversalBle.read(deviceId, service, characteristic.toLowerCase());
return _withContext('read', char, () => UniversalBle.read(deviceId, service, char));
}
@override

View File

@@ -0,0 +1,33 @@
import 'dart:async';
import 'package:prop/prop.dart' show SramBondException;
/// Thrown when setup/restore is attempted while `SramAxs` is still
/// re-establishing a link it tore down because the derailleur stopped
/// answering. Retrying once the device shows as connected again works.
class SramLinkResettingException implements Exception {
const SramLinkResettingException();
@override
String toString() => 'SramLinkResettingException: reconnecting to the derailleur, retry once it is connected';
}
/// Whether [error] means the BLE link to the derailleur stopped answering —
/// as opposed to the derailleur answering with a refusal.
///
/// - a GATT read/write/subscribe that never completed (universal_ble's
/// queue raises a [TimeoutException], see `SramBleTransport`);
/// - a bond handshake that timed out waiting for the derailleur's reply
/// (prop wraps it as `SramBondException('handshake failed: TimeoutException…')`);
/// - an attempt refused because such a link is still being reset.
///
/// A `create-bond decrypt failed` bond error is NOT a link problem: the
/// derailleur replied, it just wasn't authorized (AXS button not held).
bool isSramLinkUnresponsive(Object error) {
if (error is TimeoutException || error is SramLinkResettingException) return true;
if (error is SramBondException) {
final message = error.message;
return message.startsWith('handshake failed:') && message.contains('TimeoutException');
}
return false;
}

View File

@@ -4,6 +4,8 @@ import 'package:bike_control/widgets/ui/type_scale.dart';
import 'package:prop/prop.dart' show SramBondException;
import 'package:shadcn_flutter/shadcn_flutter.dart';
import 'sram_link_errors.dart';
/// The staged setup/restore bottom-sheet UI for [SramAxs]. Kept out of the
/// device file so that stays focused on device/BLE logic. The reusable
/// building blocks (step rail, stage badge, progress checklist) live in
@@ -56,20 +58,35 @@ class SramGuidedSheet extends StatefulWidget {
class _SramGuidedSheetState extends State<SramGuidedSheet> {
var _stage = SramSetupStage.confirm;
/// Error-stage body override; null → the generic error copy.
String? _errorMessage;
Future<void> _attempt() async {
setState(() => _stage = SramSetupStage.running);
try {
await widget.operation();
if (!mounted) return;
setState(() => _stage = SramSetupStage.success);
} on SramBondException {
// A fresh bond is needed (no valid key). Only NOW do we ask the user to
// authorize — when already bonded this never shows.
} catch (e) {
// The operation already logged the failure (and, for a wedged link,
// started the reconnect); here we only pick what to tell the rider.
if (!mounted) return;
setState(() => _stage = SramSetupStage.authorize);
} catch (_) {
if (!mounted) return;
setState(() => _stage = SramSetupStage.error);
setState(() {
if (isSramLinkUnresponsive(e)) {
// The derailleur stopped answering (including a bond handshake that
// timed out) — holding the AXS button won't help; the link is being
// re-established, so say that and let them retry once it's back.
_stage = SramSetupStage.error;
_errorMessage = context.i18n.sramLinkResetError;
} else if (e is SramBondException) {
// A fresh bond is needed (no valid key). Only NOW do we ask the user
// to authorize — when already bonded this never shows.
_stage = SramSetupStage.authorize;
} else {
_stage = SramSetupStage.error;
_errorMessage = null;
}
});
}
}
@@ -102,6 +119,7 @@ class _SramGuidedSheetState extends State<SramGuidedSheet> {
runningTitle: widget.runningTitle,
successTitle: widget.successTitle,
checklistItems: widget.checklistItems,
errorMessage: _errorMessage,
onClose: () => closeSheet(context),
onProceed: _attempt,
),
@@ -130,6 +148,7 @@ Widget sramGuidedBody(
required VoidCallback onProceed,
int runningStep = 0,
bool checklistAutoAdvance = true,
String? errorMessage,
}) {
final scheme = Theme.of(context).colorScheme;
final l = context.i18n;
@@ -208,7 +227,7 @@ Widget sramGuidedBody(
tone = scheme.destructive;
wash = dark ? const Color(0x1AEF4444) : _sramErrorWash;
heading = l.sramErrorTitle;
body = l.sramGenericError;
body = errorMessage ?? l.sramGenericError;
stepIndex = null;
extra = null;
actions = [

View File

@@ -1167,6 +1167,7 @@
"sramAuthorizeBody": "Halte die AXS-Taste an deinem Schaltwerk gedrückt, bis die Leuchte blinkt, und tippe dann auf Erneut versuchen.",
"sramErrorTitle": "Das hat nicht geklappt",
"sramGenericError": "Etwas ist schiefgelaufen. Bitte versuche es erneut.",
"sramLinkResetError": "Das Schaltwerk hat nicht mehr geantwortet, deshalb verbindet sich BikeControl neu. Warte, bis es wieder als verbunden angezeigt wird, und versuche es dann erneut.",
"sramShiftingOff": "Geräteinternes Schalten ist aus – BikeControl steuert deine Gänge.",
"sramSettingUp": "Wird eingerichtet",
"sramRestoringShifting": "Schaltung wird wiederhergestellt",

View File

@@ -1766,6 +1766,7 @@
"sramAuthorizeBody": "Hold the AXS button on your derailleur until its light flashes, then tap Retry.",
"sramErrorTitle": "That didn't work",
"sramGenericError": "Something went wrong. Please try again.",
"sramLinkResetError": "The derailleur stopped responding, so BikeControl is reconnecting to it. Wait until it shows as connected again, then retry.",
"sramShiftingOff": "On-device shifting is off — BikeControl controls your gears.",
"sramSettingUp": "Setting up",
"sramRestoringShifting": "Restoring shifting",

View File

@@ -1155,6 +1155,7 @@
"sramAuthorizeBody": "Mantén pulsado el botón AXS de tu cambio trasero hasta que su luz parpadee y luego toca Reintentar.",
"sramErrorTitle": "No ha funcionado",
"sramGenericError": "Algo ha salido mal. Inténtalo de nuevo.",
"sramLinkResetError": "El desviador ha dejado de responder, así que BikeControl se está volviendo a conectar. Espera a que aparezca de nuevo como conectado y vuelve a intentarlo.",
"sramShiftingOff": "El cambio del dispositivo está desactivado: BikeControl controla tus marchas.",
"sramSettingUp": "Configurando",
"sramRestoringShifting": "Restaurando el cambio",

View File

@@ -1155,6 +1155,7 @@
"sramAuthorizeBody": "Maintiens le bouton AXS de ton dérailleur jusqu'à ce que sa lumière clignote, puis touche Réessayer.",
"sramErrorTitle": "Ça n'a pas fonctionné",
"sramGenericError": "Une erreur s'est produite. Veuillez réessayer.",
"sramLinkResetError": "Le dérailleur ne répond plus, BikeControl s'y reconnecte. Attendez qu'il apparaisse de nouveau comme connecté, puis réessayez.",
"sramShiftingOff": "Le passage des vitesses du dérailleur est désactivé – BikeControl contrôle vos vitesses.",
"sramSettingUp": "Configuration en cours",
"sramRestoringShifting": "Restauration en cours",

View File

@@ -1155,6 +1155,7 @@
"sramAuthorizeBody": "Tieni premuto il pulsante AXS sul deragliatore finché la spia lampeggia, poi tocca Riprova.",
"sramErrorTitle": "Non ha funzionato",
"sramGenericError": "Qualcosa è andato storto. Riprova.",
"sramLinkResetError": "Il deragliatore ha smesso di rispondere, quindi BikeControl si sta riconnettendo. Attendi che risulti di nuovo connesso, poi riprova.",
"sramShiftingOff": "Il cambio integrato è disattivato: BikeControl controlla i tuoi rapporti.",
"sramSettingUp": "Configurazione in corso",
"sramRestoringShifting": "Ripristino del cambio",

View File

@@ -1155,6 +1155,7 @@
"sramAuthorizeBody": "Przytrzymaj przycisk AXS na przerzutce, aż zamiga jej dioda, a potem dotknij Ponów.",
"sramErrorTitle": "Nie udało się",
"sramGenericError": "Coś poszło nie tak. Spróbuj ponownie.",
"sramLinkResetError": "Przerzutka przestała odpowiadać, więc BikeControl łączy się z nią ponownie. Poczekaj, aż znów będzie widoczna jako połączona, i spróbuj ponownie.",
"sramShiftingOff": "Przełączanie w urządzeniu jest wyłączone — BikeControl steruje biegami.",
"sramSettingUp": "Konfigurowanie",
"sramRestoringShifting": "Przywracanie przełączania",

View File

@@ -1,5 +1,8 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:bike_control/bluetooth/devices/sram/sram_ble_transport.dart';
import 'package:bike_control/bluetooth/emulation/emulated_ble_platform.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:universal_ble/universal_ble.dart';
@@ -8,6 +11,36 @@ BleService _svc(String uuid, List<BleCharacteristic> chars) => BleService(uuid,
BleCharacteristic _char(String uuid, List<CharacteristicProperty> props) =>
BleCharacteristic(uuid, props, const []);
/// A BLE platform whose GATT calls fail like a wedged link: they throw the
/// same TimeoutException universal_ble's command queue raises after 10 s.
class _WedgedPlatform extends FakeUniversalBlePlatform {
_WedgedPlatform(this.error);
final Object error;
@override
Future<Uint8List> readValue(String deviceId, String service, String characteristic, {Duration? timeout}) async =>
throw error;
@override
Future<void> writeValue(
String deviceId,
String service,
String characteristic,
Uint8List value,
BleOutputProperty bleOutputProperty,
) async =>
throw error;
@override
Future<void> setNotifiable(
String deviceId,
String service,
String characteristic,
BleInputProperty bleInputProperty,
) async =>
throw error;
}
void main() {
test('lists read+write characteristics only', () {
final services = [
@@ -28,4 +61,58 @@ void main() {
t.onNotification(char, Uint8List.fromList([1, 2, 3]));
expect(await future, [1, 2, 3]);
});
group('transport errors name the operation and characteristic', () {
const svc = 'd905ee51-90aa-4c7c-b036-1e01fb8eb7ee';
const char = 'd905ee53-90aa-4c7c-b036-1e01fb8eb7ee';
final services = [
_svc(svc, [
_char(char, [CharacteristicProperty.read, CharacteristicProperty.write, CharacteristicProperty.notify]),
]),
];
final timeout = TimeoutException('Future not completed', const Duration(seconds: 10));
setUp(() => UniversalBle.setInstance(_WedgedPlatform(timeout)));
test('read timeout stays a TimeoutException and says what hung', () async {
final t = SramBleTransport('dev1', services);
await expectLater(
t.read(char.toUpperCase()),
throwsA(
isA<TimeoutException>()
.having((e) => e.duration, 'duration', const Duration(seconds: 10))
.having((e) => e.toString(), 'message', contains('(read $char)')),
),
);
});
test('write timeout says what hung', () async {
final t = SramBleTransport('dev1', services);
await expectLater(
t.write(char, Uint8List.fromList([1])),
throwsA(isA<TimeoutException>().having((e) => e.toString(), 'message', contains('(write $char)'))),
);
});
test('subscribe timeout says what hung', () async {
final t = SramBleTransport('dev1', services);
await expectLater(
t.subscribe(char),
throwsA(isA<TimeoutException>().having((e) => e.toString(), 'message', contains('(subscribe $char)'))),
);
});
test('a non-timeout failure keeps its cause and gains the context', () async {
UniversalBle.setInstance(_WedgedPlatform(StateError('gatt boom')));
final t = SramBleTransport('dev1', services);
await expectLater(
t.read(char),
throwsA(
isA<SramTransportException>()
.having((e) => e.cause, 'cause', isA<StateError>())
.having((e) => e.toString(), 'message', allOf(contains('gatt boom'), contains('(read $char)'))),
),
);
});
});
}

View File

@@ -0,0 +1,46 @@
import 'dart:async';
import 'package:bike_control/bluetooth/devices/sram/sram_ble_transport.dart';
import 'package:bike_control/bluetooth/devices/sram/sram_link_errors.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:prop/prop.dart' show SramBondException;
void main() {
group('isSramLinkUnresponsive', () {
test('a plain GATT timeout means the link is wedged', () {
expect(isSramLinkUnresponsive(TimeoutException('Future not completed', const Duration(seconds: 10))), isTrue);
});
test('a handshake that timed out waiting for the derailleur means the link is wedged', () {
final e = SramBondException(
'handshake failed: TimeoutException after 0:00:15.000000: Future not completed\n#0 stack',
);
expect(isSramLinkUnresponsive(e), isTrue);
});
test('a create-bond decrypt failure is the authorize case, not a wedged link', () {
final e = SramBondException(
'create-bond decrypt failed — press and hold the AXS button to authorize this device, then retry.',
);
expect(isSramLinkUnresponsive(e), isFalse);
});
test('a handshake that failed for a non-timeout reason is not treated as wedged', () {
expect(isSramLinkUnresponsive(SramBondException('handshake failed: PlatformException(x)')), isFalse);
});
test('a transport error wrapping a non-timeout cause is not treated as wedged', () {
final e = SramTransportException('read', 'd905ee53-90aa-4c7c-b036-1e01fb8eb7ee', PlatformException(code: 'x'));
expect(isSramLinkUnresponsive(e), isFalse);
});
test('an operation refused while the link is being reset counts as a link problem', () {
expect(isSramLinkUnresponsive(const SramLinkResettingException()), isTrue);
});
test('unrelated errors are not link problems', () {
expect(isSramLinkUnresponsive(StateError('SRAM: not bonded')), isFalse);
});
});
}

View File

@@ -0,0 +1,64 @@
import 'dart:async';
import 'package:bike_control/bluetooth/devices/sram/sram_setup_sheet.dart';
import 'package:bike_control/gen/l10n.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:prop/prop.dart' show SramBondException;
import 'package:shadcn_flutter/shadcn_flutter.dart';
/// Which stage the guided sheet lands on for each way setup can fail: only a
/// refused authorization asks the rider to hold the AXS button; a link that
/// stopped answering says it is reconnecting instead.
void main() {
Future<void> runWith(WidgetTester tester, Object error) async {
await tester.pumpWidget(
ShadcnApp(
localizationsDelegates: const [AppLocalizations.delegate],
supportedLocales: AppLocalizations.delegate.supportedLocales,
home: Scaffold(
child: SramGuidedSheet(
title: 'Set up',
intro: 'intro',
successMessage: 'ok',
confirmIcon: LucideIcons.slidersHorizontal,
runningTitle: 'running',
successTitle: 'done',
checklistItems: const ['a', 'b'],
operation: () async => throw error,
),
),
),
);
await tester.pump();
await tester.tap(find.text(AppLocalizations.current.continueAction));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
}
testWidgets('decrypt failed → authorize (hold the AXS button)', (tester) async {
await runWith(tester, SramBondException('create-bond decrypt failed — press and hold the AXS button'));
expect(find.text(AppLocalizations.current.sramAuthorizeTitle), findsOneWidget);
expect(find.text(AppLocalizations.current.sramLinkResetError), findsNothing);
});
testWidgets('handshake timeout → reconnecting error, not the authorize hero', (tester) async {
await runWith(
tester,
SramBondException('handshake failed: TimeoutException after 0:00:15.000000: Future not completed'),
);
expect(find.text(AppLocalizations.current.sramAuthorizeTitle), findsNothing);
expect(find.text(AppLocalizations.current.sramErrorTitle), findsOneWidget);
expect(find.text(AppLocalizations.current.sramLinkResetError), findsOneWidget);
});
testWidgets('plain GATT timeout → reconnecting error', (tester) async {
await runWith(tester, TimeoutException('Future not completed (write d9050028)', const Duration(seconds: 10)));
expect(find.text(AppLocalizations.current.sramLinkResetError), findsOneWidget);
});
testWidgets('any other failure → generic error', (tester) async {
await runWith(tester, StateError('boom'));
expect(find.text(AppLocalizations.current.sramGenericError), findsOneWidget);
expect(find.text(AppLocalizations.current.sramLinkResetError), findsNothing);
});
}

View File

@@ -1,4 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:bike_control/bluetooth/devices/sram/sram_axs.dart' show SramAxs;
import 'package:bike_control/bluetooth/emulation/emulated_ble_platform.dart';
@@ -141,6 +143,78 @@ Future<void> main() async {
expect(core.settings.getSramBackup(derailleur.deviceId), isNull, reason: 'restore clears the backup for a fresh future capture');
});
test('a GATT timeout while clearing the shifting config resets the link so a retry runs on a fresh one', () async {
final (derailleur, device) = await connectSram();
final reactionChars = {prop.SramAxs.reactionChar1.toLowerCase(), prop.SramAxs.reactionChar2.toLowerCase()};
// The derailleur stops answering config writes, exactly like a wedged
// link: universal_ble's queue gives up after 10 s with a TimeoutException.
var wedged = true;
derailleur.peripheral.onWrite = (service, characteristic, value) {
if (wedged && reactionChars.contains(characteristic.toLowerCase())) {
throw TimeoutException('Future not completed', const Duration(seconds: 10));
}
derailleur.fake.handleWrite(service, characteristic, value);
};
await expectLater(
device.setupControl(),
throwsA(isA<TimeoutException>().having((e) => e.toString(), 'message', contains('(write '))),
);
expect(device.isShiftingDisabled, isFalse);
final backup = core.settings.getSramBackup(derailleur.deviceId);
expect(backup, isNotNull, reason: 'the original config captured before the hang must survive');
// The wedged link is torn down; the same device entry stays listed and is
// reconnected by the regular rediscovery path.
expect(device.isResetting, isTrue);
await IntegrationEnv.waitFor(() => !derailleur.peripheral.isConnected, description: 'wedged link torn down');
expect(core.connection.devices, contains(device));
wedged = false;
// The still-running scan sees the derailleur advertising again.
env.ble.updateScanResult(derailleur.peripheral.scanResult);
await IntegrationEnv.waitFor(
() => device.isConnected && !device.isResetting,
description: 'same device reconnected on a fresh link',
);
await device.setupControl();
expect(device.isShiftingDisabled, isTrue);
expect(derailleur.derailleurUnassigned, isTrue);
expect(
jsonEncode(core.settings.getSramBackup(derailleur.deviceId)!.map((k, v) => MapEntry(k, v.toJson()))),
jsonEncode(backup!.map((k, v) => MapEntry(k, v.toJson()))),
reason: 'the retry must not overwrite the saved backup',
);
});
test('a refused authorization (create-bond decrypt failed) keeps the connection up', () async {
final (derailleur, device) = await connectSram();
final bondChar = prop.SramAxs.bondChar.toLowerCase();
bool isInit(List<int> v) => v.length == 16 && [for (var i = 0; i < 16; i++) v[i] == i].every((b) => b);
// AXS button not held: the derailleur answers the app's public key with a
// create-bond frame that doesn't decrypt.
derailleur.peripheral.onWrite = (service, characteristic, value) {
if (characteristic.toLowerCase() == bondChar && value.length == 16 && !isInit(value)) {
env.ble.notify(derailleur.deviceId, prop.SramAxs.bondChar, Uint8List(48));
return;
}
derailleur.fake.handleWrite(service, characteristic, value);
};
await expectLater(
device.setupControl(),
throwsA(isA<prop.SramBondException>().having((e) => e.message, 'message', contains('decrypt failed'))),
);
// Give a (wrongly) triggered disconnect time to land (the fake platform
// delivers it 400 ms later).
await Future<void>.delayed(const Duration(milliseconds: 600));
expect(device.isResetting, isFalse);
expect(derailleur.peripheral.isConnected, isTrue);
expect(device.isConnected, isTrue);
});
// NOTE on trigger semantics: SramAxs no longer resolves its own tap-count
// gesture. It emits ONE physical button press (down + release) per 0xFF
// trigger, identified by (serial, mask), and lets BaseDevice's shared