From f31f19518727ad8ecc94e822a640a50076233b3a Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Wed, 16 Sep 2026 22:35:40 +0200 Subject: [PATCH] Keep the morning going after the ring: weigh-in, shower, dress, desk, or it rings again Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 46 ++-- DOCS-morning-session.md | 123 +++++++++ DOCS-phone-alarm.md | 24 ++ .../com/kuhy/wake_alarm_sync/AlarmActivity.kt | 10 + .../com/kuhy/wake_alarm_sync/AlarmChannel.kt | 28 ++ .../com/kuhy/wake_alarm_sync/AlarmReceiver.kt | 8 + .../kuhy/wake_alarm_sync/AlarmScheduler.kt | 77 ++++++ .../com/kuhy/wake_alarm_sync/AlarmVolume.kt | 17 +- .../com/kuhy/wake_alarm_sync/BootReceiver.kt | 12 +- .../com/kuhy/wake_alarm_sync/MotionMonitor.kt | 77 ++++++ phone_app/lib/main.dart | 20 +- phone_app/lib/main_session_probe.dart | 32 +++ .../lib/probe/file_driven_scheduler.dart | 76 ++++++ phone_app/lib/screens/home_body.dart | 7 + phone_app/lib/screens/home_history_card.dart | 91 +++++++ phone_app/lib/screens/ring_screen.dart | 44 +++- phone_app/lib/screens/session_body.dart | 126 +++++++++ phone_app/lib/screens/session_checklist.dart | 80 ++++++ phone_app/lib/screens/session_screen.dart | 237 +++++++++++++++++ .../lib/screens/session_tags_screen.dart | 135 ++++++++++ phone_app/lib/screens/settings_screen.dart | 10 + phone_app/lib/services/alarm_scheduler.dart | 50 +++- phone_app/lib/services/morning_session.dart | 196 ++++++++++++++ phone_app/lib/services/room_proof.dart | 26 +- phone_app/lib/services/session_handoff.dart | 66 +++++ phone_app/lib/services/session_json.dart | 74 ++++++ phone_app/lib/services/session_publisher.dart | 44 ++++ phone_app/lib/services/session_rules.dart | 193 ++++++++++++++ phone_app/lib/services/session_store.dart | 130 +++++++++ phone_app/lib/services/session_sync.dart | 95 +++++++ .../lib/services/session_tag_settings.dart | 111 ++++++++ phone_app/lib/services/settings_sync.dart | 23 +- phone_app/lib/services/weight_entry.dart | 90 +++++++ phone_app/scripts/emu_morning.py | 193 ++++++++++++++ phone_app/test/home_history_card_test.dart | 83 ++++++ phone_app/test/ring_bypass_test.dart | 15 ++ phone_app/test/ring_route_test.dart | 22 +- phone_app/test/ring_session_handoff_test.dart | 138 ++++++++++ .../test/services/session_handoff_test.dart | 109 ++++++++ .../test/services/session_rules_test.dart | 249 ++++++++++++++++++ .../test/services/session_store_test.dart | 86 ++++++ .../test/services/session_sync_test.dart | 124 +++++++++ .../services/session_tag_settings_test.dart | 42 +++ .../test/services/weight_entry_test.dart | 32 +++ phone_app/test/session_screen_test.dart | 231 ++++++++++++++++ phone_app/test/session_tags_screen_test.dart | 101 +++++++ 46 files changed, 3733 insertions(+), 70 deletions(-) create mode 100644 DOCS-morning-session.md create mode 100644 phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/MotionMonitor.kt create mode 100644 phone_app/lib/main_session_probe.dart create mode 100644 phone_app/lib/probe/file_driven_scheduler.dart create mode 100644 phone_app/lib/screens/home_history_card.dart create mode 100644 phone_app/lib/screens/session_body.dart create mode 100644 phone_app/lib/screens/session_checklist.dart create mode 100644 phone_app/lib/screens/session_screen.dart create mode 100644 phone_app/lib/screens/session_tags_screen.dart create mode 100644 phone_app/lib/services/morning_session.dart create mode 100644 phone_app/lib/services/session_handoff.dart create mode 100644 phone_app/lib/services/session_json.dart create mode 100644 phone_app/lib/services/session_publisher.dart create mode 100644 phone_app/lib/services/session_rules.dart create mode 100644 phone_app/lib/services/session_store.dart create mode 100644 phone_app/lib/services/session_sync.dart create mode 100644 phone_app/lib/services/session_tag_settings.dart create mode 100644 phone_app/lib/services/weight_entry.dart create mode 100755 phone_app/scripts/emu_morning.py create mode 100644 phone_app/test/home_history_card_test.dart create mode 100644 phone_app/test/ring_session_handoff_test.dart create mode 100644 phone_app/test/services/session_handoff_test.dart create mode 100644 phone_app/test/services/session_rules_test.dart create mode 100644 phone_app/test/services/session_store_test.dart create mode 100644 phone_app/test/services/session_sync_test.dart create mode 100644 phone_app/test/services/session_tag_settings_test.dart create mode 100644 phone_app/test/services/weight_entry_test.dart create mode 100644 phone_app/test/session_screen_test.dart create mode 100644 phone_app/test/session_tags_screen_test.dart diff --git a/AGENTS.md b/AGENTS.md index 1d18e88..62e0137 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,10 +31,12 @@ passing sent the user back to the start. single `roomProof.nfcTagId` migrates into slot 1. **Tags and home location sync** (`settings_sync.dart`, see `DOCS-phone-alarm.md`) — a reinstall gets them back; do not make either local-only again. -- **Steps are unchanged** (`requiredSteps = 25`, `requiredElapsed = 2 min`), - and are counted from ring start, *not* re-baselined at tag 1. Consequence: - walking to tag 1 already banks the steps, so only the elapsed floor really - binds — which is why the steps stage auto-polls instead of offering a button. +- **Steps** (`requiredSteps = 25`) are counted from ring start, *not* + re-baselined at tag 1, so walking to tag 1 already banks them and the stage + passes on its first poll. The 2-minute elapsed floor (`requiredElapsed`) + applies **only under bypass/away**, where no tag proved the walk and a + shaken phone would count; on the normal path it was two minutes of ringing + nothing could shorten (dropped 2026-09-16). - **Answers are cumulative, not consecutive.** A wrong one costs the attempt and nothing else. - **The bypass skips the tags, never the walk.** After @@ -47,26 +49,19 @@ passing sent the user back to the start. deleted, not merely unrouted: the ring screen is reached by walking in from another room. -**`HomeScreen.initState` must stay strictly sequential.** It runs -`_applyPolicy()` → `_loadSyncState()` → `_syncToPc()` through one -`_bootstrapSync()`, because the last reads what the first two write and -`AlarmPublisher.publish` takes the service as a *parameter* — captured by -value, so a later assignment can never reach it. Running them concurrently -(as they once were) meant the startup publish always passed `null`, and since -that was the only publish site, **nothing published for three weeks** while -the PC honoured a record from 2026-08-09. `_pickEarlier` must publish too, or -the one schedule edit the app offers never reaches the PC. +**The dismiss does not end the morning.** Since 2026-09-16 it hands over, in +the same activity, to the silent **morning session**: weigh in → bathroom tag +→ shower → bathroom tag again → wardrobe tag → desk tag. A missed window +(AlarmManager, request code 1003) or a phone still for 4 min re-rings, and +silencing that is the full sequence above again; three re-rings fail the +session. State is persisted after every change and driven by wall-clock +instants, never Dart timers: **`DOCS-morning-session.md`**. -Relatedly: `publish()` reports a missing *backend* and a missing *store* -differently on purpose. One string for both is what made the above look like a -configuration the user had never done, while Firebase was connected the whole -time. - -`RingScreen` takes an injectable `clock`. `Stopwatch` reads the wall clock, -which `tester.pump()` does not advance, so without that seam no widget test -can reach the two-minute floor or the five-minute bypass. - -More, including everything that is a hard crash or a silent no-ring: +**`HomeScreen.initState` must stay strictly sequential** (`_applyPolicy` → +`_loadSyncState` → `_syncToPc`): run concurrently, the startup publish +captured a null store and **nothing published for three weeks**. Why, the +two deliberately distinct `publish()` failure strings, the ring's injectable +clock, and everything that is a hard crash or a silent no-ring: **`DOCS-phone-alarm.md`**. **Free days.** On a day in the shared pool (`~/src/utils/freedays`) the phone @@ -217,6 +212,8 @@ another repo with no error message anywhere. - Run tests: `python -m pytest wake_alarm/tests/ --cov=wake_alarm --cov-branch --cov-fail-under=100` - Phone tests: `cd phone_app && flutter test && flutter analyze` +- Walk the whole morning on the emulator: `phone_app/scripts/emu_morning.py` + against `lib/main_session_probe.dart` (see `DOCS-morning-session.md`) - Lint: `pre-commit run --all-files` - Show the resolved alarm: `python -m wake_alarm._sync --show` (`--no-cache` forces a live read) - Show what the next tick would do: `python -m wake_alarm._trigger --dry-run` @@ -243,6 +240,9 @@ The dev venv lacks `gatelock`, so anything importing `_state` (including - Don't raise the log level of `_sync`'s degraded-read paths. - Don't let the bypass skip the walk, and don't add a challenge kind that hides its own prompt. +- Don't close the ring screen on dismiss when a session should follow, don't + add a re-ring cancel beyond the session's own `finishSession`, and don't + restore a re-ring instant that has passed (BOOT_COMPLETED replays on launch). - Don't make `HomeScreen.initState` concurrent again, and don't collapse `publish()`'s two failure messages back into one. - Don't date a record by when the PC fetched it. diff --git a/DOCS-morning-session.md b/DOCS-morning-session.md new file mode 100644 index 0000000..c36b434 --- /dev/null +++ b/DOCS-morning-session.md @@ -0,0 +1,123 @@ +# The morning session — what happens after the ring stops + +The ring proved you stood up. It did not stop you lying back down: the +2026-09-16 observation was "I do the tags, the walk and the questions, and +then go back to sleep". So since that day **the dismiss does not end the +morning**. It hands over, inside the same `AlarmActivity`, to a silent +checklist that only ends when you are showered, dressed and sitting at the +desk — and the alarm comes back if a step is missed or the phone lies still. + +Owner: `phone_app/lib/services/morning_session.dart` (the record), +`session_rules.dart` (what moves it), `screens/session_screen.dart` (the +driver), `session_handoff.dart` (how the ring reaches it). + +## The legs + +``` +weigh in -> bathroom tag (≤ 2 min later) -> shower -> bathroom tag again + -> wardrobe tag -> desk tag -> done +``` + +| leg | passes when | window (re-ring at) | notes | +|---|---|---|---| +| `bathroomIn` | bathroom tag with a *pending* weight ≤ 2 min old | start + 10 min | the typed weight is not a leg; the tag is what proves you walked to the scale | +| `showerDone` | bathroom tag **≥ 8 min** after `bathroomIn` | `bathroomIn` + 18 min | its own window: 10 min composed with the 8-min floor would be a two-minute target, hit wet | +| `dressed` | wardrobe tag | previous + 10 min | | +| `atDesk` | desk tag | previous + 10 min | | + +Legs latch like the ring's stages. A leg whose tag is not registered is +**skipped at start** (`LegPass.skipped`), so the feature is usable before it +is configured: with no session tags at all it is a weigh-in and nothing +else. Away from home (`RingSkip.away`) there is no session. + +**Weight.** Typed, 30–250 kg; more than 3 kg from the last confirmed value +must be typed twice (`weight_entry.dart`). Without a bathroom tag the typed +value passes the first leg by itself — there is nothing to walk to. + +## What rings, and how + +- **A missed window** re-rings through an **AlarmManager alarm** + (`AlarmScheduler.scheduleReRing`, request code 1003, `setAlarmClock` like + the daily one). Not a Dart timer: the session screen can be killed, paused + or rebooted away, and the deadline has to survive all three. `BootReceiver` + restores it; `restoreReRing` drops an instant that has already passed + (see *Gotchas*). +- **A still phone** (accelerometer, `MotionMonitor.kt`, no motion for 4 min) + re-rings from Dart via `ringNow`, then routes itself to `/ring` in case the + full-screen intent lands on the live `singleInstance` activity instead of + recreating it. Suspended during the shower leg — the phone is on a shelf. + Only works while the session screen is up, which is why `AlarmActivity` + now holds `FLAG_KEEP_SCREEN_ON`; the deadline alarm is the backstop. +- **Silencing a re-ring is the full dismiss sequence**: tag 1, the walk, + tag 2, three questions. The ring screen's `_finishDismiss` sees a live + session for today and resumes it with `reRings + 1`. +- **One re-ring per leg.** After a deadline re-ring is dismissed the leg is + in `deadlineRung`; 5 min after its deadline (`bypassGrace`) it passes as + `LegPass.bypassed` — the dead-tag hatch, paid for with one full ring. +- **Three re-rings per morning** (`maxReRings`). A window missed with none + left ends the session as `failed`, silently. This is the agreed cap and the + known weakness: three rings of misery buy silence. +- The Dart tick also rings a deadline the native alarm should have fired + (20 s grace) — ringing twice is harmless, missing it is not. + +Everything is **persisted after every change** (`session_store.dart`, +`session.current`) and driven by wall-clock instants, because a re-ring +replaces the whole Flutter engine and resumes from the store. + +## History and sync + +Finished sessions go to `session.history` (30 kept). The home screen shows +the last seven (`home_history_card.dart`) with weight deltas. The record +rides on the synced `alarm.json` like the ring tags do +(`session_sync.dart`): `session_tag_ids`, `morning_sessions` (14) and +`latest_weight_kg` (`{date, kg}`, for diet-guard's budget — the reader on +that side is a separate change). The PC alarm parser ignores every field it +does not name. Sessions merge per date, newest `updatedAt` wins, so a +reinstall gets its history back. + +## Gotchas — each one cost a real run + +- **Route replacement runs the new screen's `initState` before the old + screen's `dispose`.** The ring screen's dispose used to clear the NFC + handler the session had just registered, so the session never heard a tag + (Pixel, 2026-09-16). `AlarmScheduler.clearNfcListener` now clears only if + *that instance* registered the handler. The emulator harness gives each + screen its own instance for the same reason. +- **Android replays `BOOT_COMPLETED` to a force-stopped app on its next + launch.** After `am force-stop` during a test, a plain launch delivered + BOOT_COMPLETED (`WakeAlarmBoot` log), `restoreReRing` re-armed a + nine-minute-old deadline, and the phone rang in the evening with no session + running. A stored instant in the past is now dropped, never fired. +- **`ValueKey(syncEpoch)` twice in one `Column`** — the history card and + the presence line — mis-reconciled silently in release and painted the old + presence element in the card's slot. Keys in one child list must differ. +- **The steps stage's 2-minute floor** now applies only under bypass (no tag + proved the walk). On the normal path tag 1 has already banked the steps, + so the floor was two minutes of ringing nothing could shorten. +- **`developer.log` is invisible in release logcat.** Session and challenge + logs use `debugPrint` (`WakeAlarmSession:`, `WakeAlarmRing:`), which is + what the emulator harness and a bad morning are debugged from. +- The volume ramp is ten minutes to full, not one. + +## Testing it without a bathroom + +`lib/main_session_probe.dart` runs the real app on `FileDrivenScheduler` +(`lib/probe/`), which replaces NFC, the step count and the motion watch with +files under `/sdcard/Android/data/com.kuhy.wake_alarm_sync/files/`. +`phone_app/scripts/emu_morning.py` drives it: + +```sh +flutter run -d emulator-5554 --debug -t lib/main_session_probe.dart > run.log +scripts/emu_morning.py --log run.log dismiss # ring1, 30 steps, ring2, answers +scripts/emu_morning.py weight 72.4 +scripts/emu_morning.py tag bath # then wait 8 min, tag bath again +scripts/emu_morning.py idle 250000 # still phone -> re-ring +scripts/emu_morning.py --log run.log dismiss # resumes at the same leg, 1/3 +scripts/emu_morning.py tag ward; scripts/emu_morning.py tag desk +``` + +Verified this way on 2026-09-16 (API 36 AVD): the whole morning including a +still-phone re-ring and the resume. `flutter build apk --debug --target` +produced an APK that ran `main.dart` instead; `flutter run -t` did not. +The phone remains the only test of the AlarmManager deadline with the +screen off and the app swiped away. diff --git a/DOCS-phone-alarm.md b/DOCS-phone-alarm.md index 1662022..9333b0b 100644 --- a/DOCS-phone-alarm.md +++ b/DOCS-phone-alarm.md @@ -222,3 +222,27 @@ install: both tags and the home appeared with zero taps after Google sign-in. - The emulator is a real peer: its device directory outranks the phone by HLC while it exists. Delete `wake-alarm-sync/devices/` after a restore test. + +## The home screen's startup order, and the ring's clock + +Moved here from `CLAUDE.md` on 2026-09-16 for its line cap; nothing below +has changed. + +**`HomeScreen.initState` must stay strictly sequential.** It runs +`_applyPolicy()` → `_loadSyncState()` → `_syncToPc()` through one +`_bootstrapSync()`, because the last reads what the first two write and +`AlarmPublisher.publish` takes the service as a *parameter* — captured by +value, so a later assignment can never reach it. Running them concurrently +(as they once were) meant the startup publish always passed `null`, and since +that was the only publish site, **nothing published for three weeks** while +the PC honoured a record from 2026-08-09. `_pickEarlier` must publish too, or +the one schedule edit the app offers never reaches the PC. + +Relatedly: `publish()` reports a missing *backend* and a missing *store* +differently on purpose. One string for both is what made the above look like a +configuration the user had never done, while Firebase was connected the whole +time. + +`RingScreen` takes an injectable `clock`. `Stopwatch` reads the wall clock, +which `tester.pump()` does not advance, so without that seam no widget test +can reach the two-minute floor or the five-minute bypass. diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmActivity.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmActivity.kt index fc5b351..5242184 100644 --- a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmActivity.kt +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmActivity.kt @@ -3,6 +3,7 @@ package com.kuhy.wake_alarm_sync import android.app.KeyguardManager import android.content.Context import android.os.Bundle +import android.view.WindowManager import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel @@ -28,6 +29,11 @@ class AlarmActivity : FlutterActivity() { setShowWhenLocked(true) setTurnScreenOn(true) super.onCreate(savedInstanceState) + // The morning session lives in this activity for half an hour after + // the ring stops. With the screen allowed to sleep the activity + // pauses, NFC stops polling and the motion watch stops sampling, so + // the only thing left working would be the AlarmManager backstop. + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) dismissKeyguard() } @@ -95,6 +101,10 @@ class AlarmActivity : FlutterActivity() { // pauses this one and takes reader mode down with it, and the tag tap // must keep working once the ring screen is back in front. alarmChannel?.let { NfcReader.start(this, it) } + // The user can still lock the phone mid-session with the power + // button. Coming back, the keyguard is up again and NFC is back in + // ON_LOCKED -- the same dead state onCreate handles. + dismissKeyguard() } override fun onPause() { diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmChannel.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmChannel.kt index 2f8b898..b429ffd 100644 --- a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmChannel.kt +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmChannel.kt @@ -88,6 +88,34 @@ object AlarmChannel { // means the picker asked, where there is no ring screen to close. "closeRingScreen" -> result.success(null) "stepCount" -> result.success(StepCounter.stepsSinceRingStart(context)) + // The morning session's one live deadline, as an absolute epoch + // instant; null drops it (a leg with its re-ring spent must not + // inherit the previous leg's alarm). Dart ints cross the channel + // as Int when they fit and Long when they do not; an epoch in + // millis never fits. + "armReRing" -> { + val at = call.argument("atMillis")?.toLong() + if (at == null) { + AlarmScheduler.clearReRing(context) + } else { + AlarmScheduler.scheduleReRing(context, at) + } + result.success(null) + } + // The session's finish path, and the only thing that drops a + // pending re-ring. Not named "cancel" and not reachable from any + // screen but the session's own: the wake alarm itself still has + // no off switch. + "finishSession" -> { + AlarmScheduler.clearReRing(context) + MotionMonitor.stop(context) + result.success(null) + } + "beginMotionWatch" -> { + MotionMonitor.start(context) + result.success(null) + } + "motionIdleMillis" -> result.success(MotionMonitor.idleMillis()) "beginStepCount" -> { StepCounter.markRingStart(context) result.success(null) diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmReceiver.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmReceiver.kt index 6ece7af..366e701 100644 --- a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmReceiver.kt +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmReceiver.kt @@ -16,6 +16,14 @@ import android.util.Log */ class AlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { + // A session deadline: the user dismissed the alarm and then stalled. + // No free-day check (a free day never starts a session) and no daily + // re-arm -- that is the wake alarm's business, not this one's. + if (intent.getStringExtra(AlarmScheduler.EXTRA_REASON) == AlarmScheduler.REASON_RERING) { + Log.i(TAG, "session deadline missed: re-ringing") + AlarmService.start(context) + return + } // A shared free day means the alarm does not ring -- not later, not // quieter, not at all. Re-arm for tomorrow (nextOccurrence rolls over // because the armed instant has passed) so the day after is normal. diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmScheduler.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmScheduler.kt index 8fd2dc9..8bc832c 100644 --- a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmScheduler.kt +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmScheduler.kt @@ -22,11 +22,29 @@ object AlarmScheduler { /** Request code for the single alarm PendingIntent; reused so re-arming replaces. */ private const val REQUEST_CODE = 1001 + /** + * Request code for the morning session's re-ring. + * + * Distinct from [REQUEST_CODE] on purpose: a PendingIntent is keyed by + * request code, so arming the re-ring under 1001 would silently replace + * tomorrow's wake alarm with a one-shot twenty minutes from now. + */ + private const val RERING_REQUEST_CODE = 1003 + + /** Intent extra naming why the receiver fired; absent on the daily alarm. */ + const val EXTRA_REASON = "reason" + + /** [EXTRA_REASON] value for a session deadline. */ + const val REASON_RERING = "rering" + /** SharedPreferences file holding the armed time, so boot can re-arm it. */ private const val PREFS = "wake_alarm_scheduler" private const val KEY_HOUR = "hour" private const val KEY_MINUTE = "minute" + /** Epoch millis of the armed re-ring, so a reboot mid-session restores it. */ + private const val KEY_RERING_AT = "rering_at" + /** Sentinel for "no alarm stored", distinguishable from a valid 0. */ private const val NONE = -1 @@ -68,6 +86,57 @@ object AlarmScheduler { return true } + /** + * Arms the morning session's re-ring for the absolute instant [atMillis]. + * + * Same [AlarmManager.setAlarmClock] path as the daily alarm: it is the + * one this repo has proved starts the foreground service with the screen + * off. Replaces any earlier re-ring — the session has exactly one live + * deadline at a time. + */ + fun scheduleReRing(context: Context, atMillis: Long) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putLong(KEY_RERING_AT, atMillis).apply() + val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + manager.setAlarmClock( + AlarmManager.AlarmClockInfo(atMillis, showIntent(context)), + reRingPendingIntent(context), + ) + } + + /** + * Drops the pending re-ring. Reached only from the session's own finish + * path (`finishSession`); there is no Dart-facing cancel for the alarm + * itself. + */ + fun clearReRing(context: Context) { + val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + manager.cancel(reRingPendingIntent(context)) + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .remove(KEY_RERING_AT).apply() + } + + /** + * Re-arms a stored re-ring after a reboot; false when none is still due. + * + * A past instant is dropped, never fired: a session whose deadline + * passed while the phone was off is over, and a stale instant is not + * confined to reboots -- Android re-delivered BOOT_COMPLETED to a + * force-stopped app on its next launch (Pixel 6a, 2026-09-16), which + * fired a nine-minute-old deadline into an evening with no session. + */ + fun restoreReRing(context: Context): Boolean { + val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + val at = prefs.getLong(KEY_RERING_AT, NONE.toLong()) + if (at == NONE.toLong()) return false + if (at <= System.currentTimeMillis()) { + prefs.edit().remove(KEY_RERING_AT).apply() + return false + } + scheduleReRing(context, at) + return true + } + /** * Whether the system will actually honour a full-screen intent. * @@ -114,6 +183,14 @@ object AlarmScheduler { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) + /** The re-ring's own PendingIntent; the extra is how the receiver tells them apart. */ + private fun reRingPendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast( + context, + RERING_REQUEST_CODE, + Intent(context, AlarmReceiver::class.java).putExtra(EXTRA_REASON, REASON_RERING), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + /** Tapping the clock's alarm chip opens the app rather than the ring screen. */ private fun showIntent(context: Context): PendingIntent = PendingIntent.getActivity( context, diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmVolume.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmVolume.kt index 31a6c46..eccfb51 100644 --- a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmVolume.kt +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmVolume.kt @@ -24,10 +24,16 @@ object AlarmVolume { /** Player gain the ring starts at: audible in a quiet room, not a jolt. */ const val RAMP_START_GAIN = 0.04f - /** How long the climb from [RAMP_START_GAIN] to full takes. */ - private const val RAMP_DURATION_MS = 60_000L + /** + * How long the climb from [RAMP_START_GAIN] to full takes. + * + * Ten minutes, up from one on 2026-09-16: a minute to full blast is a + * jolt, not a wake-up, and with the dismiss walk taking a few minutes + * the whole sequence was done at maximum volume. + */ + private const val RAMP_DURATION_MS = 600_000L - /** Gap between ramp steps; 30 steps over the full duration. */ + /** Gap between ramp steps; 300 steps over the full duration. */ private const val RAMP_STEP_MS = 2_000L /** @@ -55,8 +61,9 @@ object AlarmVolume { * Waking someone at full blast is not more effective, only harsher. The * climb is quadratic because perceived loudness is not linear in * amplitude: a linear ramp lurches at the start and crawls at the end. - * Measured on the Pixel 6a: -28 dB at 3s, -21 dB at 15s, -12 dB at 30s, - * 0 dB at 62s. + * Measured on the Pixel 6a at the old one-minute duration: -28 dB at + * 3s, -21 dB at 15s, -12 dB at 30s, 0 dB at 62s; the shape is the same, + * stretched tenfold. * * [player] is re-read every step and a null one ends that step, so a * dismissal mid-ramp cannot touch a released MediaPlayer — provided the diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/BootReceiver.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/BootReceiver.kt index 88aeebc..1d3e7d5 100644 --- a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/BootReceiver.kt +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/BootReceiver.kt @@ -3,6 +3,7 @@ package com.kuhy.wake_alarm_sync import android.content.BroadcastReceiver import android.content.Context import android.content.Intent +import android.util.Log /** * Re-arms the stored alarm after a reboot. @@ -13,10 +14,19 @@ import android.content.Intent class BootReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action != Intent.ACTION_BOOT_COMPLETED) return - AlarmScheduler.rearmFromStorage(context) + val rearmed = AlarmScheduler.rearmFromStorage(context) + // A reboot mid-session must not end the session silently: the live + // leg's deadline is stored alongside the daily time. Not only after + // a reboot, either -- see restoreReRing for the launch-time replay. + val rering = AlarmScheduler.restoreReRing(context) + Log.i(TAG, "boot: rearmed=$rearmed rering=$rering") // setInexactRepeating does not survive a reboot, so the daily check // has to be re-established here or it silently stops after the first // restart — exactly when a watchdog is most needed. AlarmWatchdog.schedule(context) } + + private companion object { + const val TAG = "WakeAlarmBoot" + } } diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/MotionMonitor.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/MotionMonitor.kt new file mode 100644 index 0000000..1076f66 --- /dev/null +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/MotionMonitor.kt @@ -0,0 +1,77 @@ +package com.kuhy.wake_alarm_sync + +import android.content.Context +import android.hardware.Sensor +import android.hardware.SensorEvent +import android.hardware.SensorEventListener +import android.hardware.SensorManager +import android.os.SystemClock +import kotlin.math.abs +import kotlin.math.sqrt + +/** + * How long the phone has lain still, for the morning session. + * + * A phone that does not move for minutes after the alarm is a phone on the + * nightstand next to someone who went back to bed. The accelerometer rather + * than the step sensors: sitting down is not going back to sleep, and a + * phone in a pocket keeps moving without a single step being taken. + * + * Hand-written on the existing channel, like [StepCounter]: nothing on the + * ring path may depend on a pub plugin compiling. Only meaningful while the + * session screen keeps the screen on -- an unregistered or suspended sensor + * reports nothing, which the Dart side reads as "unknown", never as "still". + */ +object MotionMonitor { + + /** Change in acceleration magnitude (m/s²) between samples that counts as motion. */ + private const val THRESHOLD = 0.6f + + /** Sentinel for "not watching". */ + private const val NONE = -1L + + @Volatile + private var lastMotionAt: Long = NONE + + private var lastMagnitude: Float = Float.NaN + private var listener: SensorEventListener? = null + + /** Starts watching; the idle clock begins now, so a resume never inherits an old gap. */ + fun start(context: Context) { + stop(context) + val manager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager + val sensor = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) ?: return + lastMotionAt = SystemClock.elapsedRealtime() + lastMagnitude = Float.NaN + val l = object : SensorEventListener { + override fun onSensorChanged(event: SensorEvent) { + val (x, y, z) = event.values + val magnitude = sqrt(x * x + y * y + z * z) + if (!lastMagnitude.isNaN() && abs(magnitude - lastMagnitude) > THRESHOLD) { + lastMotionAt = SystemClock.elapsedRealtime() + } + lastMagnitude = magnitude + } + + override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit + } + manager.registerListener(l, sensor, SensorManager.SENSOR_DELAY_NORMAL) + listener = l + } + + /** Milliseconds since the phone last moved, or -1 when not watching. */ + fun idleMillis(): Long { + val since = lastMotionAt + if (since == NONE || listener == null) return NONE + return SystemClock.elapsedRealtime() - since + } + + /** Stops watching and forgets the clock. */ + fun stop(context: Context) { + val l = listener ?: return + val manager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager + manager.unregisterListener(l) + listener = null + lastMotionAt = NONE + } +} diff --git a/phone_app/lib/main.dart b/phone_app/lib/main.dart index bce9f23..97b5d87 100644 --- a/phone_app/lib/main.dart +++ b/phone_app/lib/main.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:wake_alarm_sync/screens/home_screen.dart'; import 'package:wake_alarm_sync/screens/ring_screen.dart'; +import 'package:wake_alarm_sync/screens/session_screen.dart'; import 'package:wake_alarm_sync/services/alarm_policy.dart'; import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; import 'package:wake_alarm_sync/ui/theme.dart'; @@ -29,8 +30,18 @@ Future main() async { /// Root application widget. class WakeAlarmSyncApp extends StatelessWidget { - /// Creates a [WakeAlarmSyncApp]. - const WakeAlarmSyncApp({super.key}); + /// Creates a [WakeAlarmSyncApp]; [newScheduler] is the probes' seam. + const WakeAlarmSyncApp({super.key, this.newScheduler}); + + /// Builds the platform bridge for the ring and session screens. + /// + /// Null in production (each screen builds the real one). The emulator + /// harness supplies a file-driven bridge so a machine with no NFC and no + /// step sensor can still walk the whole morning. A factory rather than an + /// instance so each screen owns its own, as in production: the NFC + /// listener's ownership is per instance, and sharing one instance hid the + /// ring-dispose-wipes-session-listener bug the phone had just shown. + final AlarmScheduler Function()? newScheduler; @override Widget build(BuildContext context) { @@ -42,7 +53,10 @@ class WakeAlarmSyncApp extends StatelessWidget { // is what comes up over the lockscreen; the launcher still gets home. routes: { '/': (_) => const HomeScreen(), - kRingRoute: (_) => const RingScreen(), + kRingRoute: (_) => RingScreen(scheduler: newScheduler?.call()), + // Reached only by pushReplacement from the ring screen, inside + // AlarmActivity; it is never an initial route. + kSessionRoute: (_) => SessionScreen(scheduler: newScheduler?.call()), }, ); } diff --git a/phone_app/lib/main_session_probe.dart b/phone_app/lib/main_session_probe.dart new file mode 100644 index 0000000..d74c89a --- /dev/null +++ b/phone_app/lib/main_session_probe.dart @@ -0,0 +1,32 @@ +import 'package:flutter/material.dart'; + +import 'package:wake_alarm_sync/main.dart'; +import 'package:wake_alarm_sync/probe/file_driven_scheduler.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/room_proof_settings.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +/// Emulator entrypoint: the whole morning, driven from adb. +/// +/// Like `main_ring_probe.dart` it rings on launch, but it runs the app on a +/// [FileDrivenScheduler] and registers fixed tag ids, so the dismiss walk +/// and the session legs can be fed by writing files: +/// +/// ```sh +/// F=/sdcard/Android/data/com.kuhy.wake_alarm_sync/files +/// adb shell "echo -n ring1 > $F/tag"; adb shell "echo 30 > $F/steps" +/// adb shell "echo -n ring2 > $F/tag" # then answer three questions +/// adb shell "echo -n bath > $F/tag" # ... bath, ward, desk +/// ``` +/// +/// Not part of the shipped app: `flutter build apk` uses `lib/main.dart`. +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await RoomProofSettings.saveNfcTagAt(0, 'ring1'); + await RoomProofSettings.saveNfcTagAt(1, 'ring2'); + await SessionTagSettings.saveTagAt(SessionTagSlot.bathroom, 'bath'); + await SessionTagSettings.saveTagAt(SessionTagSlot.wardrobe, 'ward'); + await SessionTagSettings.saveTagAt(SessionTagSlot.desk, 'desk'); + await AlarmScheduler().ringNow(); + runApp(const WakeAlarmSyncApp(newScheduler: FileDrivenScheduler.new)); +} diff --git a/phone_app/lib/probe/file_driven_scheduler.dart b/phone_app/lib/probe/file_driven_scheduler.dart new file mode 100644 index 0000000..62331d0 --- /dev/null +++ b/phone_app/lib/probe/file_driven_scheduler.dart @@ -0,0 +1,76 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; + +/// An [AlarmScheduler] whose sensors and NFC are files adb can write. +/// +/// The emulator has no NFC and no step sensor, so the real dismiss sequence +/// and the whole morning session are unreachable on it. This bridge keeps +/// every alarm, ring and re-ring call on the real channel and replaces only +/// the three inputs hardware would supply: +/// +/// - `files/tag` — a tag id; consumed once, delivered to the NFC listener +/// - `files/steps` — the step count the ring's walk stage reads +/// - `files/idle_ms` — how long the phone has "lain still" +/// +/// under `/sdcard/Android/data//files/`. Probe-only: `lib/main.dart` +/// never constructs it. +class FileDrivenScheduler extends AlarmScheduler { + /// Creates the bridge; starts polling on the first NFC registration. + FileDrivenScheduler(); + + static const Duration _poll = Duration(milliseconds: 500); + + Directory? _dir; + Timer? _timer; + void Function(String tagId)? _onTag; + + Future _files() async => + _dir ??= (await getExternalStorageDirectory())!; + + Future _read(String name) async { + final file = File(p.join((await _files()).path, name)); + if (!file.existsSync()) return null; + return (await file.readAsString()).trim(); + } + + @override + Future hasNfc() async => true; + + @override + void onNfcTag(void Function(String tagId) onTag) { + _onTag = onTag; + _timer ??= Timer.periodic(_poll, (_) => unawaited(_deliverTag())); + } + + /// Stops this instance's polling; another instance's listener is its own. + @override + void clearNfcListener() { + _onTag = null; + _timer?.cancel(); + _timer = null; + } + + Future _deliverTag() async { + final file = File(p.join((await _files()).path, 'tag')); + if (!file.existsSync()) return; + final id = (await file.readAsString()).trim(); + await file.delete(); + debugPrint('FileDrivenScheduler: tag $id'); + _onTag?.call(id); + } + + @override + Future stepsSinceRingStart() async => + int.tryParse(await _read('steps') ?? '') ?? -1; + + @override + Future motionIdle() async { + final ms = int.tryParse(await _read('idle_ms') ?? ''); + return ms == null ? null : Duration(milliseconds: ms); + } +} diff --git a/phone_app/lib/screens/home_body.dart b/phone_app/lib/screens/home_body.dart index ecb79a6..a8f26b3 100644 --- a/phone_app/lib/screens/home_body.dart +++ b/phone_app/lib/screens/home_body.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/screens/home_history_card.dart'; import 'package:wake_alarm_sync/screens/home_presence_line.dart'; import 'package:wake_alarm_sync/ui/theme.dart'; @@ -107,6 +108,12 @@ class HomeBody extends StatelessWidget { ).extension()!.success, ), ), + const SizedBox(height: 24), + // Not `ValueKey(syncEpoch)`: the presence line above + // already carries that key in this Column, and two children + // with one key mis-reconcile silently in release -- the old + // presence element was painted here. + HomeHistoryCard(key: ValueKey('history-$syncEpoch')), if (!configured) ...[ const SizedBox(height: 16), Text( diff --git a/phone_app/lib/screens/home_history_card.dart b/phone_app/lib/screens/home_history_card.dart new file mode 100644 index 0000000..96767e9 --- /dev/null +++ b/phone_app/lib/screens/home_history_card.dart @@ -0,0 +1,91 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_store.dart'; + +/// How many mornings the home screen shows. +const int kHistoryShown = 7; + +/// The last week of mornings: outcome, re-rings and weight, one line each. +/// +/// Self-loading, keyed by the home screen's sync epoch so a history a pull +/// just restored appears without a cold start. Absent entirely until the +/// first session has finished — an empty card would only say "not yet". +class HomeHistoryCard extends StatefulWidget { + /// Creates the card; [store] is injectable for tests. + const HomeHistoryCard({super.key, this.store}); + + /// Session persistence; defaults to SharedPreferences. + final SessionStore? store; + + @override + State createState() => _HomeHistoryCardState(); +} + +class _HomeHistoryCardState extends State { + List _sessions = const []; + + @override + void initState() { + super.initState(); + unawaited(_load()); + } + + Future _load() async { + final history = await (widget.store ?? SessionStore()).history(); + if (!mounted) return; + setState(() => _sessions = history.take(kHistoryShown).toList()); + } + + @override + Widget build(BuildContext context) { + if (_sessions.isEmpty) return const SizedBox.shrink(); + final theme = Theme.of(context); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text('Last mornings', style: theme.textTheme.titleMedium), + const SizedBox(height: 8), + for (var i = 0; i < _sessions.length; i++) + Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Text( + describeMorning(_sessions[i], previousWeight: _previousWeight(i)), + style: theme.textTheme.bodyMedium, + ), + ), + ], + ); + } + + /// The nearest older weigh-in, for the delta. + double? _previousWeight(int index) { + for (var i = index + 1; i < _sessions.length; i++) { + final kg = _sessions[i].weightKg; + if (kg != null) return kg; + } + return null; + } +} + +/// One line for [session]: `09-16 ✓ 0 re-rings · 72.4 kg (−0.3)`. +String describeMorning(MorningSession session, {double? previousWeight}) { + final mark = switch (session.outcome) { + SessionOutcome.completed => '✓', + SessionOutcome.failed => '✗', + SessionOutcome.active => '…', + }; + final rings = '${session.reRings} re-ring${session.reRings == 1 ? '' : 's'}'; + final kg = session.weightKg; + var weight = ''; + if (kg != null) { + weight = ' · $kg kg'; + if (previousWeight != null) { + final delta = kg - previousWeight; + final sign = delta > 0 ? '+' : (delta < 0 ? '−' : '±'); + weight += ' ($sign${delta.abs().toStringAsFixed(1)})'; + } + } + return '${session.date.substring(5)} $mark $rings$weight'; +} diff --git a/phone_app/lib/screens/ring_screen.dart b/phone_app/lib/screens/ring_screen.dart index 077761a..d37d9fd 100644 --- a/phone_app/lib/screens/ring_screen.dart +++ b/phone_app/lib/screens/ring_screen.dart @@ -10,10 +10,14 @@ import 'package:wake_alarm_sync/services/dismiss_gate.dart'; import 'package:wake_alarm_sync/services/home_presence.dart'; import 'package:wake_alarm_sync/services/ring_startup.dart'; import 'package:wake_alarm_sync/services/room_proof.dart'; +import 'package:wake_alarm_sync/services/session_handoff.dart'; /// How often the live steps stage re-reads the step counter. const Duration kStepPollInterval = Duration(seconds: 2); +/// Route of the session screen the dismiss hands over to. +const String kSessionRoute = '/session'; + /// The dismiss screen shown over the lockscreen while the alarm rings. /// /// A strict sequence: tag 1, then the walk, then tag 2, then the challenges. @@ -26,6 +30,7 @@ class RingScreen extends StatefulWidget { this.generator, this.clock, this.presence, + this.handoff, }); /// Platform bridge; defaults to the real MethodChannel. @@ -37,6 +42,9 @@ class RingScreen extends StatefulWidget { /// Home-presence resolver; defaults to the real one. final HomePresence? presence; + /// Starts or resumes the morning session; defaults to the real handoff. + final SessionHandoff? handoff; + /// Time since the ring started; defaults to a real `Stopwatch`. /// /// Injectable because `Stopwatch` reads the wall clock, which @@ -132,12 +140,15 @@ class _RingScreenState extends State { /// Re-reads the step counter while the steps stage is live. /// /// Polled rather than button-driven: the walk to tag 1 has usually already - /// banked the steps, so the only thing still binding is the elapsed-time - /// floor. Making the user hunt for a button to discover that is friction - /// without difficulty. + /// banked the steps, so on the normal path this passes on the first poll. + /// The elapsed-time floor applies only under bypass, where no tag proved + /// the walk and a shaken phone would otherwise count. Future _pollSteps() async { if (_gate.stage != DismissStage.steps) return; - final result = await _proof.checkSteps(_elapsed()); + final result = await _proof.checkSteps( + _elapsed(), + floor: _gate.bypassActive, + ); if (!mounted || _gate.stage != DismissStage.steps) return; setState(() { if (result.satisfied) _gate.passStepsStage(); @@ -149,13 +160,14 @@ class _RingScreenState extends State { /// Logs the current challenge so a hardware test can be scripted. /// /// Debug aid only: the answer is already on screen for whoever is holding - /// the phone, so this leaks nothing the user cannot see. + /// the phone, so this leaks nothing the user cannot see. `debugPrint` + /// rather than `developer.log` so it reaches logcat, which is what the + /// emulator harness reads the answer from. void _logChallenge() { - developer.log( - 'challenge kind=${_challenge.kind.name} display="${_challenge.display}" ' - 'answer=${_challenge.answer} ' + debugPrint( + 'WakeAlarmRing: challenge kind=${_challenge.kind.name} ' + 'display="${_challenge.display}" answer=${_challenge.answer} ' '${_gate.challengesPassed}/${_gate.challengesRequired}', - name: 'WakeAlarmRing', ); } @@ -191,9 +203,12 @@ class _RingScreenState extends State { } } - /// Stops the ring, then closes this screen. + /// Stops the ring, then hands over to the session — or closes. /// - /// Ordered: the sound must stop even if closing the window fails. + /// Ordered: the sound must stop even if what follows fails. The session + /// screen replaces this one *inside* the activity, so NFC reader mode and + /// the kept-on screen carry over; closing only happens when there is no + /// session to run (away from home, or a ring after the day's session). Future _finishDismiss() async { developer.log('dismiss: stopping ring', name: 'WakeAlarmRing'); await _scheduler.dismiss(); @@ -202,6 +217,13 @@ class _RingScreenState extends State { // 08:00 baseline short of reinstalling — a ratchet with no reset is a // trap, not a defence. await AlarmPolicy.resetAfterFire(); + final handoff = widget.handoff ?? SessionHandoff(scheduler: _scheduler); + final session = await handoff.afterDismiss(away: _gate.awayActive); + if (session && mounted) { + developer.log('dismiss: opening session', name: 'WakeAlarmRing'); + await Navigator.of(context).pushReplacementNamed(kSessionRoute); + return; + } developer.log('dismiss: closing screen', name: 'WakeAlarmRing'); await _scheduler.closeRingScreen(); } diff --git a/phone_app/lib/screens/session_body.dart b/phone_app/lib/screens/session_body.dart new file mode 100644 index 0000000..0549d02 --- /dev/null +++ b/phone_app/lib/screens/session_body.dart @@ -0,0 +1,126 @@ +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/screens/session_checklist.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; + +/// The session screen's body: the checklist, the weigh-in field, the clocks. +/// +/// Stateless, taking plain values — the screen keeps the state and the +/// ordering, which is where the ring's bugs lived. +class SessionBody extends StatelessWidget { + /// Creates the body from already-resolved state. + const SessionBody({ + required this.session, + required this.now, + required this.controller, + required this.status, + required this.onSubmitWeight, + super.key, + }); + + /// The session being displayed. + final MorningSession session; + + /// The instant the clocks are drawn at. + final DateTime now; + + /// The weigh-in field's controller. + final TextEditingController controller; + + /// The status line. + final String status; + + /// Called when the user submits a weight. + final VoidCallback onSubmitWeight; + + /// Whether the weigh-in field is live: first leg, nothing typed yet. + bool get _awaitingWeight => + session.currentLeg == SessionLeg.bathroomIn && + session.weightKg == null && + session.pendingWeightKg == null; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final leg = session.currentLeg; + return Scaffold( + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text('Stay up', style: theme.textTheme.headlineMedium), + const SizedBox(height: 4), + Text( + 'The alarm is off. It comes back if a step below is missed, ' + 'or if the phone lies still.', + style: theme.textTheme.bodyMedium, + ), + const SizedBox(height: 24), + SessionChecklist(session: session, now: now), + const SizedBox(height: 24), + if (_awaitingWeight) ...[ + TextField( + controller: controller, + keyboardType: const TextInputType.numberWithOptions( + decimal: true, + ), + decoration: const InputDecoration( + labelText: 'Weight (kg)', + border: OutlineInputBorder(), + ), + onSubmitted: (_) => onSubmitWeight(), + ), + const SizedBox(height: 12), + FilledButton( + onPressed: onSubmitWeight, + child: const Text('Log weight'), + ), + const SizedBox(height: 16), + ], + if (leg != null) + Text( + _deadlineLine(leg), + textAlign: TextAlign.center, + style: theme.textTheme.titleMedium, + ), + const SizedBox(height: 8), + Text( + 'Re-rings: ${session.reRings}/${MorningSession.maxReRings}', + textAlign: TextAlign.center, + style: theme.textTheme.bodySmall, + ), + const SizedBox(height: 16), + if (status.isNotEmpty) + Text( + status, + textAlign: TextAlign.center, + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodyLarge, + ), + ], + ), + ), + ), + ); + } + + String _deadlineLine(SessionLeg leg) { + final soonest = session.earliest(leg); + if (soonest != null && now.isBefore(soonest)) { + return 'Shower — tag counts in ${_mmss(soonest.difference(now))}'; + } + final deadline = session.deadline(leg); + if (now.isBefore(deadline)) { + return 'Alarm returns in ${_mmss(deadline.difference(now))}'; + } + return 'Deadline passed'; + } + + static String _mmss(Duration d) { + final m = d.inMinutes.toString().padLeft(2, '0'); + final s = (d.inSeconds % 60).toString().padLeft(2, '0'); + return '$m:$s'; + } +} diff --git a/phone_app/lib/screens/session_checklist.dart b/phone_app/lib/screens/session_checklist.dart new file mode 100644 index 0000000..0b23b9a --- /dev/null +++ b/phone_app/lib/screens/session_checklist.dart @@ -0,0 +1,80 @@ +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; + +/// The session's progress list: the weigh-in, then every leg with a tag. +/// +/// Every remaining leg is shown up front, as on the ring screen: someone +/// half-asleep has to see that the desk tag is still coming before they sit +/// on the bed. Skipped legs (no tag registered) are not listed at all — +/// they were never required. +class SessionChecklist extends StatelessWidget { + /// Creates a checklist reflecting [session] at [now]. + const SessionChecklist({required this.session, required this.now, super.key}); + + /// The session being displayed. + final MorningSession session; + + /// The instant the list is drawn at; unused today, kept for countdowns. + final DateTime now; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final weighed = session.weightKg != null || session.pendingWeightKg != null; + final current = session.currentLeg; + final rows = <(String, bool, bool)>[ + ( + 'Weigh in${_kg(session)}', + weighed, + !weighed && current == SessionLeg.bathroomIn, + ), + for (final leg in SessionLeg.values) + if (session.passedHow[leg] != LegPass.skipped) + ( + _label(leg), + session.passedAt.containsKey(leg), + leg == current && (leg != SessionLeg.bathroomIn || weighed), + ), + ]; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final (label, done, live) in rows) + Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row( + children: [ + Icon( + done ? Icons.check_circle : Icons.radio_button_unchecked, + color: done ? theme.colorScheme.primary : theme.disabledColor, + ), + const SizedBox(width: 12), + Expanded( + child: Text( + label, + style: live + ? theme.textTheme.titleMedium + : theme.textTheme.bodyMedium, + ), + ), + ], + ), + ), + ], + ); + } + + String _label(SessionLeg leg) { + final how = session.passedHow[leg]; + if (how == LegPass.bypassed) return '${leg.label} (skipped by the clock)'; + if (leg == SessionLeg.bathroomIn && !session.bathroomTagRequired) { + return 'Weight logged'; + } + return leg.label; + } + + static String _kg(MorningSession session) { + final kg = session.weightKg ?? session.pendingWeightKg; + return kg == null ? '' : ' — $kg kg'; + } +} diff --git a/phone_app/lib/screens/session_screen.dart b/phone_app/lib/screens/session_screen.dart new file mode 100644 index 0000000..d07fc0c --- /dev/null +++ b/phone_app/lib/screens/session_screen.dart @@ -0,0 +1,237 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/main.dart'; +import 'package:wake_alarm_sync/screens/session_body.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_publisher.dart'; +import 'package:wake_alarm_sync/services/session_rules.dart'; +import 'package:wake_alarm_sync/services/session_store.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; +import 'package:wake_alarm_sync/services/weight_entry.dart'; + +/// How often the clocks advance and the countdown redraws. +const Duration kSessionTick = Duration(seconds: 1); + +/// Every this many ticks the motion watch is read. +const int kMotionPollEvery = 5; + +/// Logs to logcat in release too: `developer.log` is invisible there, and a +/// morning that went wrong on the phone is only ever debugged from logcat. +void sessionLog(String message) => debugPrint('WakeAlarmSession: $message'); + +/// The silent half hour after the ring: weigh in, shower, dress, sit down. +/// +/// Shown in `AlarmActivity` in place of the ring screen, so NFC reader mode +/// and the kept-on screen carry over. Nothing here rings by itself; the +/// deadlines are AlarmManager alarms armed through [AlarmScheduler.armReRing] +/// and this widget merely keeps them pointed at the live leg. What it does +/// decide is the still-phone ring, which needs a live sensor. +class SessionScreen extends StatefulWidget { + /// Creates the screen; every dependency is injectable for tests. + const SessionScreen({ + super.key, + this.scheduler, + this.store, + this.clock, + this.publish, + }); + + /// Platform bridge; defaults to the real MethodChannel. + final AlarmScheduler? scheduler; + + /// Session persistence; defaults to SharedPreferences. + final SessionStore? store; + + /// Wall clock; injectable because the legs are minutes apart. + final DateTime Function()? clock; + + /// Pushes the finished session; defaults to [SessionPublisher.publish]. + final Future Function()? publish; + + @override + State createState() => _SessionScreenState(); +} + +class _SessionScreenState extends State { + late final AlarmScheduler _scheduler = widget.scheduler ?? AlarmScheduler(); + late final SessionStore _store = widget.store ?? SessionStore(); + late final DateTime Function() _now = widget.clock ?? DateTime.now; + late final Future Function() _publish = + widget.publish ?? SessionPublisher().publish; + + final TextEditingController _input = TextEditingController(); + MorningSession? _session; + SessionTagSettings _tags = const SessionTagSettings(); + double? _lastWeight; + double? _confirming; + Timer? _timer; + int _ticks = 0; + bool _finishing = false; + String _status = ''; + + @override + void initState() { + super.initState(); + unawaited(_init()); + } + + /// Loads the session the ring screen left, or starts one if reached cold. + Future _init() async { + final tags = await SessionTagSettings.load(); + final now = _now(); + var session = await _store.loadCurrent(); + if (session == null) { + session = SessionRules.start( + now: now, + tags: tags, + nfcAvailable: await _scheduler.hasNfc(), + ); + // Persist before anything can ring: a re-ring replaces this engine and + // resumes from the store, so an unsaved session would restart at zero. + await _store.save(session); + } + final last = await _store.lastWeightKg(); + await _scheduler.beginMotionWatch(); + await _scheduler.armReRing(session.nextDeadline()); + if (!mounted) return; + setState(() { + _tags = tags; + _session = session; + _lastWeight = last; + }); + _scheduler.onNfcTag(_onTag); + sessionLog( + 'started leg=${session.currentLeg?.name} re-rings=${session.reRings} ' + 'deadline=${session.nextDeadline()}', + ); + _timer = Timer.periodic(kSessionTick, (_) => unawaited(_onTick())); + if (!session.isActive) await _finish(); + } + + Future _onTag(String tagId) async { + final session = _session; + if (session == null) return; + final slot = _tags.slotOf(tagId); + final detail = slot == null ? 'Unknown tag' : session.onTag(slot, _now()); + sessionLog('tag=$tagId slot=$slot: $detail'); + await _commit(detail); + } + + Future _submitWeight() async { + final session = _session; + if (session == null) return; + final check = checkWeight( + _input.text, + last: _lastWeight, + confirming: _confirming, + ); + if (!check.accepted) { + _confirming = check.verdict == WeightVerdict.needsConfirm + ? check.kg + : null; + setState(() => _status = check.detail); + return; + } + _confirming = null; + _input.clear(); + await _commit(session.enterWeight(check.kg!, _now())); + } + + /// Persists, re-points the deadline, and ends the session if it is over. + Future _commit(String status) async { + final session = _session!; + await _store.save(session); + await _scheduler.armReRing(session.nextDeadline()); + if (!mounted) return; + setState(() => _status = status); + if (!session.isActive) await _finish(); + } + + Future _onTick() async { + final session = _session; + if (session == null || _finishing) return; + final now = _now(); + final tick = session.tick(now); + if (tick.changed) { + // A bypass passes a leg, so the deadline moves with it. + await _store.save(session); + await _scheduler.armReRing(session.nextDeadline()); + } + if (tick.ringReason != null) { + await _ring(tick.ringReason!, now); + return; + } + _ticks++; + if (_ticks % kMotionPollEvery == 0) { + final idle = await _scheduler.motionIdle(); + if (session.stillnessRingDue(idle)) { + await _ring('still:${session.currentLeg!.name}', now); + return; + } + } + if (!mounted) return; + setState(() { + if (tick.note != null) _status = tick.note!; + }); + if (!session.isActive) await _finish(); + } + + /// Rings now. The ring usually replaces this engine, so persist first. + /// + /// Then route to the ring screen anyway: `AlarmActivity` is + /// `singleInstance`, and if the full-screen intent lands on the live + /// instance instead of recreating it, nothing else would put the dismiss + /// sequence in front of the sound. + Future _ring(String reason, DateTime now) async { + final session = _session!..markReRing(reason, now); + await _store.save(session); + sessionLog('re-ring: $reason'); + _timer?.cancel(); + await _scheduler.ringNow(); + if (!mounted) return; + await Navigator.of(context).pushReplacementNamed(kRingRoute); + } + + /// Drops the deadline, archives, publishes, and closes the activity. + /// + /// Ordered so that a publish failure can never leave a re-ring armed. + Future _finish() async { + if (_finishing) return; + _finishing = true; + _timer?.cancel(); + final session = _session!; + await _scheduler.finishSession(); + await _store.archive(session); + final message = await _publish(); + sessionLog( + 'finished ${session.outcome.name} re-rings=${session.reRings}: $message', + ); + if (mounted) setState(() => _status = message); + await _scheduler.closeRingScreen(); + } + + @override + void dispose() { + _timer?.cancel(); + _scheduler.clearNfcListener(); + _input.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final session = _session; + if (session == null) { + return const Scaffold(body: Center(child: CircularProgressIndicator())); + } + return SessionBody( + session: session, + now: _now(), + controller: _input, + status: _status, + onSubmitWeight: () => unawaited(_submitWeight()), + ); + } +} diff --git a/phone_app/lib/screens/session_tags_screen.dart b/phone_app/lib/screens/session_tags_screen.dart new file mode 100644 index 0000000..1820609 --- /dev/null +++ b/phone_app/lib/screens/session_tags_screen.dart @@ -0,0 +1,135 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +/// Registers the three NFC tags the morning session walks through. +/// +/// Any slot may be left empty — its leg is then skipped — but the three must +/// be distinct from each other: one tag in two rooms is no walk at all. A +/// slot may reuse a *ring* tag; the bathroom tag is often ring tag 2. +class SessionTagsScreen extends StatefulWidget { + /// Creates the screen; [scheduler] is injectable for tests. + const SessionTagsScreen({super.key, this.scheduler}); + + /// Platform bridge used to drive NFC reader mode. + final AlarmScheduler? scheduler; + + @override + State createState() => _SessionTagsScreenState(); +} + +class _SessionTagsScreenState extends State { + late final AlarmScheduler _scheduler = widget.scheduler ?? AlarmScheduler(); + + SessionTagSettings _settings = const SessionTagSettings(); + SessionTagSlot? _scanning; + String _status = ''; + + @override + void initState() { + super.initState(); + unawaited(_load()); + } + + @override + void dispose() { + if (_scanning != null) unawaited(_scheduler.stopTagRegistration()); + _scheduler.clearNfcListener(); + super.dispose(); + } + + Future _load() async { + final settings = await SessionTagSettings.load(); + if (!mounted) return; + setState(() => _settings = settings); + } + + Future _startScan(SessionTagSlot slot) async { + _scheduler.onNfcTag((tagId) => unawaited(_onTag(slot, tagId))); + final started = await _scheduler.startTagRegistration(); + if (!mounted) return; + setState(() { + _scanning = started ? slot : null; + _status = started + ? 'Tap the ${slot.name} tag against the phone…' + : 'NFC is unavailable or switched off.'; + }); + } + + Future _onTag(SessionTagSlot slot, String tagId) async { + final taken = _settings.slotOf(tagId); + await _scheduler.stopTagRegistration(); + if (taken != null && taken != slot) { + if (!mounted) return; + setState(() { + _scanning = null; + _status = + 'That is already the ${taken.name} tag. Use a different ' + 'tag, in a different room.'; + }); + return; + } + await SessionTagSettings.saveTagAt(slot, tagId); + final settings = await SessionTagSettings.load(); + if (!mounted) return; + setState(() { + _settings = settings; + _scanning = null; + _status = 'The ${slot.name} tag is registered.'; + }); + } + + Widget _slotRow(SessionTagSlot slot) { + final id = _settings.tagAt(slot); + final scanning = _scanning == slot; + return Padding( + padding: const EdgeInsets.only(bottom: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text('${_title(slot)}: ${id ?? "none registered"}'), + const SizedBox(height: 8), + FilledButton( + onPressed: _scanning != null ? null : () => _startScan(slot), + child: Text( + scanning + ? 'Waiting for tag…' + : 'Register ${slot.name} tag${id == null ? "" : " again"}', + ), + ), + ], + ), + ); + } + + static String _title(SessionTagSlot slot) => switch (slot) { + SessionTagSlot.bathroom => 'Bathroom (scale + shower)', + SessionTagSlot.wardrobe => 'Wardrobe', + SessionTagSlot.desk => 'Desk', + }; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Morning session tags')), + body: Padding( + padding: const EdgeInsets.all(24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text( + 'After the alarm is dismissed: weigh in and tap the bathroom ' + 'tag, shower and tap it again, tap the wardrobe tag dressed, ' + 'then the desk tag. A slot left empty is skipped.', + ), + const SizedBox(height: 24), + for (final slot in SessionTagSlot.values) _slotRow(slot), + Text(_status), + ], + ), + ), + ); + } +} diff --git a/phone_app/lib/screens/settings_screen.dart b/phone_app/lib/screens/settings_screen.dart index a43b8b9..2ff8fd5 100644 --- a/phone_app/lib/screens/settings_screen.dart +++ b/phone_app/lib/screens/settings_screen.dart @@ -4,6 +4,7 @@ import 'package:sync_settings_ui/sync_settings_ui.dart'; import 'package:wake_alarm_sync/screens/github_mirror_screen.dart'; import 'package:wake_alarm_sync/screens/home_location_screen.dart'; import 'package:wake_alarm_sync/screens/room_proof_screen.dart'; +import 'package:wake_alarm_sync/screens/session_tags_screen.dart'; import 'package:wake_alarm_sync/services/firebase_backend.dart'; import 'package:wake_alarm_sync/services/google_sign_in_backend.dart'; @@ -55,6 +56,15 @@ class SettingsScreen extends StatelessWidget { MaterialPageRoute(builder: (_) => const RoomProofScreen()), ), ), + ListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Morning session tags'), + subtitle: const Text('Bathroom, wardrobe, desk — after the ring'), + trailing: const Icon(Icons.chevron_right), + onTap: () => Navigator.of(context).push( + MaterialPageRoute(builder: (_) => const SessionTagsScreen()), + ), + ), ListTile( contentPadding: EdgeInsets.zero, title: const Text('Home location'), diff --git a/phone_app/lib/services/alarm_scheduler.dart b/phone_app/lib/services/alarm_scheduler.dart index 50ea6bf..856672a 100644 --- a/phone_app/lib/services/alarm_scheduler.dart +++ b/phone_app/lib/services/alarm_scheduler.dart @@ -14,6 +14,16 @@ class AlarmScheduler { final MethodChannel _channel; + /// Which scheduler instance currently owns the NFC handler. + /// + /// The handler is per *channel name*, i.e. global, but screens register + /// and clear it through their own instances. Route replacement runs the + /// new screen's `initState` before the old screen's `dispose`, so without + /// ownership the ring screen's dispose wiped the session screen's freshly + /// registered listener and no session tag was ever heard (2026-09-16, on + /// the Pixel). + static AlarmScheduler? _nfcOwner; + /// Arms the alarm for the next occurrence of [hour]:[minute] in local time. /// /// The phone rings **daily**, matching the PC's `ALARM_DAYS` (all seven @@ -66,6 +76,7 @@ class AlarmScheduler { /// Reader mode is driven from Kotlin, so the tap does not restart the /// activity — a restart would reset the challenge. void onNfcTag(void Function(String tagId) onTag) { + _nfcOwner = this; _channel.setMethodCallHandler((call) async { if (call.method == 'onNfcTag') { final id = call.arguments; @@ -86,8 +97,12 @@ class AlarmScheduler { Future stopTagRegistration() => _channel.invokeMethod('stopTagRegistration'); - /// Stops listening for NFC taps. - void clearNfcListener() => _channel.setMethodCallHandler(null); + /// Stops listening for NFC taps — only if this instance registered them. + void clearNfcListener() { + if (_nfcOwner != this) return; + _nfcOwner = null; + _channel.setMethodCallHandler(null); + } /// Closes the ring screen after a successful dismiss. /// @@ -120,6 +135,37 @@ class AlarmScheduler { Future stepsSinceRingStart() async => await _channel.invokeMethod('stepCount') ?? -1; + /// Arms the morning session's re-ring for the absolute instant [at], or + /// drops it when [at] is null. + /// + /// An AlarmManager alarm, not a Dart timer: the session screen can be + /// killed, paused or rebooted away mid-session, and the deadline must + /// survive all three. Replaces any earlier re-ring. Null exists because a + /// leg can have no deadline (its re-ring is spent, or the morning's are), + /// and the previous leg's alarm must not fire into it. + Future armReRing(DateTime? at) => _channel.invokeMethod( + 'armReRing', + {'atMillis': at?.millisecondsSinceEpoch}, + ); + + /// Ends the session: drops the pending re-ring and the motion watch. + /// + /// The only path that clears a re-ring. Called from the session's own + /// finish, never from a button — the wake alarm still has no off switch. + Future finishSession() => _channel.invokeMethod('finishSession'); + + /// Starts sampling the accelerometer; the idle clock starts now. + Future beginMotionWatch() => + _channel.invokeMethod('beginMotionWatch'); + + /// How long the phone has lain still, or null when nothing is watching. + /// + /// Null is "unknown", never "still": a missing sensor must not re-ring. + Future motionIdle() async { + final millis = await _channel.invokeMethod('motionIdleMillis') ?? -1; + return millis < 0 ? null : Duration(milliseconds: millis); + } + /// Raw presence observations: `ssid`, `bssid`, `lat`, `lon`, `accuracy`, /// `distanceMeters`, `reason`. /// diff --git a/phone_app/lib/services/morning_session.dart b/phone_app/lib/services/morning_session.dart new file mode 100644 index 0000000..5e45829 --- /dev/null +++ b/phone_app/lib/services/morning_session.dart @@ -0,0 +1,196 @@ +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +/// The legs of the morning session, in the order they must be walked. +enum SessionLeg { + /// Weigh in, then tap the bathroom tag within two minutes. + bathroomIn, + + /// Tap the bathroom tag again, at least eight minutes later: the shower. + showerDone, + + /// Tap the wardrobe tag. + dressed, + + /// Tap the desk tag. The day has started. + atDesk, +} + +/// Which room's tag a leg expects. +extension SessionLegSlot on SessionLeg { + /// The tag slot for this leg. + SessionTagSlot get slot => switch (this) { + SessionLeg.bathroomIn || SessionLeg.showerDone => SessionTagSlot.bathroom, + SessionLeg.dressed => SessionTagSlot.wardrobe, + SessionLeg.atDesk => SessionTagSlot.desk, + }; + + /// What the checklist calls this leg. + String get label => switch (this) { + SessionLeg.bathroomIn => 'Tap the bathroom tag', + SessionLeg.showerDone => 'Shower, then tap the bathroom tag again', + SessionLeg.dressed => 'Get dressed — tap the wardrobe tag', + SessionLeg.atDesk => 'Sit down — tap the desk tag', + }; +} + +/// How a leg came to be passed. +enum LegPass { + /// The right tag, at the right time. + tag, + + /// No tag registered for it, so it was never required. + skipped, + + /// Never satisfied; passed by the clock after a missed deadline. + bypassed, +} + +/// Where the session stands. +enum SessionOutcome { + /// Legs remain. + active, + + /// Every leg passed. + completed, + + /// A deadline was missed with no re-rings left. + failed, +} + +/// One morning's session: the state, the clocks, and the JSON that persists +/// them. +/// +/// **Persisted after every change and driven by wall-clock instants**, never +/// Dart timers: the session screen can be killed, paused or rebooted away, +/// and the only thing that reliably comes back is what was written. The +/// rules that mutate this live in `session_rules.dart`; this file is the +/// record. +/// +/// Legs latch like the ring's stages: a passed leg never reverts. The one +/// thing that is not a leg is the typed weight, which stays *pending* until +/// the bathroom tag confirms it — that is the walk-to-the-scale proof. +class MorningSession { + /// Creates a session from persisted or freshly-started state. + MorningSession({ + required this.date, + required this.startedAt, + required this.updatedAt, + this.bathroomTagRequired = true, + Map? passedAt, + Map? passedHow, + Set? deadlineRung, + this.weightKg, + this.pendingWeightKg, + this.pendingWeightAt, + this.reRings = 0, + List? reRingReasons, + this.pendingReRingReason, + this.outcome = SessionOutcome.active, + }) : passedAt = passedAt ?? {}, + passedHow = passedHow ?? {}, + deadlineRung = deadlineRung ?? {}, + reRingReasons = reRingReasons ?? []; + + /// Window each leg gets from the moment the previous one passed. + static const Duration legWindow = Duration(minutes: 10); + + /// The shower cannot be over sooner than this after entering the bathroom. + static const Duration showerMin = Duration(minutes: 8); + + /// The shower leg's own window; [legWindow] composed with [showerMin] + /// would leave a two-minute target, hit wet, with the phone on a shelf. + static const Duration showerWindow = Duration(minutes: 18); + + /// How long after a missed deadline an unsatisfiable leg passes itself. + /// + /// The dead-tag hatch. The deadline has already re-rung by then, so a + /// missing tag costs one full dismiss sequence and five more minutes on + /// your feet — never a silent skip. + static const Duration bypassGrace = Duration(minutes: 5); + + /// A phone that has not moved for this long is on a nightstand. + static const Duration stillnessLimit = Duration(minutes: 4); + + /// Re-rings per morning before the session gives up. + static const int maxReRings = 3; + + /// The session's calendar day, `yyyy-mm-dd` local. + final String date; + + /// When the ring was dismissed and the session began. + final DateTime startedAt; + + /// Whether a bathroom tag exists to confirm the weigh-in. + /// + /// Without one the typed weight passes [SessionLeg.bathroomIn] by itself; + /// there is nothing to walk to. + final bool bathroomTagRequired; + + /// When each passed leg passed. + final Map passedAt; + + /// How each passed leg passed. + final Map passedHow; + + /// Legs whose deadline already re-rang; each leg gets one. + final Set deadlineRung; + + /// The confirmed weigh-in, kg. + double? weightKg; + + /// A typed weight the bathroom tag has not confirmed yet. + double? pendingWeightKg; + + /// When [pendingWeightKg] was typed. + DateTime? pendingWeightAt; + + /// Re-rings dismissed so far this session. + int reRings; + + /// Why each re-ring happened, e.g. `still:dressed`, `deadline:atDesk`. + final List reRingReasons; + + /// Set by the driver before it rings, so the dismiss can name the reason. + String? pendingReRingReason; + + /// Where the session stands. + SessionOutcome outcome; + + /// Last change, for the cross-device merge. + DateTime updatedAt; + + /// The leg awaiting satisfaction, or null when none remains. + SessionLeg? get currentLeg { + for (final leg in SessionLeg.values) { + if (!passedAt.containsKey(leg)) return leg; + } + return null; + } + + /// When [leg]'s clock started: the previous leg's pass, or the start. + DateTime legStart(SessionLeg leg) { + if (leg.index == 0) return startedAt; + return passedAt[SessionLeg.values[leg.index - 1]] ?? startedAt; + } + + /// Before this instant [leg] cannot pass; only the shower has one. + DateTime? earliest(SessionLeg leg) => + leg == SessionLeg.showerDone ? legStart(leg).add(showerMin) : null; + + /// The instant at which [leg] re-rings if still unsatisfied. + DateTime deadline(SessionLeg leg) => legStart( + leg, + ).add(leg == SessionLeg.showerDone ? showerWindow : legWindow); + + /// The instant at which an already-re-rung [leg] passes itself. + DateTime bypassAt(SessionLeg leg) => deadline(leg).add(bypassGrace); + + /// Whether another re-ring is allowed. + bool get canReRing => reRings < maxReRings; + + /// Whether the still-phone check is off: it lies on a shelf in the shower. + bool get stillnessSuspended => currentLeg == SessionLeg.showerDone; + + /// Whether this session still needs driving. + bool get isActive => outcome == SessionOutcome.active; +} diff --git a/phone_app/lib/services/room_proof.dart b/phone_app/lib/services/room_proof.dart index 7b94ba0..69dc23e 100644 --- a/phone_app/lib/services/room_proof.dart +++ b/phone_app/lib/services/room_proof.dart @@ -49,7 +49,12 @@ class RoomProof { /// Steps required, counted since the alarm started ringing. static const int requiredSteps = 25; - /// Elapsed time also required, so shaking the phone cannot pass. + /// Elapsed time also required **under bypass**, so shaking the phone + /// cannot pass when no tag proved the walk. + /// + /// Not applied on the normal path since 2026-09-16: tag 1 has already + /// banked the steps by the time this stage is live, so the floor was two + /// minutes of ringing that nothing the user did could shorten. static const Duration requiredElapsed = Duration(minutes: 2); /// Whether [tagId] is the tag registered for [slot]. @@ -66,10 +71,7 @@ class RoomProof { ); } if (tagId != expected) { - return RoomProofResult( - satisfied: false, - detail: 'Not tag ${slot + 1}', - ); + return RoomProofResult(satisfied: false, detail: 'Not tag ${slot + 1}'); } return RoomProofResult( satisfied: true, @@ -78,11 +80,15 @@ class RoomProof { ); } - /// Enough steps AND enough elapsed time since the ring started. + /// Enough steps, and — when [floor] is set — enough elapsed time too. /// - /// Both are required together. [elapsed] is passed in rather than measured - /// here so the ring screen owns the single clock. - Future checkSteps(Duration elapsed) async { + /// [elapsed] is passed in rather than measured here so the ring screen + /// owns the single clock. [floor] is the bypass profile's anti-shake + /// guard; with a tag stage passed the walk is already proven. + Future checkSteps( + Duration elapsed, { + bool floor = true, + }) async { final steps = await scheduler.stepsSinceRingStart(); if (steps < 0) { return const RoomProofResult( @@ -96,7 +102,7 @@ class RoomProof { detail: '$steps/$requiredSteps steps', ); } - if (elapsed < requiredElapsed) { + if (floor && elapsed < requiredElapsed) { final left = requiredElapsed - elapsed; return RoomProofResult( satisfied: false, diff --git a/phone_app/lib/services/session_handoff.dart b/phone_app/lib/services/session_handoff.dart new file mode 100644 index 0000000..6999131 --- /dev/null +++ b/phone_app/lib/services/session_handoff.dart @@ -0,0 +1,66 @@ +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_rules.dart'; +import 'package:wake_alarm_sync/services/session_store.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +/// What the ring screen does once the dismiss sequence is satisfied. +/// +/// The ring no longer ends the morning. The first dismiss of the day starts +/// the session; the dismiss of a re-ring resumes it, one re-ring richer. +/// Either way the ring screen hands over to the session screen instead of +/// closing the activity — the activity is what keeps NFC and the screen on. +class SessionHandoff { + /// Creates a handoff; every dependency is injectable for tests. + SessionHandoff({ + required this.scheduler, + SessionStore? store, + DateTime Function()? now, + }) : store = store ?? SessionStore(), + _now = now ?? DateTime.now; + + /// Platform bridge, for the NFC availability check. + final AlarmScheduler scheduler; + + /// Session persistence. + final SessionStore store; + + final DateTime Function() _now; + + /// Starts or resumes today's session; false when the ring should just end. + /// + /// [away] is the ring's verdict that the phone is not at home: no scale, + /// no tags, no session. A live session from a *previous* day is archived + /// as it stands (failed, since it never finished) rather than resumed — + /// yesterday's clocks would re-ring the moment the screen came up. + Future afterDismiss({required bool away}) async { + final now = _now(); + final today = SessionRules.dateKey(now); + final current = await store.loadCurrent(); + if (current != null && current.date == today) { + if (!current.isActive) return false; + current.recordReRing(now); + await store.save(current); + return true; + } + if (current != null) { + current + ..outcome = SessionOutcome.failed + ..updatedAt = now; + await store.archive(current); + } + if (away) return false; + // One session per day. A ring after today's has finished (a probe, or + // the alarm moved earlier and rung twice) must not start the morning + // over -- the weigh-in and the walk have been done. + final history = await store.history(); + if (history.any((s) => s.date == today)) return false; + final session = SessionRules.start( + now: now, + tags: await SessionTagSettings.load(), + nfcAvailable: await scheduler.hasNfc(), + ); + await store.save(session); + return true; + } +} diff --git a/phone_app/lib/services/session_json.dart b/phone_app/lib/services/session_json.dart new file mode 100644 index 0000000..ac9a7d8 --- /dev/null +++ b/phone_app/lib/services/session_json.dart @@ -0,0 +1,74 @@ +import 'package:wake_alarm_sync/services/morning_session.dart'; + +/// JSON for [MorningSession]: SharedPreferences and the synced record share +/// one shape, so a session restored from a peer reads like a local one. +extension SessionJson on MorningSession { + /// Serialises for SharedPreferences and the synced record. + Map toJson() => { + 'date': date, + 'started_at': startedAt.toIso8601String(), + 'updated_at': updatedAt.toIso8601String(), + 'bathroom_tag_required': bathroomTagRequired, + 'passed': { + for (final e in passedAt.entries) + e.key.name: { + 'at': e.value.toIso8601String(), + 'how': passedHow[e.key]?.name, + }, + }, + 'deadline_rung': deadlineRung.map((l) => l.name).toList(), + 'weight_kg': weightKg, + 'pending_weight_kg': pendingWeightKg, + 'pending_weight_at': pendingWeightAt?.toIso8601String(), + 're_rings': reRings, + 're_ring_reasons': reRingReasons, + 'pending_re_ring_reason': pendingReRingReason, + 'outcome': outcome.name, + }; +} + +/// Restores from [SessionJson.toJson]; null when the shape is not a session. +MorningSession? sessionFromJson(Object? raw) { + if (raw is! Map) return null; + final date = raw['date']; + final started = DateTime.tryParse('${raw['started_at']}'); + if (date is! String || started == null) return null; + final passed = raw['passed']; + final passedAt = {}; + final passedHow = {}; + if (passed is Map) { + for (final leg in SessionLeg.values) { + final entry = passed[leg.name]; + if (entry is! Map) continue; + final at = DateTime.tryParse('${entry['at']}'); + if (at == null) continue; + passedAt[leg] = at; + passedHow[leg] = LegPass.values.asNameMap()[entry['how']] ?? LegPass.tag; + } + } + final rung = raw['deadline_rung']; + final reasons = raw['re_ring_reasons']; + return MorningSession( + date: date, + startedAt: started, + updatedAt: DateTime.tryParse('${raw['updated_at']}') ?? started, + bathroomTagRequired: raw['bathroom_tag_required'] != false, + passedAt: passedAt, + passedHow: passedHow, + deadlineRung: { + if (rung is List) + for (final name in rung) ?SessionLeg.values.asNameMap()[name], + }, + weightKg: (raw['weight_kg'] as num?)?.toDouble(), + pendingWeightKg: (raw['pending_weight_kg'] as num?)?.toDouble(), + pendingWeightAt: DateTime.tryParse('${raw['pending_weight_at']}'), + reRings: (raw['re_rings'] as num?)?.toInt() ?? 0, + reRingReasons: reasons is List + ? reasons.whereType().toList() + : [], + pendingReRingReason: raw['pending_re_ring_reason'] as String?, + outcome: + SessionOutcome.values.asNameMap()[raw['outcome']] ?? + SessionOutcome.active, + ); +} diff --git a/phone_app/lib/services/session_publisher.dart b/phone_app/lib/services/session_publisher.dart new file mode 100644 index 0000000..7b17f11 --- /dev/null +++ b/phone_app/lib/services/session_publisher.dart @@ -0,0 +1,44 @@ +import 'dart:developer' as developer; + +import 'package:wake_alarm_sync/services/alarm_sync_service.dart'; +import 'package:wake_alarm_sync/services/firebase_backend.dart'; +import 'package:wake_alarm_sync/services/settings_sync.dart'; +import 'package:wake_alarm_sync/services/sync_settings.dart'; + +/// Pushes the finished session's record to the PC, best effort. +/// +/// Runs from the session screen, unattended, at the end of a morning: a +/// backend that is down must not keep the screen up. The home screen's +/// startup publish stages the same history again, so a push that fails here +/// is retried the next time the app is opened. +class SessionPublisher { + /// Creates a publisher; [open] is injectable for tests. + SessionPublisher({Future Function()? open}) + : _open = open ?? AlarmSyncService.open; + + final Future Function() _open; + + /// Stages and pushes; returns a status line, never throws. + Future publish() async { + try { + final settings = await SyncSettings.load(); + final hasFirebase = await loadAccount() != null; + if (!settings.isConfigured && !hasFirebase) { + return 'No sync backend — session kept locally'; + } + final service = await _open(); + await stageLocalSettings(service); + await service.push(settings.token); + await applySyncedSettings(service); + return 'Session synced to PC ✓'; + } on Exception catch (e, stack) { + developer.log( + 'session publish failed: $e', + name: 'WakeAlarmSession', + error: e, + stackTrace: stack, + ); + return 'Session kept locally (sync failed)'; + } + } +} diff --git a/phone_app/lib/services/session_rules.dart b/phone_app/lib/services/session_rules.dart new file mode 100644 index 0000000..40be258 --- /dev/null +++ b/phone_app/lib/services/session_rules.dart @@ -0,0 +1,193 @@ +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; +import 'package:wake_alarm_sync/services/weight_entry.dart'; + +/// What a clock tick decided; the driver acts on it, the session records it. +class SessionTick { + /// Creates a tick result. + const SessionTick({this.changed = false, this.ringReason, this.note}); + + /// Whether the session must be re-persisted. + final bool changed; + + /// Why to ring right now, or null. + /// + /// Set only for a stillness ring or a deadline the native alarm should + /// already have fired — calling the ring twice is harmless, missing it is + /// not. + final String? ringReason; + + /// Something to show, or null. + final String? note; +} + +/// Grace after a deadline before Dart rings it itself, in case the +/// AlarmManager alarm did not. +const Duration _deadlineGrace = Duration(seconds: 20); + +/// Starts and advances a [MorningSession]; the rules half of the record. +extension SessionRules on MorningSession { + /// Begins today's session, skipping every leg whose tag does not exist. + /// + /// With NFC off or no session tags registered this is a weigh-in and + /// nothing else — the feature must be usable before it is configured, and + /// a leg that can never pass must never be required. + static MorningSession start({ + required DateTime now, + required SessionTagSettings tags, + required bool nfcAvailable, + }) { + final session = MorningSession( + date: dateKey(now), + startedAt: now, + updatedAt: now, + bathroomTagRequired: + nfcAvailable && tags.tagAt(SessionTagSlot.bathroom) != null, + ); + for (final leg in SessionLeg.values) { + if (leg == SessionLeg.bathroomIn) continue; + if (!nfcAvailable || tags.tagAt(leg.slot) == null) { + session.passedAt[leg] = now; + session.passedHow[leg] = LegPass.skipped; + } + } + return session; + } + + /// `yyyy-mm-dd` of [now], local. + static String dateKey(DateTime now) => now.toIso8601String().substring(0, 10); + + /// Records a typed, already-validated weight. + /// + /// Pending until the bathroom tag confirms it; without a bathroom tag it + /// is the whole first leg. + String enterWeight(double kg, DateTime now) { + if (currentLeg != SessionLeg.bathroomIn) return 'Already weighed in'; + updatedAt = now; + if (!bathroomTagRequired) { + weightKg = kg; + _pass(SessionLeg.bathroomIn, now, LegPass.tag); + return '$kg kg noted'; + } + pendingWeightKg = kg; + pendingWeightAt = now; + return '$kg kg — now tap the bathroom tag within ' + '${confirmWindow.inMinutes} min'; + } + + /// Applies a tag tap for [slot]; only the live leg's room advances. + String onTag(SessionTagSlot slot, DateTime now) { + final leg = currentLeg; + if (leg == null) return 'Session finished'; + if (slot != leg.slot) return 'Not the ${leg.slot.name} tag'; + switch (leg) { + case SessionLeg.bathroomIn: + final typedAt = pendingWeightAt; + final kg = pendingWeightKg; + if (kg == null || typedAt == null) { + return 'Weigh in first, then tap the bathroom tag'; + } + if (now.difference(typedAt) > confirmWindow) { + _clearPendingWeight(now); + return 'That weight expired — type it again at the scale'; + } + weightKg = kg; + _clearPendingWeight(now); + case SessionLeg.showerDone: + final soonest = earliest(leg)!; + if (now.isBefore(soonest)) { + final left = soonest.difference(now); + return 'Too early — shower first (${left.inMinutes + 1} min left)'; + } + case SessionLeg.dressed || SessionLeg.atDesk: + break; + } + _pass(leg, now, LegPass.tag); + return outcome == SessionOutcome.completed + ? 'Session complete — have a good day' + : 'Done: ${leg.label}'; + } + + /// Advances the clocks to [now]. + SessionTick tick(DateTime now) { + final leg = currentLeg; + if (!isActive || leg == null) return const SessionTick(); + final typedAt = pendingWeightAt; + if (typedAt != null && now.difference(typedAt) > confirmWindow) { + _clearPendingWeight(now); + return const SessionTick( + changed: true, + note: 'That weight expired — type it again at the scale', + ); + } + if (now.isBefore(deadline(leg))) return const SessionTick(); + if (deadlineRung.contains(leg)) { + if (now.isBefore(bypassAt(leg))) return const SessionTick(); + // The dead-tag hatch: the re-ring has been paid, the grace has run. + _pass(leg, now, LegPass.bypassed); + return SessionTick(changed: true, note: 'Skipped: ${leg.label}'); + } + if (!canReRing) { + outcome = SessionOutcome.failed; + updatedAt = now; + return const SessionTick( + changed: true, + note: 'Missed with no re-rings left — session failed', + ); + } + if (now.isBefore(deadline(leg).add(_deadlineGrace))) { + return const SessionTick(); + } + return SessionTick(ringReason: 'deadline:${leg.name}'); + } + + /// Whether the phone has lain still long enough to ring. + bool stillnessRingDue(Duration? idle) => + isActive && + canReRing && + !stillnessSuspended && + idle != null && + idle >= MorningSession.stillnessLimit; + + /// Names the re-ring the driver is about to trigger. + void markReRing(String reason, DateTime now) { + pendingReRingReason = reason; + updatedAt = now; + } + + /// Records that a re-ring was dismissed; the session resumes here. + /// + /// A leg whose deadline has already passed is marked as rung whatever the + /// reason: its native alarm fired into the ring that was already sounding, + /// so ringing it again on resume would be a second bill for one miss. + void recordReRing(DateTime now) { + final leg = currentLeg; + reRings++; + reRingReasons.add(pendingReRingReason ?? 'deadline:${leg?.name ?? 'none'}'); + pendingReRingReason = null; + if (leg != null && !now.isBefore(deadline(leg))) deadlineRung.add(leg); + updatedAt = now; + } + + /// The instant to arm natively for the live leg, or null when nothing + /// should ring: no legs left, the leg already re-rang, or no re-rings left. + DateTime? nextDeadline() { + final leg = currentLeg; + if (!isActive || leg == null) return null; + if (deadlineRung.contains(leg) || !canReRing) return null; + return deadline(leg); + } + + void _pass(SessionLeg leg, DateTime now, LegPass how) { + passedAt[leg] = now; + passedHow[leg] = how; + updatedAt = now; + if (currentLeg == null) outcome = SessionOutcome.completed; + } + + void _clearPendingWeight(DateTime now) { + pendingWeightKg = null; + pendingWeightAt = null; + updatedAt = now; + } +} diff --git a/phone_app/lib/services/session_store.dart b/phone_app/lib/services/session_store.dart new file mode 100644 index 0000000..fcc3bbf --- /dev/null +++ b/phone_app/lib/services/session_store.dart @@ -0,0 +1,130 @@ +import 'dart:convert'; + +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_json.dart'; + +/// Persistence for the morning session: the live one and the last month. +/// +/// Written after every change (see `MorningSession`): the session screen is +/// not guaranteed to survive its own thirty minutes, and a re-ring replaces +/// the whole Flutter engine. The history is what the home screen shows and +/// what the synced record carries. +class SessionStore { + /// Creates a store; [prefs] is injectable for tests. + SessionStore({this.prefs}); + + /// SharedPreferences key holding today's session as JSON. + static const String kCurrentKey = 'session.current'; + + /// SharedPreferences key holding finished sessions, newest first. + static const String kHistoryKey = 'session.history'; + + /// Finished sessions kept locally. + static const int keep = 30; + + /// The backing store, opened lazily when not injected. + SharedPreferences? prefs; + + Future get _store async => + prefs ??= await SharedPreferences.getInstance(); + + /// The live session, or null when there is none. + Future loadCurrent() async { + final prefs = await _store; + return _decodeOne(prefs.getString(kCurrentKey)); + } + + /// Persists [session] as the live one. + Future save(MorningSession session) async { + final prefs = await _store; + await prefs.setString(kCurrentKey, jsonEncode(session.toJson())); + } + + /// Moves [session] into the history and clears the live slot. + /// + /// Replaces any history entry for the same date: a second session on one + /// day (a probe, a re-ring after a finish) is the newer truth. + Future archive(MorningSession session) async { + final prefs = await _store; + final next = [ + session, + ...(await history()).where((s) => s.date != session.date), + ]; + await _writeHistory(prefs, next); + await prefs.remove(kCurrentKey); + } + + /// Finished sessions, newest first. + Future> history() async { + final prefs = await _store; + return decodeHistory(prefs.getString(kHistoryKey)); + } + + /// The most recent confirmed weight, or null when never weighed. + Future lastWeightKg() async { + for (final session in await history()) { + final kg = session.weightKg; + if (kg != null) return kg; + } + return null; + } + + /// Merges [remote] sessions into the history; the newer `updatedAt` wins + /// per date. + /// + /// The restore path for a reinstall, and how two installs' mornings end up + /// in one list. Returns whether anything changed. + Future mergeHistory(List remote) async { + final prefs = await _store; + final byDate = { + for (final s in await history()) s.date: s, + }; + var changed = false; + for (final s in remote) { + final local = byDate[s.date]; + if (local == null || s.updatedAt.isAfter(local.updatedAt)) { + byDate[s.date] = s; + changed = true; + } + } + if (!changed) return false; + final merged = byDate.values.toList() + ..sort((a, b) => b.date.compareTo(a.date)); + await _writeHistory(prefs, merged); + return true; + } + + Future _writeHistory( + SharedPreferences prefs, + List sessions, + ) => prefs.setString( + kHistoryKey, + jsonEncode(sessions.take(keep).map((s) => s.toJson()).toList()), + ); + + static MorningSession? _decodeOne(String? raw) { + if (raw == null) return null; + try { + return sessionFromJson(jsonDecode(raw)); + } on FormatException { + return null; + } + } + + /// Decodes a JSON list of sessions, dropping anything malformed. + static List decodeHistory(String? raw) { + if (raw == null) return const []; + try { + return decodeSessions(jsonDecode(raw)); + } on FormatException { + return const []; + } + } + + /// Decodes an already-parsed list of session maps. + static List decodeSessions(Object? decoded) { + if (decoded is! List) return const []; + return decoded.map(sessionFromJson).nonNulls.toList(); + } +} diff --git a/phone_app/lib/services/session_sync.dart b/phone_app/lib/services/session_sync.dart new file mode 100644 index 0000000..e95e3b7 --- /dev/null +++ b/phone_app/lib/services/session_sync.dart @@ -0,0 +1,95 @@ +/// The morning session's tags and history, carried on the synced alarm +/// record next to the ring tags (`settings_sync.dart`). +/// +/// Same shape, same reasons: the tags are properties of the flat and must +/// survive a reinstall; the history is what makes a week of mornings +/// judgeable, and it is where diet-guard's PC side reads the weight from. +/// The PC alarm parser ignores every field it does not name, so nothing +/// here can move the alarm time. +library; + +import 'package:wake_alarm_sync/services/alarm_sync_service.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_json.dart'; +import 'package:wake_alarm_sync/services/session_store.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; +import 'package:wake_alarm_sync/services/settings_sync.dart'; + +/// Field holding the session tag ids, one string per [SessionTagSlot]. +const sessionTagsField = 'session_tag_ids'; + +/// Field holding the last [sessionsCarried] finished sessions, newest first. +const sessionsField = 'morning_sessions'; + +/// Field holding `{date, kg}` of the newest confirmed weigh-in. +/// +/// Redundant with [sessionsField] on purpose: a reader that wants one +/// number (diet-guard's budget) should not have to know the session shape. +const latestWeightField = 'latest_weight_kg'; + +/// How many finished sessions ride on the record. +const sessionsCarried = 14; + +/// Copies local session data newer than the log's copy onto the record. +Future stageSessionData( + AlarmSyncService service, { + SessionStore? store, +}) async { + final tags = await SessionTagSettings.load(); + await stageField( + service, + sessionTagsField, + tags.editedAt, + tags.tagIds, + configured: tags.isConfigured, + ); + final history = await (store ?? SessionStore()).history(); + if (history.isEmpty) return; + final newest = history + .map((s) => s.updatedAt) + .reduce((a, b) => a.isAfter(b) ? a : b); + final stamp = newest.toUtc().toIso8601String(); + await stageField( + service, + sessionsField, + stamp, + history.take(sessionsCarried).map((s) => s.toJson()).toList(), + configured: true, + ); + final weighed = history.where((s) => s.weightKg != null).firstOrNull; + if (weighed == null) return; + await stageField(service, latestWeightField, stamp, { + 'date': weighed.date, + 'kg': weighed.weightKg, + }, configured: true); +} + +/// Writes log values newer than the local copy into local storage. +/// +/// Sessions merge per date rather than replace: two installs' mornings end +/// up in one list, and a peer's shorter list cannot truncate ours. +Future applySyncedSessionData( + AlarmSyncService service, { + SessionStore? store, +}) async { + final tags = await SessionTagSettings.load(); + final tagField = service.field(sessionTagsField); + if (tagField != null && isNewer(tagField.$2, tags.editedAt)) { + final ids = tagField.$1; + if (ids is List) { + await SessionTagSettings.replaceAll( + ids.whereType().toList(), + stampOf(tagField.$2), + ); + } + } + final sessions = service.field(sessionsField); + if (sessions == null) return; + await (store ?? SessionStore()).mergeHistory( + SessionStore.decodeSessions(sessions.$1), + ); +} + +/// The sessions currently on the record, for tests and diagnostics. +List sessionsOnRecord(AlarmSyncService service) => + SessionStore.decodeSessions(service.field(sessionsField)?.$1); diff --git a/phone_app/lib/services/session_tag_settings.dart b/phone_app/lib/services/session_tag_settings.dart new file mode 100644 index 0000000..a5462a1 --- /dev/null +++ b/phone_app/lib/services/session_tag_settings.dart @@ -0,0 +1,111 @@ +import 'dart:convert'; + +import 'package:shared_preferences/shared_preferences.dart'; + +/// The rooms the morning session walks through, one NFC tag each. +enum SessionTagSlot { + /// By the scale and the shower; tapped twice, before and after. + bathroom, + + /// Where the clothes are. + wardrobe, + + /// Where the day starts — the PC. + desk, +} + +/// Persisted morning-session configuration: one tag per [SessionTagSlot]. +/// +/// Separate from `RoomProofSettings`: those two tags gate the *ring*, these +/// three gate what comes after it. A slot may hold the same physical tag as +/// a ring slot (the bathroom tag is often ring tag 2), but the three session +/// slots must be distinct from each other — one tag satisfying two rooms +/// removes the walk between them. +/// +/// A slot left empty is not an error: the session skips that leg. That is +/// what makes the feature usable on the first morning after the update, +/// before any of the three has been registered. +class SessionTagSettings { + /// Creates settings from the registered tag ids, one per slot. + const SessionTagSettings({ + this.tagIds = const ['', '', ''], + this.editedAt = '', + }); + + /// SharedPreferences key holding the tag ids as a JSON list. + static const String kTagsKey = 'session.tagIds'; + + /// SharedPreferences key holding when the tags were last changed (ISO). + /// + /// The stamp the cross-device merge compares (`session_sync.dart`). + static const String kEditedAtKey = 'session.editedAt'; + + /// Registered tag ids by [SessionTagSlot.index]; '' means unset. + final List tagIds; + + /// When [tagIds] was last set, ISO format, or '' when never. + final String editedAt; + + /// The tag registered for [slot], or null when unset. + String? tagAt(SessionTagSlot slot) { + final id = tagIds[slot.index]; + return id.isEmpty ? null : id; + } + + /// Which slot [tagId] is registered under, or null for an unknown tag. + SessionTagSlot? slotOf(String tagId) { + for (final slot in SessionTagSlot.values) { + if (tagAt(slot) == tagId) return slot; + } + return null; + } + + /// Whether any slot is registered at all. + bool get isConfigured => tagIds.any((id) => id.isNotEmpty); + + /// Normalises [raw] to exactly one entry per slot. + static List padded(List raw) => List.generate( + SessionTagSlot.values.length, + (i) => i < raw.length ? raw[i] : '', + ); + + /// Loads the stored configuration. + static Future load() async { + final prefs = await SharedPreferences.getInstance(); + final stored = prefs.getString(kTagsKey); + if (stored == null) return const SessionTagSettings(); + return SessionTagSettings( + tagIds: padded(_decode(stored)), + editedAt: prefs.getString(kEditedAtKey) ?? '', + ); + } + + /// Decodes the stored JSON list, treating anything malformed as unset. + static List _decode(String stored) { + try { + final decoded = jsonDecode(stored); + if (decoded is! List) return const []; + return decoded.whereType().toList(); + } on FormatException { + return const []; + } + } + + /// Stores [tagId] in [slot], leaving the others untouched, stamped now. + static Future saveTagAt(SessionTagSlot slot, String tagId) async { + final current = await load(); + final next = List.of(current.tagIds); + next[slot.index] = tagId; + await replaceAll(next, DateTime.now().toIso8601String()); + } + + /// Stores [tagIds] wholesale with the given [editedAt]. + /// + /// The sync merge uses this to apply a winner from another install with + /// that side's real edit time, so the next merge does not push it back. + static Future replaceAll(List tagIds, String editedAt) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(kTagsKey, jsonEncode(padded(tagIds))); + await prefs.setString(kEditedAtKey, editedAt); + } +} diff --git a/phone_app/lib/services/settings_sync.dart b/phone_app/lib/services/settings_sync.dart index e4ebeab..0027b87 100644 --- a/phone_app/lib/services/settings_sync.dart +++ b/phone_app/lib/services/settings_sync.dart @@ -21,6 +21,7 @@ import 'package:crdt_sync/crdt_sync.dart'; import 'package:wake_alarm_sync/services/alarm_sync_service.dart'; import 'package:wake_alarm_sync/services/home_location_settings.dart'; import 'package:wake_alarm_sync/services/room_proof_settings.dart'; +import 'package:wake_alarm_sync/services/session_sync.dart'; /// Field holding the registered tag ids, one string per slot. const nfcTagsField = 'nfc_tag_ids'; @@ -34,7 +35,7 @@ int _msOf(String editedAt) => DateTime.tryParse(editedAt)?.toUtc().millisecondsSinceEpoch ?? 0; /// The stamp a value applied from the log carries locally. -String _stampOf(Hlc hlc) => DateTime.fromMillisecondsSinceEpoch( +String stampOf(Hlc hlc) => DateTime.fromMillisecondsSinceEpoch( hlc.wallTimeMs, isUtc: true, ).toIso8601String(); @@ -49,7 +50,7 @@ String _stampOf(Hlc hlc) => DateTime.fromMillisecondsSinceEpoch( /// stamped peer. Future stageLocalSettings(AlarmSyncService service) async { final tags = await RoomProofSettings.load(); - await _stage( + await stageField( service, nfcTagsField, tags.editedAt, @@ -57,20 +58,22 @@ Future stageLocalSettings(AlarmSyncService service) async { configured: tags.nfcTagIds.any((id) => id.isNotEmpty), ); final home = await HomeLocationSettings.load(); - await _stage( + await stageField( service, homeLocationField, home.editedAt, home.toJson(), configured: home.isConfigured, ); + await stageSessionData(service); } /// The stamp of a pre-stamp value: just above the epoch, so any real edit /// wins, but present, so it is pushed rather than silently dropped. const _legacyMs = 1; -Future _stage( +/// Stages one field if the local [editedAt] beats the log's stamp. +Future stageField( AlarmSyncService service, String field, String editedAt, @@ -94,28 +97,30 @@ Future _stage( Future applySyncedSettings(AlarmSyncService service) async { final tags = await RoomProofSettings.load(); final tagField = service.field(nfcTagsField); - if (tagField != null && _newer(tagField.$2, tags.editedAt)) { + if (tagField != null && isNewer(tagField.$2, tags.editedAt)) { final ids = tagField.$1; if (ids is List) { await RoomProofSettings.replaceAll( ids.whereType().toList(), - _stampOf(tagField.$2), + stampOf(tagField.$2), ); } } final home = await HomeLocationSettings.load(); final homeField = service.field(homeLocationField); - if (homeField != null && _newer(homeField.$2, home.editedAt)) { + if (homeField != null && isNewer(homeField.$2, home.editedAt)) { final json = homeField.$1; if (json is Map) { await HomeLocationSettings.applySynced( HomeLocationSettings.fromJson( Map.from(json), - ).withEditedAt(_stampOf(homeField.$2)), + ).withEditedAt(stampOf(homeField.$2)), ); } } + await applySyncedSessionData(service); } -bool _newer(Hlc remote, String localEditedAt) => +/// Whether [remote]'s wall time beats the local ISO [localEditedAt]. +bool isNewer(Hlc remote, String localEditedAt) => localEditedAt.isEmpty || remote.wallTimeMs > _msOf(localEditedAt); diff --git a/phone_app/lib/services/weight_entry.dart b/phone_app/lib/services/weight_entry.dart new file mode 100644 index 0000000..279eb4c --- /dev/null +++ b/phone_app/lib/services/weight_entry.dart @@ -0,0 +1,90 @@ +/// Validation for the morning weigh-in. +/// +/// A typed number, not a Bluetooth scale — the ring path takes no plugins. +/// Two gates stand in for the hardware: the value has to be plausible, and +/// the bathroom tag has to follow it within [confirmWindow] (enforced by +/// `MorningSession`, which is what stops it being typed from bed). +library; + +/// Lightest value accepted, in kg. +const double minWeightKg = 30; + +/// Heaviest value accepted, in kg. +const double maxWeightKg = 250; + +/// Largest overnight change accepted without retyping, in kg. +const double maxWeightJumpKg = 3; + +/// How long a typed weight stays valid before the bathroom tag confirms it. +const Duration confirmWindow = Duration(minutes: 2); + +/// What a weigh-in attempt came to. +enum WeightVerdict { + /// Accepted. + ok, + + /// Not a number. + unparsable, + + /// Outside [minWeightKg]..[maxWeightKg]. + outOfRange, + + /// More than [maxWeightJumpKg] from the last entry; type it again to + /// confirm. + needsConfirm, +} + +/// A checked weigh-in: the verdict, the parsed value and a line for the UI. +class WeightCheck { + /// Creates a result. + const WeightCheck(this.verdict, {required this.detail, this.kg}); + + /// What happened. + final WeightVerdict verdict; + + /// The parsed value, present whenever [detail] could name one. + final double? kg; + + /// Human-readable reason, shown on the session screen. + final String detail; + + /// Whether the value was accepted. + bool get accepted => verdict == WeightVerdict.ok; +} + +/// Parses [text] as kilograms; a decimal comma is fine. +double? parseWeight(String text) => + double.tryParse(text.trim().replaceAll(',', '.')); + +/// Checks [text] against the range and the last known weight. +/// +/// [confirming] is the value the user was just asked to retype: an identical +/// second entry passes the jump check, a different one starts over. Without +/// [last] there is nothing to jump from, so only the range applies. +WeightCheck checkWeight(String text, {double? last, double? confirming}) { + final kg = parseWeight(text); + if (kg == null) { + return const WeightCheck( + WeightVerdict.unparsable, + detail: 'Enter your weight in kg, e.g. 72.4', + ); + } + if (kg < minWeightKg || kg > maxWeightKg) { + return WeightCheck( + WeightVerdict.outOfRange, + kg: kg, + detail: '$kg kg is not a body weight', + ); + } + if (last != null && (kg - last).abs() > maxWeightJumpKg) { + if (confirming != kg) { + final delta = (kg - last).toStringAsFixed(1); + return WeightCheck( + WeightVerdict.needsConfirm, + kg: kg, + detail: 'That is $delta kg from last time — type it again to confirm', + ); + } + } + return WeightCheck(WeightVerdict.ok, kg: kg, detail: '$kg kg noted'); +} diff --git a/phone_app/scripts/emu_morning.py b/phone_app/scripts/emu_morning.py new file mode 100755 index 0000000..825589f --- /dev/null +++ b/phone_app/scripts/emu_morning.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""Drive the whole morning on the emulator over adb. + +Companion to ``lib/main_session_probe.dart``: that entrypoint replaces the +phone's NFC and step sensor with files, and this script writes those files +and types the challenge answers it reads back from logcat. Everything else +(the ring service, the re-ring alarms, the session clocks) is the real code. + + scripts/emu_morning.py dismiss # tag 1, walk, tag 2, 3 answers + scripts/emu_morning.py tag bath # one session tag + scripts/emu_morning.py idle 300000 # the phone "lay still" 5 min + scripts/emu_morning.py weight 72.4 # type a weight and submit + scripts/emu_morning.py shot out.png # screenshot + +Reads answers from a ``flutter run`` log (``--log``) or from ``adb logcat``. +No image library: the submit button is found in ``screencap``'s raw RGBA +dump by its gold colour. +""" + +from __future__ import annotations + +import argparse +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys +import time + +PACKAGE = "com.kuhy.wake_alarm_sync" +FILES = f"/sdcard/Android/data/{PACKAGE}/files" +KEY_ENTER = "66" +KEY_DEL = "67" +KEY_CTRL_A = ("113", "29") +ANSWER_RE = re.compile(r"answer=(\S+)") +# The FilledButton's gold, as (min red, green range, max blue). +GOLD_RED_MIN = 170 +GOLD_GREEN = (120, 170) +GOLD_BLUE_MAX = 90 +# Columns sampled per row, and gold samples that make a row "button". +SAMPLE_STEP = 4 +GOLD_HITS_MIN = 20 +# The text field sits this fraction of the screen height above the button. +FIELD_ABOVE_BUTTON = 0.079 +ADB = shutil.which("adb") or "/usr/bin/adb" + + +def adb(serial: str, *args: str) -> bytes: + """Runs one adb command and returns its raw stdout.""" + return subprocess.run( + [ADB, "-s", serial, *args], capture_output=True, check=False + ).stdout + + +def adb_text(serial: str, *args: str) -> str: + """Runs one adb command and returns its stdout as text.""" + return adb(serial, *args).decode(errors="replace") + + +def write_file(serial: str, name: str, content: str) -> None: + """Writes one harness input file on the device.""" + adb(serial, "shell", f"mkdir -p {FILES} && printf %s '{content}' > {FILES}/{name}") + + +def screenshot(serial: str, path: Path) -> None: + """Captures the screen as PNG to [path].""" + path.write_bytes(adb(serial, "exec-out", "screencap", "-p")) + + +def raw_screen(serial: str) -> tuple[int, int, bytes]: + """The screen as (width, height, RGBA bytes), from screencap's raw dump.""" + data = adb(serial, "exec-out", "screencap") + width, height = struct.unpack(" tuple[int, int] | None: + """(row, screen height) of the gold FilledButton, or None when absent.""" + width, height, pixels = raw_screen(serial) + rows = [] + for y in range(height): + hits = 0 + for x in range(0, width, SAMPLE_STEP): + i = (y * width + x) * 4 + red, green, blue = pixels[i], pixels[i + 1], pixels[i + 2] + if ( + red > GOLD_RED_MIN + and GOLD_GREEN[0] < green < GOLD_GREEN[1] + and blue < GOLD_BLUE_MAX + ): + hits += 1 + if hits > GOLD_HITS_MIN: + rows.append(y) + if not rows: + return None + return (rows[0] + rows[-1]) // 2, height + + +def focus_field(serial: str) -> bool: + """Taps the text field sitting above the submit button.""" + found = find_button_y(serial) + if found is None: + return False + y, height = found + width = raw_screen(serial)[0] + field_y = int(y - height * FIELD_ABOVE_BUTTON) + adb(serial, "shell", "input", "tap", str(width // 2), str(field_y)) + time.sleep(1) + return True + + +def type_and_submit(serial: str, text: str) -> None: + """Focuses the field, replaces its content with [text], presses Enter.""" + if not focus_field(serial): + msg = "no submit button on screen" + raise SystemExit(msg) + adb(serial, "shell", "input", "keycombination", *KEY_CTRL_A) + adb(serial, "shell", "input", "keyevent", KEY_DEL) + adb(serial, "shell", "input", "text", text) + time.sleep(0.5) + adb(serial, "shell", "input", "keyevent", KEY_ENTER) + time.sleep(2) + + +def log_text(serial: str, log: Path | None) -> str: + """The flutter run log, or the device's flutter logcat.""" + return log.read_text() if log else adb_text(serial, "logcat", "-d", "-s", "flutter") + + +def last_answer(serial: str, log: Path | None) -> str | None: + """The newest challenge answer the ring logged.""" + found = ANSWER_RE.findall(log_text(serial, log)) + return found[-1] if found else None + + +def session_started(serial: str, log: Path | None) -> bool: + """Whether the session screen has logged its start since the last ring.""" + text = log_text(serial, log) + return text.rfind("WakeAlarmSession: started") > text.rfind("challenge kind=") + + +def dismiss(serial: str, log: Path | None) -> None: + """Tag 1, thirty steps, tag 2, then answers until the session starts.""" + write_file(serial, "steps", "30") + write_file(serial, "tag", "ring1") + time.sleep(4) + write_file(serial, "tag", "ring2") + time.sleep(3) + for _ in range(8): + answer = last_answer(serial, log) + if answer is None: + msg = "no challenge logged yet" + raise SystemExit(msg) + type_and_submit(serial, answer) + if session_started(serial, log): + return + msg = "still ringing after eight answers" + raise SystemExit(msg) + + +def main(argv: list[str]) -> int: + """CLI entry.""" + parser = argparse.ArgumentParser(description=__doc__.split("\n", maxsplit=1)[0]) + parser.add_argument("--serial", default="emulator-5554") + parser.add_argument("--log", type=Path, help="flutter run log to read answers from") + sub = parser.add_subparsers(dest="cmd", required=True) + sub.add_parser("dismiss") + sub.add_parser("tag").add_argument("id") + sub.add_parser("idle").add_argument("ms") + sub.add_parser("weight").add_argument("kg") + sub.add_parser("shot").add_argument("path", type=Path) + args = parser.parse_args(argv) + if args.cmd == "dismiss": + dismiss(args.serial, args.log) + elif args.cmd == "tag": + write_file(args.serial, "tag", args.id) + elif args.cmd == "idle": + write_file(args.serial, "idle_ms", args.ms) + elif args.cmd == "weight": + type_and_submit(args.serial, args.kg) + elif args.cmd == "shot": + screenshot(args.serial, args.path) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/phone_app/test/home_history_card_test.dart b/phone_app/test/home_history_card_test.dart new file mode 100644 index 0000000..adcdaef --- /dev/null +++ b/phone_app/test/home_history_card_test.dart @@ -0,0 +1,83 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/screens/home_history_card.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_rules.dart'; +import 'package:wake_alarm_sync/services/session_store.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +MorningSession _session( + DateTime at, { + double? kg, + int reRings = 0, + SessionOutcome outcome = SessionOutcome.completed, +}) => + SessionRules.start( + now: at, + tags: const SessionTagSettings(), + nfcAvailable: false, + ) + ..weightKg = kg + ..reRings = reRings + ..outcome = outcome; + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + test('describes a morning in one line', () { + expect( + describeMorning( + _session(DateTime(2026, 9, 17, 8), kg: 72.4, reRings: 1), + previousWeight: 72.7, + ), + '09-17 ✓ 1 re-ring · 72.4 kg (−0.3)', + ); + expect( + describeMorning( + _session( + DateTime(2026, 9, 16, 8), + kg: 73, + outcome: SessionOutcome.failed, + ), + previousWeight: 72, + ), + '09-16 ✗ 0 re-rings · 73.0 kg (+1.0)', + ); + expect( + describeMorning( + _session(DateTime(2026, 9, 15, 8), kg: 72), + previousWeight: 72, + ), + '09-15 ✓ 0 re-rings · 72.0 kg (±0.0)', + ); + expect( + describeMorning( + _session(DateTime(2026, 9, 14, 8), outcome: SessionOutcome.active), + ), + '09-14 … 0 re-rings', + ); + }); + + testWidgets('is absent until a morning has finished', (tester) async { + await tester.pumpWidget(const MaterialApp(home: HomeHistoryCard())); + await tester.pump(); + expect(find.text('Last mornings'), findsNothing); + }); + + testWidgets('lists the last seven with weight deltas', (tester) async { + final store = SessionStore(); + for (var day = 1; day <= 9; day++) { + await store.archive(_session(DateTime(2026, 9, day, 8), kg: 70.0 + day)); + } + await tester.pumpWidget(const MaterialApp(home: HomeHistoryCard())); + await tester.pump(); + expect(find.text('Last mornings'), findsOneWidget); + expect( + find.textContaining('09-09 ✓ 0 re-rings · 79.0 kg (+1.0)'), + findsOne, + ); + expect(find.textContaining('09-03'), findsOneWidget); + expect(find.textContaining('09-02'), findsNothing); + }); +} diff --git a/phone_app/test/ring_bypass_test.dart b/phone_app/test/ring_bypass_test.dart index 94a736b..2d37db1 100644 --- a/phone_app/test/ring_bypass_test.dart +++ b/phone_app/test/ring_bypass_test.dart @@ -93,6 +93,21 @@ void main() { expect(find.text('Question 1 of 6'), findsOneWidget); }); + testWidgets('under bypass the walk still needs elapsed time', (tester) async { + // The anti-shake floor lives here now and only here: with no tag to + // prove the walk, 25 "steps" in five seconds is a phone shaken in bed. + // Only an immediate bypass can hit it -- the five-minute one has already + // outlasted the floor by the time it fires. + hasNfc = false; + mockChannel(); + await pumpRing(tester); + steps = 500; + elapsed = const Duration(seconds: 5); + await pollSteps(tester); + expect(find.textContaining('Keep moving'), findsOneWidget); + expect(find.text('Submit'), findsNothing); + }); + testWidgets('an unregistered second tag bypasses immediately', ( tester, ) async { diff --git a/phone_app/test/ring_route_test.dart b/phone_app/test/ring_route_test.dart index 8ea6c39..172a087 100644 --- a/phone_app/test/ring_route_test.dart +++ b/phone_app/test/ring_route_test.dart @@ -74,6 +74,9 @@ void main() { generator: ChallengeGenerator(random: Random(1)), clock: () => elapsed, ), + routes: { + kSessionRoute: (_) => const Scaffold(body: Text('SESSION')), + }, ), ); await tester.pump(); @@ -139,15 +142,20 @@ void main() { expect(find.textContaining('Not tag 1'), findsOneWidget); }); - testWidgets('the walk needs elapsed time, not just a step count', ( + testWidgets('after tag 1 the banked steps pass the walk at once', ( tester, ) async { + // No elapsed-time floor on the normal path (2026-09-16): tag 1 already + // proved the walk, and the floor was two minutes of ringing that nothing + // the user did could shorten. It still applies under bypass -- see + // ring_bypass_test. await pumpRing(tester); await tapTag(tester, _tag1); steps = 500; elapsed = const Duration(seconds: 5); await pollSteps(tester); - expect(find.textContaining('Keep moving'), findsOneWidget); + expect(find.textContaining('Keep moving'), findsNothing); + expect(find.textContaining('Walked far enough'), findsOneWidget); expect(find.text('Tap tag 2'), findsOneWidget); }); @@ -170,10 +178,13 @@ void main() { await tester.pump(); } - // Closing is load-bearing: back is disabled in both halves, so a screen - // left up after the last answer is a dead end over the lockscreen. + // The ring stops, then the morning session takes the screen over (see + // ring_session_handoff_test for the handoff and the away-from-home + // close). Back is disabled in both halves, so the dismiss must always + // lead *somewhere*. expect(calls, contains('dismiss')); - expect(calls, contains('closeRingScreen')); + await tester.pumpAndSettle(); + expect(find.text('SESSION'), findsOneWidget); }); testWidgets('a wrong answer costs the attempt but not the tally', ( @@ -202,7 +213,6 @@ void main() { ); expect(calls, isNot(contains('closeRingScreen'))); }); - } /// Local helper so the test need not import dart:async for one call. diff --git a/phone_app/test/ring_session_handoff_test.dart b/phone_app/test/ring_session_handoff_test.dart new file mode 100644 index 0000000..005ffc8 --- /dev/null +++ b/phone_app/test/ring_session_handoff_test.dart @@ -0,0 +1,138 @@ +import 'dart:math'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/screens/ring_screen.dart'; +import 'package:wake_alarm_sync/screens/session_screen.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/challenge.dart'; +import 'package:wake_alarm_sync/services/home_location_settings.dart'; +import 'package:wake_alarm_sync/services/room_proof_settings.dart'; +import 'package:wake_alarm_sync/services/session_store.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +const String _tag1 = '04a2b3c4'; +const String _tag2 = '04ffee11'; + +/// The dismiss no longer ends the morning: it hands over to the session, +/// inside the same activity, and the session must hear the tags. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late List calls; + Map? presence; + + setUp(() async { + calls = []; + presence = null; + SharedPreferences.setMockInitialValues({}); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel(AlarmScheduler.channelName), + (call) async { + calls.add(call.method); + if (call.method == 'stepCount') return 500; + if (call.method == 'hasNfc') return true; + if (call.method == 'readPresence') return presence; + return null; + }, + ); + await RoomProofSettings.saveNfcTagAt(0, _tag1); + await RoomProofSettings.saveNfcTagAt(1, _tag2); + await SessionTagSettings.saveTagAt(SessionTagSlot.bathroom, 'bath'); + }); + + Future tapTag(WidgetTester tester, String id) async { + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + AlarmScheduler.channelName, + const StandardMethodCodec().encodeMethodCall( + MethodCall('onNfcTag', id), + ), + (_) {}, + ); + await tester.pump(); + } + + /// Pumps the ring inside an app that also knows the session route, with + /// each screen building its own scheduler exactly as production does. + Future pumpApp(WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + routes: { + '/': (_) => RingScreen( + generator: ChallengeGenerator(random: Random(1)), + clock: () => const Duration(minutes: 3), + ), + kSessionRoute: (_) => SessionScreen(publish: () async => 'ok'), + }, + ), + ); + await tester.pump(); + return ChallengeGenerator(random: Random(1)); + } + + /// Tag 1, the walk, tag 2, three answers. + Future dismiss(WidgetTester tester, ChallengeGenerator answers) async { + await tapTag(tester, _tag1); + await tester.pump(kStepPollInterval); + await tester.pump(); + await tapTag(tester, _tag2); + for (var i = 0; i < 3; i++) { + await tester.enterText(find.byType(TextField), answers.next().answer); + await tester.tap(find.text('Submit')); + await tester.pump(); + } + await tester.pumpAndSettle(); + } + + testWidgets('the dismiss opens the session instead of closing', ( + tester, + ) async { + final answers = await pumpApp(tester); + await dismiss(tester, answers); + expect(find.byType(SessionScreen), findsOneWidget); + expect(find.byType(RingScreen), findsNothing); + expect(calls, contains('dismiss')); + expect(calls, isNot(contains('closeRingScreen'))); + expect((await SessionStore().loadCurrent())?.reRings, 0); + }); + + testWidgets('the session hears tags after the ring screen is gone', ( + tester, + ) async { + // The ring screen's dispose runs *after* the session screen's initState, + // and used to wipe the listener the session had just registered: the + // Pixel showed a session that never heard a single tag (2026-09-16). + final answers = await pumpApp(tester); + await dismiss(tester, answers); + await tester.enterText(find.byType(TextField), '72'); + await tester.tap(find.text('Log weight')); + await tester.pump(); + await tapTag(tester, 'bath'); + await tester.pump(); + expect(find.text('Weigh in — 72.0 kg'), findsOneWidget); + expect(find.textContaining('tag counts in'), findsOneWidget); + }); + + testWidgets('away from home the dismiss still just closes', (tester) async { + await HomeLocationSettings.capture(ssid: 'Orange_Home'); + presence = {'ssid': 'Hotel_Guest', 'reason': 'ok'}; + final answers = await pumpApp(tester); + await tester.pump(); + // Away: tags skipped, so the walk and three answers are the whole gate. + await tester.pump(kStepPollInterval); + await tester.pump(); + for (var i = 0; i < 3; i++) { + await tester.enterText(find.byType(TextField), answers.next().answer); + await tester.tap(find.text('Submit')); + await tester.pump(); + } + await tester.pumpAndSettle(); + expect(calls.last, 'closeRingScreen'); + expect(find.byType(SessionScreen), findsNothing); + expect(await SessionStore().loadCurrent(), isNull); + }); +} diff --git a/phone_app/test/services/session_handoff_test.dart b/phone_app/test/services/session_handoff_test.dart new file mode 100644 index 0000000..1e987fa --- /dev/null +++ b/phone_app/test/services/session_handoff_test.dart @@ -0,0 +1,109 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_handoff.dart'; +import 'package:wake_alarm_sync/services/session_rules.dart'; +import 'package:wake_alarm_sync/services/session_store.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final now = DateTime(2026, 9, 17, 8, 4); + var hasNfc = true; + + setUp(() { + hasNfc = true; + SharedPreferences.setMockInitialValues({}); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel(AlarmScheduler.channelName), + (call) async => call.method == 'hasNfc' ? hasNfc : null, + ); + }); + + SessionHandoff handoff() => + SessionHandoff(scheduler: AlarmScheduler(), now: () => now); + + test("the first dismiss starts today's session", () async { + await SessionTagSettings.saveTagAt(SessionTagSlot.desk, 'd'); + expect(await handoff().afterDismiss(away: false), isTrue); + final session = (await SessionStore().loadCurrent())!; + expect(session.date, '2026-09-17'); + expect(session.startedAt, now); + expect(session.reRings, 0); + expect(session.passedHow[SessionLeg.dressed], LegPass.skipped); + expect(session.passedHow.containsKey(SessionLeg.atDesk), isFalse); + }); + + test('without NFC the session is a bare weigh-in', () async { + hasNfc = false; + expect(await handoff().afterDismiss(away: false), isTrue); + final session = (await SessionStore().loadCurrent())!; + expect(session.bathroomTagRequired, isFalse); + }); + + test('away from home there is no session', () async { + expect(await handoff().afterDismiss(away: true), isFalse); + expect(await SessionStore().loadCurrent(), isNull); + }); + + test('a dismiss during a live session is a re-ring', () async { + final store = SessionStore(); + await store.save( + SessionRules.start( + now: now.subtract(const Duration(minutes: 12)), + tags: const SessionTagSettings(tagIds: ['b', 'w', 'd']), + nfcAvailable: true, + ), + ); + expect(await handoff().afterDismiss(away: false), isTrue); + final session = (await store.loadCurrent())!; + expect(session.reRings, 1); + expect(session.reRingReasons, ['deadline:bathroomIn']); + expect(session.deadlineRung, {SessionLeg.bathroomIn}); + }); + + test("a ring after today's session finished just closes", () async { + final store = SessionStore(); + await store.save( + SessionRules.start( + now: now, + tags: const SessionTagSettings(), + nfcAvailable: false, + )..outcome = SessionOutcome.completed, + ); + expect(await handoff().afterDismiss(away: false), isFalse); + }); + + test("a ring after today's session was archived just closes", () async { + final store = SessionStore(); + await store.archive( + SessionRules.start( + now: now.subtract(const Duration(minutes: 40)), + tags: const SessionTagSettings(), + nfcAvailable: false, + )..outcome = SessionOutcome.completed, + ); + expect(await handoff().afterDismiss(away: false), isFalse); + expect(await store.loadCurrent(), isNull); + }); + + test("yesterday's unfinished session is archived as failed", () async { + final store = SessionStore(); + await store.save( + SessionRules.start( + now: now.subtract(const Duration(days: 1)), + tags: const SessionTagSettings(), + nfcAvailable: false, + ), + ); + expect(await handoff().afterDismiss(away: false), isTrue); + final history = await store.history(); + expect(history.single.date, '2026-09-16'); + expect(history.single.outcome, SessionOutcome.failed); + expect((await store.loadCurrent())!.date, '2026-09-17'); + }); +} diff --git a/phone_app/test/services/session_rules_test.dart b/phone_app/test/services/session_rules_test.dart new file mode 100644 index 0000000..9df061f --- /dev/null +++ b/phone_app/test/services/session_rules_test.dart @@ -0,0 +1,249 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_json.dart'; +import 'package:wake_alarm_sync/services/session_rules.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +final DateTime t0 = DateTime(2026, 9, 17, 8, 5); +const SessionTagSettings allTags = SessionTagSettings( + tagIds: ['bath', 'ward', 'desk'], +); + +MorningSession fresh({SessionTagSettings tags = allTags, bool nfc = true}) => + SessionRules.start(now: t0, tags: tags, nfcAvailable: nfc); + +/// Weighs in and taps the bathroom tag, leaving the shower leg live. +MorningSession inBathroom() => fresh() + ..enterWeight(72, t0) + ..onTag(SessionTagSlot.bathroom, t0.add(const Duration(seconds: 30))); + +void main() { + group('start', () { + test('requires every leg when all tags exist', () { + final s = fresh(); + expect(s.currentLeg, SessionLeg.bathroomIn); + expect(s.passedAt, isEmpty); + expect(s.bathroomTagRequired, isTrue); + expect(s.date, '2026-09-17'); + }); + + test('skips legs whose tag is unregistered', () { + final s = fresh( + tags: const SessionTagSettings(tagIds: ['bath', '', 'desk']), + ); + expect(s.passedHow[SessionLeg.dressed], LegPass.skipped); + expect(s.passedHow.containsKey(SessionLeg.atDesk), isFalse); + }); + + test('without NFC it is a weigh-in and nothing else', () { + final s = fresh(nfc: false); + expect(s.bathroomTagRequired, isFalse); + expect(s.currentLeg, SessionLeg.bathroomIn); + s.enterWeight(70, t0); + expect(s.outcome, SessionOutcome.completed); + expect(s.weightKg, 70); + }); + }); + + group('weigh-in', () { + test('stays pending until the bathroom tag confirms it', () { + final s = fresh(); + expect(s.enterWeight(72, t0), contains('tap the bathroom tag')); + expect(s.weightKg, isNull); + expect(s.pendingWeightKg, 72); + s.onTag(SessionTagSlot.bathroom, t0.add(const Duration(minutes: 1))); + expect(s.weightKg, 72); + expect(s.pendingWeightKg, isNull); + expect(s.currentLeg, SessionLeg.showerDone); + }); + + test('a tag without a weight does nothing', () { + final s = fresh(); + expect(s.onTag(SessionTagSlot.bathroom, t0), contains('Weigh in first')); + expect(s.currentLeg, SessionLeg.bathroomIn); + }); + + test('a late tag discards the weight', () { + final s = fresh()..enterWeight(72, t0); + final late = t0.add(const Duration(minutes: 2, seconds: 1)); + expect(s.onTag(SessionTagSlot.bathroom, late), contains('expired')); + expect(s.pendingWeightKg, isNull); + expect(s.currentLeg, SessionLeg.bathroomIn); + }); + + test('the tick expires a pending weight too', () { + final s = fresh()..enterWeight(72, t0); + final tick = s.tick(t0.add(const Duration(minutes: 3))); + expect(tick.changed, isTrue); + expect(tick.note, contains('expired')); + expect(s.pendingWeightKg, isNull); + }); + + test('is refused once the leg has passed', () { + final s = inBathroom(); + expect(s.enterWeight(80, t0), 'Already weighed in'); + expect(s.weightKg, 72); + }); + }); + + group('legs', () { + test('the wrong room does not advance', () { + final s = inBathroom(); + expect(s.onTag(SessionTagSlot.desk, t0), 'Not the bathroom tag'); + expect(s.currentLeg, SessionLeg.showerDone); + }); + + test('the shower tag is refused before eight minutes', () { + final s = inBathroom(); + final early = s + .legStart(SessionLeg.showerDone) + .add(const Duration(minutes: 7)); + expect(s.onTag(SessionTagSlot.bathroom, early), contains('Too early')); + expect(s.currentLeg, SessionLeg.showerDone); + }); + + test('the full walk completes the session', () { + final s = inBathroom(); + final shower = s.earliest(SessionLeg.showerDone)!; + s + ..onTag(SessionTagSlot.bathroom, shower) + ..onTag( + SessionTagSlot.wardrobe, + shower.add(const Duration(minutes: 3)), + ); + final done = s.onTag( + SessionTagSlot.desk, + shower.add(const Duration(minutes: 5)), + ); + expect(done, contains('complete')); + expect(s.outcome, SessionOutcome.completed); + expect(s.currentLeg, isNull); + expect(s.onTag(SessionTagSlot.desk, shower), 'Session finished'); + }); + + test('deadlines follow the previous leg and the shower has its own', () { + final s = inBathroom(); + final tap1 = s.passedAt[SessionLeg.bathroomIn]!; + expect( + s.deadline(SessionLeg.showerDone), + tap1.add(const Duration(minutes: 18)), + ); + expect( + s.earliest(SessionLeg.showerDone), + tap1.add(const Duration(minutes: 8)), + ); + expect( + s.deadline(SessionLeg.bathroomIn), + t0.add(const Duration(minutes: 10)), + ); + expect(s.stillnessSuspended, isTrue); + }); + }); + + group('deadlines and re-rings', () { + test('nothing rings before the deadline', () { + final s = fresh(); + final tick = s.tick(t0.add(const Duration(minutes: 9))); + expect(tick.changed, isFalse); + expect(tick.ringReason, isNull); + expect(s.nextDeadline(), t0.add(const Duration(minutes: 10))); + }); + + test('the native alarm gets a grace before Dart rings itself', () { + final s = fresh(); + final deadline = s.deadline(SessionLeg.bathroomIn); + expect( + s.tick(deadline.add(const Duration(seconds: 5))).ringReason, + isNull, + ); + expect( + s.tick(deadline.add(const Duration(seconds: 25))).ringReason, + 'deadline:bathroomIn', + ); + }); + + test('a dismissed re-ring marks the leg and bypasses it later', () { + final s = fresh(); + final deadline = s.deadline(SessionLeg.bathroomIn); + s.recordReRing(deadline.add(const Duration(minutes: 3))); + expect(s.reRings, 1); + expect(s.reRingReasons, ['deadline:bathroomIn']); + expect(s.deadlineRung, {SessionLeg.bathroomIn}); + expect(s.nextDeadline(), isNull); + expect(s.tick(deadline.add(const Duration(minutes: 4))).changed, isFalse); + final tick = s.tick(deadline.add(const Duration(minutes: 5))); + expect(tick.note, contains('Skipped')); + expect(s.passedHow[SessionLeg.bathroomIn], LegPass.bypassed); + expect(s.currentLeg, SessionLeg.showerDone); + }); + + test( + 'a stillness ring keeps its reason and does not spend the deadline', + () { + final s = fresh() + ..markReRing('still:bathroomIn', t0) + ..recordReRing(t0.add(const Duration(minutes: 3))); + expect(s.reRingReasons, ['still:bathroomIn']); + expect(s.deadlineRung, isEmpty); + expect(s.nextDeadline(), isNotNull); + }, + ); + + test('stillness is due only when live, allowed and not showering', () { + final s = fresh(); + expect(s.stillnessRingDue(const Duration(minutes: 4)), isTrue); + expect(s.stillnessRingDue(const Duration(minutes: 3)), isFalse); + expect(s.stillnessRingDue(null), isFalse); + expect( + inBathroom().stillnessRingDue(const Duration(minutes: 9)), + isFalse, + ); + s.reRings = MorningSession.maxReRings; + expect(s.stillnessRingDue(const Duration(minutes: 9)), isFalse); + }); + + test('a miss with no re-rings left fails the session', () { + final s = fresh()..reRings = MorningSession.maxReRings; + expect(s.nextDeadline(), isNull); + final tick = s.tick(s.deadline(SessionLeg.bathroomIn)); + expect(tick.changed, isTrue); + expect(s.isActive, isFalse); + expect(s.tick(t0).changed, isFalse); + }); + }); + + group('json', () { + test('round-trips every field', () { + final s = inBathroom() + ..markReRing('still:showerDone', t0) + ..recordReRing(t0.add(const Duration(minutes: 5))); + final back = sessionFromJson(s.toJson())!; + expect(back.toJson(), s.toJson()); + expect(back.currentLeg, SessionLeg.showerDone); + expect(back.weightKg, 72); + expect(back.passedHow[SessionLeg.bathroomIn], LegPass.tag); + }); + + test('rejects shapes that are not a session', () { + expect(sessionFromJson({'date': 1}), isNull); + expect(sessionFromJson('x'), isNull); + }); + + test('tolerates missing optionals', () { + final s = sessionFromJson({ + 'date': '2026-09-17', + 'started_at': t0.toIso8601String(), + 'passed': { + 'dressed': {'at': 'garbage'}, + 'atDesk': {'at': t0.toIso8601String()}, + }, + 'deadline_rung': ['nope', 'atDesk'], + })!; + expect(s.updatedAt, t0); + expect(s.passedAt.keys, [SessionLeg.atDesk]); + expect(s.passedHow[SessionLeg.atDesk], LegPass.tag); + expect(s.deadlineRung, {SessionLeg.atDesk}); + expect(s.outcome, SessionOutcome.active); + }); + }); +} diff --git a/phone_app/test/services/session_store_test.dart b/phone_app/test/services/session_store_test.dart new file mode 100644 index 0000000..c6214bd --- /dev/null +++ b/phone_app/test/services/session_store_test.dart @@ -0,0 +1,86 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_rules.dart'; +import 'package:wake_alarm_sync/services/session_store.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +MorningSession session(DateTime at, {double? kg}) => SessionRules.start( + now: at, + tags: const SessionTagSettings(), + nfcAvailable: false, +)..weightKg = kg; + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + test('saves and reloads the live session', () async { + final store = SessionStore(); + expect(await store.loadCurrent(), isNull); + await store.save(session(DateTime(2026, 9, 17, 8), kg: 72)); + final back = await store.loadCurrent(); + expect(back?.date, '2026-09-17'); + expect(back?.weightKg, 72); + }); + + test('archive moves it into the history, newest first', () async { + final store = SessionStore(); + await store.archive(session(DateTime(2026, 9, 16, 8), kg: 71)); + await store.archive(session(DateTime(2026, 9, 17, 8))); + await store.save(session(DateTime(2026, 9, 18, 8))); + await store.archive((await store.loadCurrent())!); + final history = await store.history(); + expect(history.map((s) => s.date), [ + '2026-09-18', + '2026-09-17', + '2026-09-16', + ]); + expect(await store.loadCurrent(), isNull); + expect(await store.lastWeightKg(), 71); + }); + + test('a second session on one date replaces the first', () async { + final store = SessionStore(); + await store.archive(session(DateTime(2026, 9, 17, 8), kg: 70)); + await store.archive(session(DateTime(2026, 9, 17, 9), kg: 72)); + final history = await store.history(); + expect(history, hasLength(1)); + expect(history.single.weightKg, 72); + }); + + test('keeps only the newest thirty', () async { + final store = SessionStore(); + for (var day = 1; day <= 32; day++) { + await store.archive(session(DateTime(2026, 1, day, 8))); + } + expect(await store.history(), hasLength(SessionStore.keep)); + }); + + test('merge takes the newer copy per date', () async { + final store = SessionStore(); + final local = session(DateTime(2026, 9, 17, 8), kg: 70); + await store.archive(local); + final older = session(DateTime(2026, 9, 17, 8), kg: 99) + ..updatedAt = local.updatedAt.subtract(const Duration(hours: 1)); + expect(await store.mergeHistory([older]), isFalse); + final newer = session(DateTime(2026, 9, 17, 8), kg: 72) + ..updatedAt = local.updatedAt.add(const Duration(hours: 1)); + final other = session(DateTime(2026, 9, 10, 8), kg: 68); + expect(await store.mergeHistory([newer, other]), isTrue); + final history = await store.history(); + expect(history.map((s) => s.date), ['2026-09-17', '2026-09-10']); + expect(history.first.weightKg, 72); + }); + + test('malformed storage reads as empty', () async { + SharedPreferences.setMockInitialValues({ + SessionStore.kCurrentKey: '{oops', + SessionStore.kHistoryKey: '[1, "x", {}]', + }); + final store = SessionStore(); + expect(await store.loadCurrent(), isNull); + expect(await store.history(), isEmpty); + expect(SessionStore.decodeHistory('nope'), isEmpty); + expect(SessionStore.decodeSessions('not a list'), isEmpty); + }); +} diff --git a/phone_app/test/services/session_sync_test.dart b/phone_app/test/services/session_sync_test.dart new file mode 100644 index 0000000..8266dcb --- /dev/null +++ b/phone_app/test/services/session_sync_test.dart @@ -0,0 +1,124 @@ +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/services/alarm_sync_service.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_json.dart'; +import 'package:wake_alarm_sync/services/session_rules.dart'; +import 'package:wake_alarm_sync/services/session_store.dart'; +import 'package:wake_alarm_sync/services/session_sync.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; +import 'package:wake_alarm_sync/services/settings_sync.dart'; + +class _MemPersistence implements LogPersistence { + String? text; + + @override + Future read() async => text; + + @override + Future write(String value) async => text = value; +} + +Future _open() => + AlarmSyncService.open(persistence: _MemPersistence(), deviceId: 'me'); + +MorningSession _session(DateTime at, {double? kg}) => SessionRules.start( + now: at, + tags: const SessionTagSettings(), + nfcAvailable: false, +)..weightKg = kg; + +Hlc _at(DateTime when) => + Hlc.newTick('peer', wallTimeMsOverride: when.millisecondsSinceEpoch); + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + group('stageSessionData', () { + test('stages nothing from an install with nothing to say', () async { + final service = await _open(); + await stageSessionData(service); + expect(service.field(sessionTagsField), isNull); + expect(service.field(sessionsField), isNull); + expect(service.field(latestWeightField), isNull); + }); + + test('stages tags, the history and the latest weight', () async { + await SessionTagSettings.saveTagAt(SessionTagSlot.desk, 'd1'); + final store = SessionStore(); + await store.archive(_session(DateTime(2026, 9, 16, 8), kg: 71)); + await store.archive(_session(DateTime(2026, 9, 17, 8))); + final service = await _open(); + await stageSessionData(service); + expect(service.field(sessionTagsField)?.$1, ['', '', 'd1']); + expect(sessionsOnRecord(service).map((s) => s.date), [ + '2026-09-17', + '2026-09-16', + ]); + expect(service.field(latestWeightField)?.$1, { + 'date': '2026-09-16', + 'kg': 71.0, + }); + }); + + test('an unchanged history is not restaged', () async { + await SessionStore().archive(_session(DateTime(2026, 9, 17, 8), kg: 70)); + final service = await _open(); + await stageSessionData(service); + final first = service.field(sessionsField)!.$2; + await stageSessionData(service); + expect(service.field(sessionsField)!.$2, first); + }); + + test('rides along with the ring settings', () async { + await SessionStore().archive(_session(DateTime(2026, 9, 17, 8))); + final service = await _open(); + await stageLocalSettings(service); + expect(service.field(sessionsField), isNotNull); + }); + }); + + group('applySyncedSessionData', () { + test('restores tags and merges sessions from the record', () async { + final service = await _open(); + final when = DateTime(2026, 9, 17, 9); + await service.setFields({ + sessionTagsField: ['b', 'w', 'd'], + sessionsField: [ + _session(DateTime(2026, 9, 15, 8), kg: 69).toJson(), + 'junk', + ], + }, _at(when)); + await applySyncedSettings(service); + final tags = await SessionTagSettings.load(); + expect(tags.tagIds, ['b', 'w', 'd']); + expect(tags.editedAt, stampOf(_at(when))); + final history = await SessionStore().history(); + expect(history.single.date, '2026-09-15'); + expect(history.single.weightKg, 69); + }); + + test('a local registration newer than the record wins', () async { + await SessionTagSettings.saveTagAt(SessionTagSlot.bathroom, 'mine'); + final service = await _open(); + await service.setFields({ + sessionTagsField: ['theirs', '', ''], + }, _at(DateTime(2020))); + await applySyncedSessionData(service); + expect( + (await SessionTagSettings.load()).tagAt(SessionTagSlot.bathroom), + 'mine', + ); + }); + + test('a malformed tag list is left alone', () async { + final service = await _open(); + await service.setFields({ + sessionTagsField: 'not a list', + }, _at(DateTime(2026, 9, 17))); + await applySyncedSessionData(service); + expect((await SessionTagSettings.load()).isConfigured, isFalse); + }); + }); +} diff --git a/phone_app/test/services/session_tag_settings_test.dart b/phone_app/test/services/session_tag_settings_test.dart new file mode 100644 index 0000000..a56d6c0 --- /dev/null +++ b/phone_app/test/services/session_tag_settings_test.dart @@ -0,0 +1,42 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + test('starts empty and unconfigured', () async { + final s = await SessionTagSettings.load(); + expect(s.isConfigured, isFalse); + expect(s.tagAt(SessionTagSlot.bathroom), isNull); + expect(s.slotOf('x'), isNull); + }); + + test('saves per slot, stamped, and finds a tag by id', () async { + await SessionTagSettings.saveTagAt(SessionTagSlot.wardrobe, 'w1'); + final s = await SessionTagSettings.load(); + expect(s.tagAt(SessionTagSlot.wardrobe), 'w1'); + expect(s.tagAt(SessionTagSlot.desk), isNull); + expect(s.slotOf('w1'), SessionTagSlot.wardrobe); + expect(s.isConfigured, isTrue); + expect(DateTime.tryParse(s.editedAt), isNotNull); + }); + + test('replaceAll keeps the given stamp and pads short lists', () async { + await SessionTagSettings.replaceAll(['b'], '2026-01-01T00:00:00'); + final s = await SessionTagSettings.load(); + expect(s.tagIds, ['b', '', '']); + expect(s.editedAt, '2026-01-01T00:00:00'); + }); + + test('malformed storage reads as unset', () async { + SharedPreferences.setMockInitialValues({ + SessionTagSettings.kTagsKey: '{not a list', + }); + expect((await SessionTagSettings.load()).isConfigured, isFalse); + SharedPreferences.setMockInitialValues({ + SessionTagSettings.kTagsKey: '{"a": 1}', + }); + expect((await SessionTagSettings.load()).isConfigured, isFalse); + }); +} diff --git a/phone_app/test/services/weight_entry_test.dart b/phone_app/test/services/weight_entry_test.dart new file mode 100644 index 0000000..44a3f70 --- /dev/null +++ b/phone_app/test/services/weight_entry_test.dart @@ -0,0 +1,32 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:wake_alarm_sync/services/weight_entry.dart'; + +void main() { + test('parses a decimal comma', () { + expect(parseWeight(' 72,4 '), 72.4); + expect(parseWeight('abc'), isNull); + }); + + test('accepts a plausible first weigh-in', () { + final check = checkWeight('72.4'); + expect(check.accepted, isTrue); + expect(check.kg, 72.4); + expect(check.detail, contains('72.4')); + }); + + test('rejects nonsense and out-of-range values', () { + expect(checkWeight('').verdict, WeightVerdict.unparsable); + expect(checkWeight('12').verdict, WeightVerdict.outOfRange); + expect(checkWeight('300').verdict, WeightVerdict.outOfRange); + expect(checkWeight('12').accepted, isFalse); + }); + + test('a jump from last time must be retyped', () { + final first = checkWeight('76', last: 72); + expect(first.verdict, WeightVerdict.needsConfirm); + expect(first.detail, contains('4.0 kg')); + expect(checkWeight('76', last: 72, confirming: 76).accepted, isTrue); + expect(checkWeight('77', last: 72, confirming: 76).accepted, isFalse); + expect(checkWeight('74', last: 72).accepted, isTrue); + }); +} diff --git a/phone_app/test/session_screen_test.dart b/phone_app/test/session_screen_test.dart new file mode 100644 index 0000000..5984cc1 --- /dev/null +++ b/phone_app/test/session_screen_test.dart @@ -0,0 +1,231 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/screens/session_screen.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/morning_session.dart'; +import 'package:wake_alarm_sync/services/session_rules.dart'; +import 'package:wake_alarm_sync/services/session_store.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late List calls; + late DateTime now; + int? idleMs; + var published = 0; + + void mockChannel() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel(AlarmScheduler.channelName), + (call) async { + calls.add(call); + if (call.method == 'hasNfc') return true; + if (call.method == 'motionIdleMillis') return idleMs ?? -1; + return null; + }, + ); + } + + /// Delivers a tag from the platform side, as `NfcReader` does. + Future tap(String tagId) async { + const codec = StandardMethodCodec(); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + AlarmScheduler.channelName, + codec.encodeMethodCall(MethodCall('onNfcTag', tagId)), + (_) {}, + ); + } + + List methods() => calls.map((c) => c.method).toList(); + + Future tick(WidgetTester tester, [int seconds = 1]) async { + for (var i = 0; i < seconds; i++) { + await tester.pump(kSessionTick); + } + await tester.pump(); + } + + setUp(() async { + calls = []; + now = DateTime(2026, 9, 17, 8, 4); + idleMs = null; + published = 0; + SharedPreferences.setMockInitialValues({}); + mockChannel(); + await SessionTagSettings.replaceAll(['bath', 'ward', 'desk'], ''); + }); + + Future pumpSession(WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + routes: { + '/': (_) => SessionScreen( + clock: () => now, + publish: () async { + published++; + return 'pushed'; + }, + ), + '/ring': (_) => const Scaffold(body: Text('RING')), + }, + ), + ); + await tester.pump(); + await tester.pump(); + } + + Future logWeight(WidgetTester tester, String kg) async { + await tester.enterText(find.byType(TextField), kg); + await tester.tap(find.text('Log weight')); + await tester.pump(); + } + + testWidgets('starts a session cold and arms the first deadline', ( + tester, + ) async { + await pumpSession(tester); + expect(find.text('Stay up'), findsOneWidget); + expect(find.text('Weigh in'), findsOneWidget); + expect(find.text('Alarm returns in 10:00'), findsOneWidget); + expect(methods(), contains('beginMotionWatch')); + final arm = calls.firstWhere((c) => c.method == 'armReRing'); + expect(arm.arguments, { + 'atMillis': now.add(MorningSession.legWindow).millisecondsSinceEpoch, + }); + expect((await SessionStore().loadCurrent())?.date, '2026-09-17'); + }); + + testWidgets('walks every leg, then finishes, archives and closes', ( + tester, + ) async { + await pumpSession(tester); + await logWeight(tester, '72,4'); + expect(find.textContaining('now tap the bathroom tag'), findsOneWidget); + expect(find.byType(TextField), findsNothing); + await tap('desk'); + await tester.pump(); + expect(find.text('Not the bathroom tag'), findsOneWidget); + await tap('bath'); + await tester.pump(); + expect(find.text('Weigh in — 72.4 kg'), findsOneWidget); + expect(find.textContaining('tag counts in 08:00'), findsOneWidget); + await tap('bath'); + await tester.pump(); + await tester.pump(); + expect(find.textContaining('Too early'), findsOneWidget); + now = now.add(const Duration(minutes: 9)); + await tick(tester); + expect(find.textContaining('Alarm returns in'), findsOneWidget); + await tap('bath'); + await tap('ward'); + await tap('desk'); + await tester.pump(); + await tester.pump(); + expect(methods(), contains('finishSession')); + expect(methods().last, 'closeRingScreen'); + expect(published, 1); + final store = SessionStore(); + expect(await store.loadCurrent(), isNull); + final done = (await store.history()).single; + expect(done.outcome, SessionOutcome.completed); + expect(done.weightKg, 72.4); + expect(done.reRings, 0); + }); + + testWidgets('a still phone rings and routes to the ring screen', ( + tester, + ) async { + await pumpSession(tester); + await logWeight(tester, '72'); + await tap('bath'); + now = now.add(const Duration(minutes: 9)); + await tap('bath'); + await tester.pump(); + idleMs = MorningSession.stillnessLimit.inMilliseconds; + await tick(tester, kMotionPollEvery); + await tester.pumpAndSettle(); + expect(methods(), contains('ringNow')); + expect(find.text('RING'), findsOneWidget); + final saved = (await SessionStore().loadCurrent())!; + expect(saved.pendingReRingReason, 'still:dressed'); + expect(saved.currentLeg, SessionLeg.dressed); + }); + + testWidgets('stillness is ignored while showering', (tester) async { + await pumpSession(tester); + await logWeight(tester, '72'); + await tap('bath'); + idleMs = MorningSession.stillnessLimit.inMilliseconds * 2; + await tick(tester, kMotionPollEvery); + expect(methods(), isNot(contains('ringNow'))); + }); + + testWidgets('a missed deadline the alarm did not fire rings from Dart', ( + tester, + ) async { + await pumpSession(tester); + now = now.add(MorningSession.legWindow).add(const Duration(seconds: 30)); + await tick(tester); + await tester.pumpAndSettle(); + expect(methods(), contains('ringNow')); + expect( + (await SessionStore().loadCurrent())!.pendingReRingReason, + 'deadline:bathroomIn', + ); + }); + + testWidgets('resumes a stored session and bypasses a spent leg', ( + tester, + ) async { + final started = now.subtract(const Duration(minutes: 16)); + final session = SessionRules.start( + now: started, + tags: await SessionTagSettings.load(), + nfcAvailable: true, + )..recordReRing(now.subtract(const Duration(minutes: 1))); + await SessionStore().save(session); + await pumpSession(tester); + expect(find.text('Re-rings: 1/3'), findsOneWidget); + expect( + calls.firstWhere((c) => c.method == 'armReRing').arguments, + {'atMillis': null}, + ); + await tick(tester); + expect(find.textContaining('Skipped'), findsOneWidget); + expect(find.textContaining('(skipped by the clock)'), findsOneWidget); + }); + + testWidgets('a big jump must be typed twice', (tester) async { + final store = SessionStore(); + await store.archive( + SessionRules.start( + now: now.subtract(const Duration(days: 1)), + tags: const SessionTagSettings(), + nfcAvailable: false, + )..weightKg = 70, + ); + await pumpSession(tester); + await logWeight(tester, '75'); + expect(find.textContaining('type it again'), findsOneWidget); + await logWeight(tester, '75'); + expect(find.textContaining('now tap the bathroom tag'), findsOneWidget); + expect(find.byType(TextField), findsNothing); + }); + + testWidgets('an unknown tag and bad weights are reported', (tester) async { + await pumpSession(tester); + await logWeight(tester, 'x'); + expect(find.textContaining('Enter your weight'), findsOneWidget); + await logWeight(tester, '1'); + expect(find.textContaining('not a body weight'), findsOneWidget); + expect(find.byType(TextField), findsOneWidget); + await tap('mystery'); + await tester.pump(); + expect(find.text('Unknown tag'), findsOneWidget); + }); +} diff --git a/phone_app/test/session_tags_screen_test.dart b/phone_app/test/session_tags_screen_test.dart new file mode 100644 index 0000000..d0e1333 --- /dev/null +++ b/phone_app/test/session_tags_screen_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/screens/session_tags_screen.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late List calls; + var nfcStarts = true; + + setUp(() { + calls = []; + nfcStarts = true; + SharedPreferences.setMockInitialValues({}); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel(AlarmScheduler.channelName), + (call) async { + calls.add(call.method); + if (call.method == 'startTagRegistration') return nfcStarts; + return null; + }, + ); + }); + + Future tapTag(WidgetTester tester, String id) async { + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + AlarmScheduler.channelName, + const StandardMethodCodec().encodeMethodCall( + MethodCall('onNfcTag', id), + ), + (_) {}, + ); + await tester.pump(); + await tester.pump(); + } + + testWidgets('shows the three rooms unregistered on a fresh install', ( + tester, + ) async { + await tester.pumpWidget(const MaterialApp(home: SessionTagsScreen())); + await tester.pump(); + expect(find.textContaining('Bathroom (scale + shower): none'), findsOne); + expect(find.textContaining('Wardrobe: none'), findsOneWidget); + expect(find.textContaining('Desk: none'), findsOneWidget); + }); + + testWidgets('a scan registers the tag in its slot', (tester) async { + await tester.pumpWidget(const MaterialApp(home: SessionTagsScreen())); + await tester.pump(); + await tester.tap(find.text('Register wardrobe tag')); + await tester.pump(); + expect(find.text('Waiting for tag…'), findsOneWidget); + await tapTag(tester, 'w1'); + expect(find.textContaining('Wardrobe: w1'), findsOneWidget); + expect(find.text('The wardrobe tag is registered.'), findsOneWidget); + expect(calls, contains('stopTagRegistration')); + expect( + (await SessionTagSettings.load()).tagAt(SessionTagSlot.wardrobe), + 'w1', + ); + }); + + testWidgets('one tag cannot hold two rooms', (tester) async { + await SessionTagSettings.saveTagAt(SessionTagSlot.bathroom, 'b1'); + await tester.pumpWidget(const MaterialApp(home: SessionTagsScreen())); + await tester.pump(); + await tester.tap(find.text('Register desk tag')); + await tester.pump(); + await tapTag(tester, 'b1'); + expect(find.textContaining('already the bathroom tag'), findsOneWidget); + expect( + (await SessionTagSettings.load()).tagAt(SessionTagSlot.desk), + isNull, + ); + }); + + testWidgets('re-registering the same room again is fine', (tester) async { + await SessionTagSettings.saveTagAt(SessionTagSlot.desk, 'd1'); + await tester.pumpWidget(const MaterialApp(home: SessionTagsScreen())); + await tester.pump(); + await tester.tap(find.text('Register desk tag again')); + await tester.pump(); + await tapTag(tester, 'd1'); + expect(find.text('The desk tag is registered.'), findsOneWidget); + }); + + testWidgets('says so when NFC is off', (tester) async { + nfcStarts = false; + await tester.pumpWidget(const MaterialApp(home: SessionTagsScreen())); + await tester.pump(); + await tester.tap(find.text('Register bathroom tag')); + await tester.pump(); + expect(find.textContaining('NFC is unavailable'), findsOneWidget); + }); +}