Files
swiftcontrol/lib/bluetooth/emulation/emulation_manager.dart
Jonas Bark db5cc74a12 fix(erg,sram): shared ERG stepping with boundary guards; scope §7 guard to shifting-enabled; coalesce iOS echo presses
ERG (review findings on the ±5W change):
- New ErgPowerStepping extension is the single home for the 5W step and
  500W manual cap, replacing 7 inline copies (physical buttons, hero-card
  buttons/slider, three overlay controllers).
- Boundaries are guards, not clamps: up at >=500W is a no-op like the
  disabled UI button (a 600W FTMS target is no longer slashed to 500),
  down from >500W steps relative, and an unknown baseline (hub-commanded
  ERG reports no target) is a no-op with a new localized message instead
  of slamming the trainer to ~150W.
- ERG shift-up Success carries the button again so +5W presses show
  activity feedback (missed conversion from 843f7985).

SRAM gesture:
- Same-lever repeats inside the 90ms combo window coalesce as duplicates:
  a finger can't re-press in 90ms, but iOS re-delivers a colliding read
  response of the 0xFF edge through the notify callback — it must not
  actuate twice (nor break a combo when it misdecodes to the other lever).
- The §7 multishift guard only runs while shifting is enabled — the one
  state where a held paddle actually bursts (per c94b87f0's --observe
  capture). Bonded rapid tapping and both-lever combos are never
  throttled. Timer-driven instead of DateTime.now() (deterministic under
  fakeAsync) and cleared by _resetGesture on (re)connect.
- The "set up SRAM control" warning fires once per connection, not on
  every undecoded press.

Harness:
- EmulationSession.notify drops notifications for removed peripherals so
  delayed notifies (SRAM double-tap) can't land after teardown.
- The 0xFF press edge is SramAxsConstants.triggerEdge at all call sites;
  the emulation test waits on the named TRIGGER_UUID constant.
- New coverage: guard behavior through processCharacteristic in both
  states, burst suppression while unbonded, all-taps-delivered once
  bonded, ERG boundary/game-set-target cases.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 17:51:35 +02:00

105 lines
3.7 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:universal_ble/universal_ble.dart';
import 'emulated_ble_platform.dart';
import 'emulation_profile.dart';
/// Retained entry cap for [EmulationSession.writeLog].
const _maxWriteLogEntries = 100;
/// A live emulated device: its peripheral, profile, decoded write log and the
/// interactive inputs bound to it.
class EmulationSession {
EmulationSession({required this.profile, required this.peripheral, required this.ble}) {
profile.onRegistered?.call(ble, peripheral);
final scripted = peripheral.onWrite;
peripheral.onWrite = (service, characteristic, value) {
scripted?.call(service, characteristic, value);
final decoded = profile.decodeWrite?.call(characteristic.toLowerCase(), value);
if (decoded != null) {
final updated = [...writeLog.value, decoded];
// Incline writes stream continuously for the ride's duration; cap
// retained entries so a long ride doesn't grow this unbounded.
writeLog.value = updated.length > _maxWriteLogEntries
? updated.sublist(updated.length - _maxWriteLogEntries)
: updated;
}
};
inputs = profile.inputs?.call(this) ?? const [];
}
final EmulationProfile profile;
final FakePeripheral peripheral;
final FakeUniversalBlePlatform ble;
final ValueNotifier<List<String>> writeLog = ValueNotifier(const []);
late final List<EmulatedInput> inputs;
/// Delivers a notification unless the peripheral has been removed — profiles
/// fire DELAYED notifies (e.g. the SRAM double-tap's second edge, 100ms
/// late), and a dangling one must not reach the app after the session was
/// stopped: it would register a phantom press post-teardown.
void notify(String characteristicUuid, List<int> bytes) {
if (!ble.peripherals.containsKey(peripheral.deviceId)) return;
ble.notify(peripheral.deviceId, characteristicUuid, bytes);
}
void dropConnection() => ble.dropConnection(peripheral.deviceId);
/// Re-emits the scan result with a different RSSI (drives the signal UI).
void setRssi(int rssi) {
final base = peripheral.scanResult;
ble.updateScanResult(
BleDevice(
deviceId: base.deviceId,
name: peripheral.name,
rssi: rssi,
services: base.services,
manufacturerDataList: base.manufacturerDataList,
),
);
}
}
/// Owns the emulated peripherals in debug builds. Never attached in release
/// builds, so it stays inert there.
class EmulationManager {
FakeUniversalBlePlatform? _ble;
final Map<String, EmulationSession> _sessions = {};
bool get isAvailable => _ble != null;
/// The fake platform the emulated peripherals live on. Only valid when
/// [isAvailable].
FakeUniversalBlePlatform get ble => _ble!;
void attach(FakeUniversalBlePlatform ble) => _ble = ble;
List<EmulationSession> get sessions => _sessions.values.toList();
EmulationSession start(EmulationProfile profile) {
final ble = _ble;
if (ble == null) throw StateError('EmulationManager.attach was never called');
final peripheral = profile.build();
final existing = _sessions[peripheral.deviceId];
if (existing != null) return existing;
final session = EmulationSession(profile: profile, peripheral: peripheral, ble: ble);
_sessions[peripheral.deviceId] = session;
ble.addPeripheral(peripheral);
return session;
}
bool isEmulated(String deviceId) => _sessions.containsKey(deviceId);
EmulationSession? sessionFor(String deviceId) => _sessions[deviceId];
void stop(String deviceId) {
_sessions.remove(deviceId);
_ble?.removePeripheral(deviceId);
}
/// Test hook: drop all sessions (the fake platform's own reset() clears the
/// peripherals).
@visibleForTesting
void reset() => _sessions.clear();
}