diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index b93f12045..01e1b80b6 100644 --- a/lib/state/app_state.dart +++ b/lib/state/app_state.dart @@ -4051,14 +4051,11 @@ class AppState extends ChangeNotifier { void releaseLiveHrView() => _liveStreamController.releaseLiveHrView(); - /// A bounded movement-reminder sampling window is open (IMU-only owner). - /// - /// There is NO scheduler yet, and enabling the movement-reminder preference - /// must not hold the IMU stream: sampling only inside bounded windows cannot - /// prove that movement did not happen between them, so a standing owner - /// would let the reminder claim an uninterrupted stillness it never - /// observed. A separately validated scheduler that can account for the gaps - /// is the only thing that should call this. + /// A bounded movement-sampling window is open (IMU-only owner). Driven by the + /// step-calibration routine (which needs the live count as feedback), and in + /// future by a validated movement-reminder scheduler. See + /// [LiveStreamController.setMovementSamplingWindow] for why the reminder + /// preference itself must not hold this. void setMovementSamplingWindow(bool active) => _liveStreamController.setMovementSamplingWindow(active); diff --git a/lib/state/live_stream_controller.dart b/lib/state/live_stream_controller.dart index 8b044bc24..78add4f7b 100644 --- a/lib/state/live_stream_controller.dart +++ b/lib/state/live_stream_controller.dart @@ -65,14 +65,19 @@ class LiveStreamController { nudge(); } - /// A bounded movement-reminder sampling window is open (IMU-only owner). + /// A bounded movement-sampling window is open (IMU-only owner). /// /// There is NO scheduler yet, and enabling the movement-reminder preference /// must not hold the IMU stream: sampling only inside bounded windows cannot /// prove that movement did not happen between them, so a standing owner /// would let the reminder claim an uninterrupted stillness it never /// observed. A separately validated scheduler that can account for the gaps - /// is the only thing that should call this. + /// is the only thing that should drive this FOR THE REMINDER. The + /// step-calibration screen is the other legitimate caller: a genuinely + /// bounded, user-watched routine that makes no stillness claim between + /// windows, so the gap concern does not apply to it — it needs the live + /// 100 Hz count as feedback while the routine runs and releases it at the + /// end (gen5 owns no IMU stream by default since #287). void setMovementSamplingWindow(bool active) { if (_movementSampling == active) return; _movementSampling = active; diff --git a/lib/ui2/profile/step_calibration.dart b/lib/ui2/profile/step_calibration.dart index a0695fc78..64761fc16 100644 --- a/lib/ui2/profile/step_calibration.dart +++ b/lib/ui2/profile/step_calibration.dart @@ -72,6 +72,12 @@ class _StepCalibrationScreenState extends State { bool _busy = false; + /// The [AppState] this screen asked to own the live IMU stream while a + /// routine runs. Held as a captured reference (not re-read from `context`) + /// so [dispose] can release it without touching an unmounted context (§4.5), + /// the same pattern the live-HR screens use for `retainLiveHrView`. + AppState? _imuOwner; + @override void initState() { super.initState(); @@ -81,9 +87,27 @@ class _StepCalibrationScreenState extends State { @override void dispose() { _ticker?.cancel(); + // Backstop for every exit path: leaving the window held would keep the + // 100 Hz IMU stream (and its battery cost) armed after the screen is gone. + _releaseImuWindow(); super.dispose(); } + /// The band's live step count this screen shows is the band's own 100 Hz IMU + /// stream. Since #287 a plain gen5 foreground owns no live stream, so the + /// routine must request the IMU stream explicitly through the bounded + /// movement-sampling owner, or the feedback count never leaves 0 (#1047). + void _retainImuWindow(AppState app) { + _imuOwner = app..setMovementSamplingWindow(true); + } + + /// Release the IMU window if one is held. Safe to call when nothing was + /// held, and idempotent, so every routine-ending path can call it (§4.3). + void _releaseImuWindow() { + _imuOwner?.setMovementSamplingWindow(false); + _imuOwner = null; + } + Future _loadProfiles() async { for (final c in StepCategory.values) { _profiles[c] = await LocalDb.liveStepGainProfile(c); @@ -132,6 +156,7 @@ class _StepCalibrationScreenState extends State { }; }); if (begun.session != null) { + _retainImuWindow(app); _ticker = Timer.periodic(Motion.tick, (_) => _tick()); } } @@ -206,6 +231,7 @@ class _StepCalibrationScreenState extends State { void _cancel() { _ticker?.cancel(); + _releaseImuWindow(); setState(() { _session = null; _routineStart = null; @@ -282,6 +308,10 @@ class _StepCalibrationScreenState extends State { // §4.5: `context` may not be used after an await without this. if (!mounted) return; final out = s.finish(countedSteps: counted); + // The band's counts are now read off the session; the routine is over on + // every branch below, so stop owning the live stream here. (An early + // `!mounted` return above leaves `dispose` to release it.) + _releaseImuWindow(); final l = AppLocalizations.of(context); if (out.bandSilent) { diff --git a/test/step_calibration_imu_stream_test.dart b/test/step_calibration_imu_stream_test.dart new file mode 100644 index 000000000..fa9fa5905 --- /dev/null +++ b/test/step_calibration_imu_stream_test.dart @@ -0,0 +1,131 @@ +// The band's live step count on the calibration screen is a direct readout of +// the band's own 100 Hz IMU stream. Since #287 a plain gen5 foreground owns no +// live stream, so unless the calibration routine explicitly requests the IMU +// stream the feedback count sits at 0 forever (#1047: "step count calibration +// not working" — live HR worked, steps stuck at 0, gen5 firmware 50.41). +// +// These tests pin the fix at the owner seam (what the screen asks the engine +// for), not the wire: starting a routine must make the app an owner of the IMU +// stream (`movementSampling`), and EVERY routine-ending path must release it — +// a sticky owner left armed is the §4.3 latch bug the repo keeps reintroducing. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +import 'package:openstrap_edge/ble/ble_engine.dart'; +import 'package:openstrap_edge/data/db.dart'; +import 'package:openstrap_edge/state/app_state.dart'; +import 'package:openstrap_edge/ui2/profile/step_calibration.dart'; +import 'package:openstrap_edge/ui2/ui2.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const name = 'step_calibration_imu_stream_test.db'; + + setUpAll(() async { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + await LocalDb.close(); + LocalDb.dbName = name; + await databaseFactory.deleteDatabase( + p.join(await databaseFactory.getDatabasesPath(), name), + ); + }); + + setUp(() { + SharedPreferences.setMockInitialValues({}); + BleEngine.resetBandClaimForTest(); + }); + tearDown(BleEngine.resetBandClaimForTest); + + tearDownAll(() async { + await LocalDb.close(); + await databaseFactory.deleteDatabase( + p.join(await databaseFactory.getDatabasesPath(), name), + ); + }); + + // initState kicks off `_loadProfiles`, four real sqflite reads on a + // background isolate. pumpAndSettle only drives the fake-async frame clock + // and would let those reads land after the test (against a closed DB), so + // flush the real async with runAsync — the pattern the MetricDetail test + // uses — before each test finishes. + Future settle(WidgetTester t) async { + for (var i = 0; i < 8; i++) { + await t.runAsync( + () => Future.delayed(const Duration(milliseconds: 20))); + await t.pump(const Duration(milliseconds: 16)); + } + } + + Future pump(WidgetTester t) async { + t.view.physicalSize = const Size(390 * 3, 2400 * 3); + t.view.devicePixelRatio = 3; + addTearDown(t.view.reset); + final app = AppState.forTesting(); + addTearDown(app.dispose); + await t.pumpWidget(MaterialApp( + theme: buildTheme(Brightness.light), + home: ChangeNotifierProvider.value( + value: app, + child: const StepCalibrationScreen(), + ), + )); + await settle(t); + return app; + } + + // Start a gait routine ("Slow walk"): its reference is the wearer, not the + // phone, so it touches no platform channel and starts cleanly in a test. + Future startSlowWalk(WidgetTester t) async { + await t.tap(find.text('Slow walk')); + // _start awaits beginCalibrationRoutine (no real async for gait) then arms + // the window and installs a 1 Hz ticker. Flush microtasks; do NOT + // pumpAndSettle — the periodic ticker never settles. + await t.pump(); + await t.pump(const Duration(milliseconds: 20)); + await settle(t); + } + + testWidgets('starting a routine makes the app own the live IMU stream', + (t) async { + final app = await pump(t); + expect(app.debugLiveOwners.movementSampling, isFalse, + reason: 'nothing owns the IMU stream before a routine starts'); + + await startSlowWalk(t); + expect(app.debugLiveOwners.movementSampling, isTrue, + reason: 'the running routine must request the IMU stream, or its ' + 'live band-step feedback never leaves 0 (#1047)'); + }); + + testWidgets('cancelling a routine releases the IMU stream', (t) async { + final app = await pump(t); + await startSlowWalk(t); + expect(app.debugLiveOwners.movementSampling, isTrue); + + await t.tap(find.text('Cancel')); + await t.pump(); + expect(app.debugLiveOwners.movementSampling, isFalse, + reason: 'the IMU owner must not stick past a cancelled routine (§4.3)'); + }); + + testWidgets('disposing the screen mid-routine releases the IMU stream', + (t) async { + final app = await pump(t); + await startSlowWalk(t); + expect(app.debugLiveOwners.movementSampling, isTrue); + + // Replace the screen with an empty route → the state is disposed. + await t.pumpWidget(const MaterialApp(home: SizedBox.shrink())); + await t.pump(); + expect(app.debugLiveOwners.movementSampling, isFalse, + reason: 'dispose is the backstop that frees the stream when the screen ' + 'is torn down mid-routine (§4.3)'); + }); +}