diff --git a/AGENTS.md b/AGENTS.md index b18f840..a89b0f8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -128,6 +128,72 @@ remote reader to keep in step. Check what the PC currently resolves: `python -m wake_alarm._sync --show`. Check what it would do right now: `python -m wake_alarm._trigger --dry-run`. +## The phone rings on its own — hand-written Kotlin, one MethodChannel + +`phone_app/` is no longer just a time picker. It arms and rings its own alarm +(items 1/4) through five Kotlin files behind **one** MethodChannel +(`AlarmChannel.kt`) on `MainActivity`/`AlarmActivity`: + +`AlarmScheduler` (arm/cancel/re-arm) · `AlarmReceiver` (fires) · +`AlarmService` (foreground service: wakelock, sound, vibration, full-screen +intent) · `AlarmActivity` (dismiss screen over the lockscreen) · +`BootReceiver` (re-arm after reboot) · `StepCounter` (item 3 fallback). + +**Never replace any of this with a pub plugin.** The stack is AGP 9.0.1 / +Gradle 9.1 / Kotlin 2.3.20; a plugin that will not compile against AGP 9 breaks +the build outright rather than degrading, and this is the one path that must +not break. Third-party plugins are acceptable only for droppable extras (QR +scanning) — never for the ring path. + +Things that are a hard crash or a silent no-ring, not a warning: + +- **`STREAM_ALARM` is load-bearing.** `AlarmService` sets + `AudioAttributes.USAGE_ALARM`, which is what ignores DND and silent mode. + Never `USAGE_MEDIA`/`STREAM_MUSIC` — it would be muted exactly when the + alarm matters most. +- **`android:foregroundServiceType="mediaPlayback"` must be on the `` + in the manifest AND passed to `startForeground()`.** Omitting either is a + hard crash the moment the alarm fires on API 34+ — and it is invisible on an + API 33 device, which is why the API 36 AVD exists. +- **`setAlarmClock()`, not `setExactAndAllowWhileIdle()`.** It is Doze-exempt, + needs no `SCHEDULE_EXACT_ALARM` prompt (`USE_EXACT_ALARM` covers an + alarm-clock app), and it is what grants the receiver its foreground-service + exemption when it fires with the screen off. +- **`FLAG_IMMUTABLE` on every `PendingIntent`** — mandatory since API 31; a + mutable one throws at arm time. +- **`canUseFullScreenIntent()` gates, it does not warn.** From API 34 the grant + can be revoked; `_armOwnAlarm()` in `home_screen.dart` refuses to report + success and tells the user to grant it, because without it the alarm posts a + notification the sleeping user never sees. +- **`min/target/compileSdk` are pinned explicitly** (28/36/36) in + `android/app/build.gradle.kts`. They used to be delegated to the Flutter + Gradle plugin, so there was no floor to reason about. minSdk 28 is what makes + `android:showWhenLocked`/`turnScreenOn` plain manifest attributes. + +**Re-arm has three hooks, and needs all three.** `LogStore` has **no change +stream** (the plan claimed one; it does not exist in `crdt_sync_dart`), so the +picker's save is only one of them: `main()`'s startup `rearm()`, +`BOOT_COMPLETED`, and the dismiss handler. Drop any one and the alarm rings +once and then silently stops. + +**The phone rings daily**, matching the PC's `ALARM_DAYS` (all seven days). +The two are deliberately not synced — a shared day set is item 8's shape, and +diverging defaults would have the halves firing on different days. + +`lib/services/challenge.dart` is a port of `_challenges.py`'s five kinds so +both halves behave identically; `kDismissCodeLength`/`kDismissFlashSeconds` +are **duplicated** from `_constants.py`, not synced. Change one, change both. + +Room proof (item 3) is `lib/services/room_proof.dart`: **NFC or QR satisfies +on its own; steps alone never does** — the phone is stationary while you walk +to it, so steps only accrue after pickup and can be faked by shaking it in +bed. Steps are accepted only together with elapsed time, as the fallback for +when both other mechanisms fail. + +Emulator: `wake_alarm_api36` (Pixel 6a profile, API 36). The SDK tools are at +`~/Android/Sdk` but **not on PATH** — export `ANDROID_HOME` and add +`cmdline-tools/latest/bin`, `emulator` and `platform-tools` yourself. + ## Module map `_alarm.py` owns the window and the dismiss flow and nothing else. The full 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 4cc6ea5..336a98f 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 @@ -40,6 +40,14 @@ object AlarmChannel { AlarmScheduler.rearmFromStorage(context) result.success(null) } + // Fires the ring immediately, so the foreground-service and + // full-screen-intent path can be exercised on an emulator without + // waiting for a real alarm instant. Reachable only over this app's + // own channel; it arms nothing and changes no stored time. + "ringNow" -> { + AlarmService.start(context) + result.success(null) + } "stepCount" -> result.success(StepCounter.stepsSinceRingStart(context)) "beginStepCount" -> { StepCounter.markRingStart(context) 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 a9c6767..8fd2dc9 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 @@ -71,14 +71,20 @@ object AlarmScheduler { /** * Whether the system will actually honour a full-screen intent. * - * False from API 34 unless the user granted it. The caller must treat this - * as a hard failure rather than logging and continuing: without it the - * alarm posts a notification the sleeping user never sees. + * Requires BOTH the API 34 full-screen-intent grant AND notifications + * being enabled at all: with notifications blocked the post is dropped + * before the full-screen intent is ever considered, so the alarm rings + * with no dismiss screen. Measured on the API 36 AVD, where a freshly + * installed app sits at importance=NONE and the op logs a rejectTime. + * + * The caller must treat a false here as a hard failure rather than + * logging and continuing — the sleeping user never sees a notification. */ fun canUseFullScreenIntent(context: Context): Boolean { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return true val notifications = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + if (!notifications.areNotificationsEnabled()) return false + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return true return notifications.canUseFullScreenIntent() } diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/MainActivity.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/MainActivity.kt index 82a30fa..15bc397 100644 --- a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/MainActivity.kt +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/MainActivity.kt @@ -1,5 +1,10 @@ package com.kuhy.wake_alarm_sync +import android.Manifest +import android.content.pm.PackageManager +import android.os.Bundle +import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine @@ -10,8 +15,40 @@ import io.flutter.embedding.engine.FlutterEngine * cancel and re-arm without going through the ring screen. */ class MainActivity : FlutterActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + requestNotificationPermission() + } + + /** + * Asks for POST_NOTIFICATIONS, which is a runtime permission from API 33. + * + * Without the grant the app sits at importance=NONE, the full-screen + * intent is rejected before it is considered, and the alarm rings with no + * dismiss screen. Measured on the API 36 AVD, where a freshly installed + * app is blocked by default. + */ + private fun requestNotificationPermission() { + val granted = ContextCompat.checkSelfPermission( + this, + Manifest.permission.POST_NOTIFICATIONS, + ) == PackageManager.PERMISSION_GRANTED + if (granted) return + ActivityCompat.requestPermissions( + this, + arrayOf(Manifest.permission.POST_NOTIFICATIONS), + NOTIFICATION_REQUEST_CODE, + ) + } + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) AlarmChannel.register(this, flutterEngine) } + + private companion object { + /** Request code for the notification permission prompt. */ + const val NOTIFICATION_REQUEST_CODE = 2001 + } } diff --git a/phone_app/lib/main.dart b/phone_app/lib/main.dart index 1df1e4a..d32ae9e 100644 --- a/phone_app/lib/main.dart +++ b/phone_app/lib/main.dart @@ -1,10 +1,29 @@ 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/services/alarm_scheduler.dart'; import 'package:wake_alarm_sync/ui/theme.dart'; +/// Route the Kotlin `AlarmActivity` hands to the engine as its initial +/// route. +const String kRingRoute = '/ring'; + +/// Navigator key, so the platform side can drive navigation without a context. +final GlobalKey navigatorKey = GlobalKey(); + /// Entry point. -void main() => runApp(const WakeAlarmSyncApp()); +/// +/// `ensureInitialized` is required before any MethodChannel call: the +/// startup re-arm below runs before the first frame. +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + // The log store has no change stream, so the picker's save is the only other + // arm hook. Without this, restarting the app without touching the picker + // would leave nothing armed at all. + await AlarmScheduler().rearm(); + runApp(const WakeAlarmSyncApp()); +} /// Root application widget. class WakeAlarmSyncApp extends StatelessWidget { @@ -16,7 +35,13 @@ class WakeAlarmSyncApp extends StatelessWidget { return MaterialApp( title: 'Wake Alarm Sync', theme: buildAppTheme(), - home: const HomeScreen(), + navigatorKey: navigatorKey, + // AlarmActivity sets its initial route to kRingRoute, so the ring screen + // is what comes up over the lockscreen; the launcher still gets home. + routes: { + '/': (_) => const HomeScreen(), + kRingRoute: (_) => const RingScreen(), + }, ); } } diff --git a/phone_app/lib/main_ring_probe.dart b/phone_app/lib/main_ring_probe.dart new file mode 100644 index 0000000..f7d5ef5 --- /dev/null +++ b/phone_app/lib/main_ring_probe.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; + +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; + +/// Debug entrypoint that starts the ring immediately on launch. +/// +/// Used to exercise the Kotlin foreground-service and full-screen-intent path +/// on an emulator, where the normal flow needs a sync backend first. Not part +/// of the shipped app: `flutter build apk` uses `lib/main.dart`. +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await AlarmScheduler().ringNow(); + runApp(const _Probe()); +} + +class _Probe extends StatelessWidget { + const _Probe(); + + @override + Widget build(BuildContext context) => const MaterialApp( + home: Scaffold(body: Center(child: Text('ring probe'))), + ); +} diff --git a/phone_app/lib/screens/home_screen.dart b/phone_app/lib/screens/home_screen.dart index 466a2ea..3921fb7 100644 --- a/phone_app/lib/screens/home_screen.dart +++ b/phone_app/lib/screens/home_screen.dart @@ -4,6 +4,7 @@ import 'package:android_intent_plus/android_intent.dart'; import 'package:flutter/material.dart'; import 'package:wake_alarm_sync/screens/settings_screen.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; 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/sync_settings.dart'; @@ -27,6 +28,9 @@ class _HomeScreenState extends State { bool _configured = false; AlarmSyncService? _service; + /// Platform bridge that arms the app's own alarm (item 1). + final AlarmScheduler _scheduler = AlarmScheduler(); + @override void initState() { super.initState(); @@ -82,13 +86,34 @@ class _HomeScreenState extends State { /// /// android_intent_plus v5 uses startActivityForResult; the Clock app /// never sends a result, so we time out after 3 s rather than hang forever. + /// Arms the app's own alarm — no user interaction (item 1). + /// + /// The SET_ALARM intent below is kept only as optional redundancy in the + /// system Clock app; it is no longer what makes the phone ring, because it + /// required the user to confirm in another app every single time. + /// + /// Returns an error string when the alarm could not be armed, or null on + /// success. A full-screen-intent grant that has been revoked is a hard + /// failure, not a warning: without it the alarm posts a notification the + /// sleeping user never sees. + Future _armOwnAlarm() async { + if (!await _scheduler.canUseFullScreenIntent()) { + return 'Allow "full screen notifications" for this app in Android ' + 'settings — without it the alarm cannot show over the lockscreen.'; + } + await _scheduler.schedule(_hour, _minute); + return null; + } + Future _setPhoneAlarm() async { final intent = AndroidIntent( action: 'android.intent.action.SET_ALARM', arguments: { 'android.intent.extra.alarm.HOUR': _hour, 'android.intent.extra.alarm.MINUTES': _minute, - 'android.intent.extra.alarm.SKIP_UI': false, + // SKIP_UI: the app already armed its own alarm, so the Clock entry is + // pure redundancy and must not demand a tap. + 'android.intent.extra.alarm.SKIP_UI': true, 'android.intent.extra.alarm.MESSAGE': 'Wake Alarm', }, ); @@ -113,9 +138,15 @@ class _HomeScreenState extends State { try { await service.setLocal(_hour, _minute); await service.push(settings.token); - setState(() => _status = 'Synced ✓ — opening Clock app…'); + setState(() => _status = 'Synced ✓ — arming alarm…'); + final problem = await _armOwnAlarm(); + if (problem != null) { + setState(() => _status = problem); + return; + } await _setPhoneAlarm(); - setState(() => _status = 'Done! Confirm the alarm in the Clock app.'); + final at = _fmt(_hour, _minute); + setState(() => _status = 'Done! Alarm armed for $at.'); } on Exception catch (e) { setState(() => _status = 'Error: $e'); } finally { diff --git a/phone_app/lib/screens/ring_screen.dart b/phone_app/lib/screens/ring_screen.dart new file mode 100644 index 0000000..fe7ff9e --- /dev/null +++ b/phone_app/lib/screens/ring_screen.dart @@ -0,0 +1,147 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/challenge.dart'; +import 'package:wake_alarm_sync/services/room_proof.dart'; + +/// The dismiss screen shown over the lockscreen while the alarm rings. +/// +/// Two gates, in order: prove you are in the other room, then solve a +/// challenge. Only then does the sound stop. +class RingScreen extends StatefulWidget { + /// Creates the ring screen; both dependencies are injectable for tests. + const RingScreen({super.key, this.scheduler, this.generator}); + + /// Platform bridge; defaults to the real MethodChannel. + final AlarmScheduler? scheduler; + + /// Challenge source; defaults to a secure-random generator. + final ChallengeGenerator? generator; + + @override + State createState() => _RingScreenState(); +} + +class _RingScreenState extends State { + late final AlarmScheduler _scheduler = widget.scheduler ?? AlarmScheduler(); + late final ChallengeGenerator _generator = + widget.generator ?? ChallengeGenerator(); + late final RoomProof _proof = RoomProof(scheduler: _scheduler); + late Challenge _challenge = _generator.next(); + + final TextEditingController _input = TextEditingController(); + final Stopwatch _elapsed = Stopwatch()..start(); + + /// Whether the room proof has been satisfied; the challenge is gated on it. + bool _inRoom = false; + String _status = ''; + + /// Hidden after [kDismissFlashSeconds] for the flash challenge only. + bool _codeVisible = true; + Timer? _flashTimer; + + @override + void initState() { + super.initState(); + unawaited(_scheduler.beginStepCount()); + _startFlashTimerIfNeeded(); + } + + @override + void dispose() { + _flashTimer?.cancel(); + _input.dispose(); + _elapsed.stop(); + super.dispose(); + } + + void _startFlashTimerIfNeeded() { + if (_challenge.kind != ChallengeKind.flash) return; + _flashTimer?.cancel(); + _flashTimer = Timer(const Duration(seconds: kDismissFlashSeconds), () { + if (mounted) setState(() => _codeVisible = false); + }); + } + + Future _trySteps() async { + final result = await _proof.checkSteps(_elapsed.elapsed); + if (!mounted) return; + setState(() { + _inRoom = result.satisfied; + _status = result.detail; + }); + } + + void _submit() { + if (!_challenge.accepts(_input.text)) { + setState(() { + _status = 'Wrong — here is another one'; + _challenge = _generator.next(); + _codeVisible = true; + _input.clear(); + }); + _startFlashTimerIfNeeded(); + return; + } + unawaited(_scheduler.dismiss()); + setState(() => _status = 'Dismissed'); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return PopScope( + // The alarm cannot be escaped with back; dismissing is the only way out. + canPop: false, + child: Scaffold( + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text('Wake up', style: theme.textTheme.headlineMedium), + const SizedBox(height: 24), + if (!_inRoom) ..._roomGate(theme) else ..._challengeGate(theme), + const SizedBox(height: 16), + Text(_status, style: theme.textTheme.bodyMedium), + ], + ), + ), + ), + ), + ); + } + + List _roomGate(ThemeData theme) => [ + Text( + 'Go to the other room: tap the NFC tag, scan the QR code, ' + 'or walk ${RoomProof.requiredSteps} steps.', + textAlign: TextAlign.center, + style: theme.textTheme.bodyLarge, + ), + const SizedBox(height: 16), + FilledButton(onPressed: _trySteps, child: const Text('Check steps')), + ]; + + List _challengeGate(ThemeData theme) => [ + Text(_challenge.hint, style: theme.textTheme.bodyLarge), + const SizedBox(height: 12), + Text( + _codeVisible ? _challenge.display : '••••••', + textAlign: TextAlign.center, + style: theme.textTheme.displaySmall, + ), + const SizedBox(height: 16), + TextField( + controller: _input, + autofocus: true, + textCapitalization: TextCapitalization.characters, + decoration: const InputDecoration(labelText: 'Answer'), + onSubmitted: (_) => _submit(), + ), + const SizedBox(height: 16), + FilledButton(onPressed: _submit, child: const Text('Dismiss')), + ]; +} diff --git a/phone_app/lib/services/alarm_scheduler.dart b/phone_app/lib/services/alarm_scheduler.dart new file mode 100644 index 0000000..5797711 --- /dev/null +++ b/phone_app/lib/services/alarm_scheduler.dart @@ -0,0 +1,63 @@ +import 'package:flutter/services.dart'; + +/// Dart side of the single MethodChannel the Kotlin ring path exposes. +/// +/// One channel for the whole feature (see `AlarmChannel.kt`): the alarm must +/// never depend on a pub plugin compiling against AGP 9. +class AlarmScheduler { + /// Creates a scheduler; [channel] is injectable so tests need no platform. + AlarmScheduler({MethodChannel? channel}) + : _channel = channel ?? const MethodChannel(channelName); + + /// Channel name, matching `AlarmActivity.CHANNEL` on the Kotlin side. + static const String channelName = 'com.kuhy.wake_alarm_sync/alarm'; + + final MethodChannel _channel; + + /// Arms the alarm for the next occurrence of [hour]:[minute] in local time. + /// + /// The phone rings **daily**, matching the PC's `ALARM_DAYS` which is + /// currently all seven days. The two are deliberately not synced — a shared + /// day set is item 8's shape, and diverging defaults would have the halves + /// firing on different days. + Future schedule(int hour, int minute) => + _channel.invokeMethod('schedule', { + 'hour': hour, + 'minute': minute, + }); + + /// Cancels the armed alarm and forgets the stored time. + Future cancel() => _channel.invokeMethod('cancel'); + + /// Re-arms from the stored time; false when no alarm was ever set. + /// + /// Called from the app's init seam because the store has no change stream: + /// without this, an app restart that does not touch the picker would leave + /// nothing armed. + Future rearm() async => + await _channel.invokeMethod('rearm') ?? false; + + /// Stops the ring and immediately re-arms for tomorrow. + Future dismiss() => _channel.invokeMethod('dismiss'); + + /// Whether the system will honour the full-screen intent. + /// + /// False from API 34 unless granted. The caller must treat this as a hard + /// failure: without it the alarm posts a notification the sleeper never sees. + Future canUseFullScreenIntent() async => + await _channel.invokeMethod('canUseFullScreenIntent') ?? false; + + /// Starts the ring immediately, without waiting for the alarm instant. + /// + /// Exists so the foreground-service and full-screen-intent path can be + /// exercised on an emulator; it arms nothing and changes no stored time. + Future ringNow() => _channel.invokeMethod('ringNow'); + + /// Captures the step baseline for this ring. + Future beginStepCount() => + _channel.invokeMethod('beginStepCount'); + + /// Steps since [beginStepCount], or -1 when unavailable. + Future stepsSinceRingStart() async => + await _channel.invokeMethod('stepCount') ?? -1; +} diff --git a/phone_app/lib/services/challenge.dart b/phone_app/lib/services/challenge.dart new file mode 100644 index 0000000..1b0875c --- /dev/null +++ b/phone_app/lib/services/challenge.dart @@ -0,0 +1,232 @@ +/// Dismiss-challenge types, ported from the PC half's +/// `wake_alarm/_challenges.py` so both halves behave identically. +/// +/// The two constants below are duplicated from `wake_alarm/_constants.py` +/// (`DISMISS_CODE_LENGTH`, `DISMISS_FLASH_SECONDS`) rather than synced — the +/// Dart side has no way to read Python. If they change there, change them here. +library; + +import 'dart:math'; + +/// Length of a generated dismiss code. Mirrors `DISMISS_CODE_LENGTH`. +const int kDismissCodeLength = 10; + +/// Seconds a flash challenge stays visible. Mirrors `DISMISS_FLASH_SECONDS`. +const int kDismissFlashSeconds = 4; + +/// Uppercase alphanumerics with visually ambiguous characters removed: +/// O/0 and I/1 are excluded so the code is legible half-asleep. +const String _dismissChars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; + +/// Words for the reverse challenge — common, unambiguous when read half-asleep. +const List _reverseWords = [ + 'MORNING', + 'COFFEE', + 'PILLOW', + 'BLANKET', + 'ALARM', + 'AWAKE', + 'SHOWER', + 'BREAKFAST', + 'WORKOUT', + 'WINDOW', + 'MONDAY', + 'TUESDAY', + 'FRIDAY', + 'SUNDAY', + 'WEEKEND', +]; + +/// The five challenge kinds, matching the PC half's `kind` strings exactly. +enum ChallengeKind { + /// Solve an arithmetic problem. + math, + + /// Type shuffled digits in ascending order. + sort, + + /// Memorise a code before it is hidden. + flash, + + /// Identify and continue a numeric pattern. + sequence, + + /// Type a displayed word backwards. + reverse, +} + +/// A dismiss challenge presented to the user to prove wakefulness. +class Challenge { + /// Creates a challenge with its display text, expected answer and hint. + const Challenge({ + required this.kind, + required this.display, + required this.answer, + required this.hint, + }); + + /// Which of the five variants this is. + final ChallengeKind kind; + + /// Text shown in the large code label. + final String display; + + /// Expected typed answer, normalised upper-case. + final String answer; + + /// Short instruction shown above the code label. + final String hint; + + /// Whether [input] solves this challenge, ignoring case and + /// surrounding space. + bool accepts(String input) => + input.trim().toUpperCase() == answer.trim().toUpperCase(); +} + +/// Generates challenges. The random source is injectable so tests are +/// deterministic. +class ChallengeGenerator { + /// Creates a generator; production uses a secure random source. + ChallengeGenerator({Random? random}) : _random = random ?? Random.secure(); + + final Random _random; + + /// Picks one of the five kinds at random and generates an instance. + Challenge next() { + final builders = [ + math, + flash, + sort, + sequence, + reverse, + ]; + return builders[_random.nextInt(builders.length)](); + } + + /// Generates a random dismiss code with ambiguous characters excluded. + String generateCode() => List.generate( + kDismissCodeLength, + (_) => _dismissChars[_random.nextInt(_dismissChars.length)], + ).join(); + + /// An arithmetic problem: addition, subtraction, multiplication or division. + Challenge math() { + const hint = 'Solve and type the answer'; + switch (_random.nextInt(4)) { + case 0: + final a = 100 + _random.nextInt(400); + final b = 100 + _random.nextInt(400); + return Challenge( + kind: ChallengeKind.math, + display: '$a + $b = ?', + answer: '${a + b}', + hint: hint, + ); + case 1: + final a = 200 + _random.nextInt(300); + final b = 100 + _random.nextInt(a - 100); + return Challenge( + kind: ChallengeKind.math, + display: '$a - $b = ?', + answer: '${a - b}', + hint: hint, + ); + case 2: + final a = 12 + _random.nextInt(14); + final b = 3 + _random.nextInt(7); + return Challenge( + kind: ChallengeKind.math, + display: '$a * $b = ?', + answer: '${a * b}', + hint: hint, + ); + default: + // Division: build a from b first so the quotient is always an integer. + final b = 3 + _random.nextInt(8); + final a = (10 + _random.nextInt(20)) * b; + return Challenge( + kind: ChallengeKind.math, + display: '$a ÷ $b = ?', + answer: '${a ~/ b}', + hint: hint, + ); + } + } + + /// Eight shuffled digits the user must type in ascending order. + Challenge sort() { + final pool = List.generate(9, (i) => i + 1); + for (var i = pool.length - 1; i > 0; i--) { + final j = _random.nextInt(i + 1); + final tmp = pool[i]; + pool[i] = pool[j]; + pool[j] = tmp; + } + final digits = pool.take(8).toList(); + final ascending = List.from(digits)..sort(); + return Challenge( + kind: ChallengeKind.sort, + display: digits.join(' '), + answer: ascending.join(), + hint: 'Type digits sorted lowest → highest (no spaces)', + ); + } + + /// A code shown briefly, then hidden; the user types it from memory. + Challenge flash() { + final code = generateCode(); + return Challenge( + kind: ChallengeKind.flash, + display: code, + answer: code, + hint: 'Memorise this code — it disappears in ${kDismissFlashSeconds}s', + ); + } + + /// Four terms of an arithmetic or geometric sequence; the user gives + /// the fifth term. + Challenge sequence() { + const hint = 'Find the pattern and type the next number'; + if (_random.nextInt(2) == 0) { + final start = 2 + _random.nextInt(14); + final step = 2 + _random.nextInt(8); + final terms = List.generate(4, (i) => start + step * i); + return Challenge( + kind: ChallengeKind.sequence, + display: '${terms.join(', ')}, ?', + answer: '${start + step * 4}', + hint: hint, + ); + } + final start = 2 + _random.nextInt(5); + final ratio = 2 + _random.nextInt(2); + final terms = List.generate(4, (i) => start * _pow(ratio, i)); + return Challenge( + kind: ChallengeKind.sequence, + display: '${terms.join(', ')}, ?', + answer: '${start * _pow(ratio, 4)}', + hint: hint, + ); + } + + /// A common word the user must type backwards. + Challenge reverse() { + final word = _reverseWords[_random.nextInt(_reverseWords.length)]; + final backwards = word.split('').reversed.join(); + return Challenge( + kind: ChallengeKind.reverse, + display: 'Type this word backwards:\n$word', + answer: backwards, + hint: 'Type the word backwards', + ); + } + + /// Integer exponentiation; `pow` returns a `num` and would need a cast. + static int _pow(int base, int exponent) { + var result = 1; + for (var i = 0; i < exponent; i++) { + result *= base; + } + return result; + } +} diff --git a/phone_app/lib/services/room_proof.dart b/phone_app/lib/services/room_proof.dart new file mode 100644 index 0000000..4334cf7 --- /dev/null +++ b/phone_app/lib/services/room_proof.dart @@ -0,0 +1,120 @@ +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; + +/// Which mechanism satisfied the separate-room requirement. +enum RoomProofKind { + /// Tapped the registered NFC tag in the other room. + nfc, + + /// Scanned the printed QR code in the other room. + qr, + + /// Walked far enough, for long enough, since the alarm started. + steps, +} + +/// Result of a room-proof attempt. +class RoomProofResult { + /// Creates a result; [kind] is null when nothing has satisfied yet. + const RoomProofResult({required this.satisfied, this.kind, this.detail = ''}); + + /// Whether the user has proven they are in the other room. + final bool satisfied; + + /// Which mechanism satisfied it, or null if none did. + final RoomProofKind? kind; + + /// Human-readable reason, shown on the ring screen. + final String detail; +} + +/// Proof that the user physically walked to another room before dismissing. +/// +/// **Any one of NFC or QR satisfies.** Steps alone deliberately does NOT: the +/// phone is stationary in the other room while you walk *to* it, so steps only +/// accrue after pickup and can be faked by shaking it in bed. Steps are only +/// accepted together with elapsed time, as the fallback for when both other +/// mechanisms fail — a single failing mechanism at 06:00 must never make the +/// alarm undismissable. +class RoomProof { + /// Creates a room-proof checker over [scheduler]'s platform channel. + RoomProof({required this.scheduler, this._registeredTagId}); + + /// Platform bridge used to read the step counter. + final AlarmScheduler scheduler; + final String? _registeredTagId; + + /// Steps required by the fallback, counted since the alarm started ringing. + static const int requiredSteps = 25; + + /// Elapsed time the fallback also requires, so shaking the phone cannot pass. + static const Duration requiredElapsed = Duration(minutes: 2); + + /// Whether [tagId] is the tag registered in Settings. + /// + /// Registering no tag means NFC cannot satisfy the proof — it does not mean + /// every tag passes. + RoomProofResult checkNfc(String tagId) { + final registered = _registeredTagId; + if (registered == null || registered.isEmpty) { + return const RoomProofResult( + satisfied: false, + detail: 'No NFC tag registered in Settings', + ); + } + if (tagId != registered) { + return const RoomProofResult(satisfied: false, detail: 'Wrong NFC tag'); + } + return const RoomProofResult( + satisfied: true, + kind: RoomProofKind.nfc, + detail: 'NFC tag matched', + ); + } + + /// Whether [payload] is the expected printed QR code. + /// + /// A printed code is photographable, which is exactly why it is one of two + /// accepted proofs rather than the only one. + RoomProofResult checkQr(String payload, {required String expected}) { + if (expected.isEmpty || payload != expected) { + return const RoomProofResult(satisfied: false, detail: 'Wrong QR code'); + } + return const RoomProofResult( + satisfied: true, + kind: RoomProofKind.qr, + detail: 'QR code matched', + ); + } + + /// The fallback: enough steps AND enough elapsed time since the ring started. + /// + /// 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 { + final steps = await scheduler.stepsSinceRingStart(); + if (steps < 0) { + return const RoomProofResult( + satisfied: false, + detail: 'Step sensor unavailable', + ); + } + if (steps < requiredSteps) { + return RoomProofResult( + satisfied: false, + detail: '$steps/$requiredSteps steps', + ); + } + if (elapsed < requiredElapsed) { + final left = requiredElapsed - elapsed; + return RoomProofResult( + satisfied: false, + detail: 'Keep moving for ${left.inSeconds}s more', + ); + } + return const RoomProofResult( + satisfied: true, + kind: RoomProofKind.steps, + detail: 'Walked far enough, long enough', + ); + } +} diff --git a/phone_app/test/services/alarm_scheduler_test.dart b/phone_app/test/services/alarm_scheduler_test.dart new file mode 100644 index 0000000..fe7956c --- /dev/null +++ b/phone_app/test/services/alarm_scheduler_test.dart @@ -0,0 +1,71 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late List calls; + late AlarmScheduler scheduler; + Object? reply; + + setUp(() { + calls = []; + reply = null; + const channel = MethodChannel(AlarmScheduler.channelName); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return reply; + }); + scheduler = AlarmScheduler(channel: channel); + }); + + test('schedule passes hour and minute across the channel', () async { + await scheduler.schedule(6, 45); + expect(calls.single.method, 'schedule'); + expect(calls.single.arguments, {'hour': 6, 'minute': 45}); + }); + + test('cancel invokes cancel', () async { + await scheduler.cancel(); + expect(calls.single.method, 'cancel'); + }); + + test('dismiss invokes dismiss', () async { + await scheduler.dismiss(); + expect(calls.single.method, 'dismiss'); + }); + + test('rearm returns the platform result', () async { + reply = true; + expect(await scheduler.rearm(), isTrue); + }); + + test('rearm treats a null platform result as "nothing armed"', () async { + expect(await scheduler.rearm(), isFalse); + }); + + test('canUseFullScreenIntent returns the platform result', () async { + reply = true; + expect(await scheduler.canUseFullScreenIntent(), isTrue); + }); + + test('canUseFullScreenIntent fails closed on a null result', () async { + expect(await scheduler.canUseFullScreenIntent(), isFalse); + }); + + test('beginStepCount invokes beginStepCount', () async { + await scheduler.beginStepCount(); + expect(calls.single.method, 'beginStepCount'); + }); + + test('stepsSinceRingStart returns the platform count', () async { + reply = 31; + expect(await scheduler.stepsSinceRingStart(), 31); + }); + + test('stepsSinceRingStart reports -1 when the platform gives null', () async { + expect(await scheduler.stepsSinceRingStart(), -1); + }); +} diff --git a/phone_app/test/services/challenge_test.dart b/phone_app/test/services/challenge_test.dart new file mode 100644 index 0000000..c6bad37 --- /dev/null +++ b/phone_app/test/services/challenge_test.dart @@ -0,0 +1,153 @@ +import 'dart:math'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wake_alarm_sync/services/challenge.dart'; + +/// Deterministic source so every branch can be reached on purpose. +class _FixedRandom implements Random { + _FixedRandom(this._values); + + final List _values; + int _at = 0; + + @override + int nextInt(int max) { + final v = _values[_at % _values.length]; + _at++; + return v % max; + } + + @override + bool nextBool() => nextInt(2) == 0; + + @override + double nextDouble() => 0; +} + +void main() { + group('Challenge.accepts', () { + const challenge = Challenge( + kind: ChallengeKind.math, + display: '1 + 1 = ?', + answer: '2', + hint: 'h', + ); + + test('accepts the exact answer', () { + expect(challenge.accepts('2'), isTrue); + }); + + test('ignores case and surrounding whitespace', () { + const word = Challenge( + kind: ChallengeKind.reverse, + display: 'd', + answer: 'MRALA', + hint: 'h', + ); + expect(word.accepts(' mrala '), isTrue); + }); + + test('rejects a wrong answer', () { + expect(challenge.accepts('3'), isFalse); + }); + }); + + group('ChallengeGenerator', () { + test('generateCode has the mirrored length and no ambiguous chars', () { + final code = ChallengeGenerator().generateCode(); + expect(code, hasLength(kDismissCodeLength)); + expect(RegExp(r'^[A-HJ-NP-Z2-9]+$').hasMatch(code), isTrue); + }); + + test('math covers addition', () { + final c = ChallengeGenerator(random: _FixedRandom([0, 5, 7])).math(); + expect(c.kind, ChallengeKind.math); + expect(c.display, contains('+')); + final parts = RegExp(r'(\d+) \+ (\d+)').firstMatch(c.display)!; + final sum = int.parse(parts.group(1)!) + int.parse(parts.group(2)!); + expect(c.answer, '$sum'); + }); + + test('math covers subtraction with a non-negative result', () { + final c = ChallengeGenerator(random: _FixedRandom([1, 5, 7])).math(); + expect(c.display, contains('-')); + expect(int.parse(c.answer), greaterThanOrEqualTo(0)); + }); + + test('math covers multiplication', () { + final c = ChallengeGenerator(random: _FixedRandom([2, 3, 4])).math(); + expect(c.display, contains('*')); + final parts = RegExp(r'(\d+) \* (\d+)').firstMatch(c.display)!; + final product = + int.parse(parts.group(1)!) * int.parse(parts.group(2)!); + expect(c.answer, '$product'); + }); + + test('math division always has an integer answer', () { + final c = ChallengeGenerator(random: _FixedRandom([3, 2, 6])).math(); + expect(c.display, contains('÷')); + final parts = RegExp(r'(\d+) ÷ (\d+)').firstMatch(c.display)!; + final a = int.parse(parts.group(1)!); + final b = int.parse(parts.group(2)!); + expect(a % b, 0); + expect(c.answer, '${a ~/ b}'); + }); + + test('sort shows eight digits and answers them ascending', () { + final c = ChallengeGenerator().sort(); + final shown = c.display.split(' ').map(int.parse).toList(); + expect(shown, hasLength(8)); + expect(c.answer, (List.from(shown)..sort()).join()); + expect(c.answer.split('').toSet(), hasLength(8)); + }); + + test('flash displays the code it expects back', () { + final c = ChallengeGenerator().flash(); + expect(c.kind, ChallengeKind.flash); + expect(c.display, c.answer); + expect(c.hint, contains('${kDismissFlashSeconds}s')); + }); + + test('sequence covers the arithmetic branch', () { + final c = ChallengeGenerator( + random: _FixedRandom([0, 3, 2]), + ).sequence(); + final terms = c.display + .replaceAll(', ?', '') + .split(', ') + .map(int.parse) + .toList(); + final step = terms[1] - terms[0]; + expect(terms[3] - terms[2], step); + expect(c.answer, '${terms[3] + step}'); + }); + + test('sequence covers the geometric branch', () { + final c = ChallengeGenerator( + random: _FixedRandom([1, 2, 0]), + ).sequence(); + final terms = c.display + .replaceAll(', ?', '') + .split(', ') + .map(int.parse) + .toList(); + final ratio = terms[1] ~/ terms[0]; + expect(terms[3], terms[2] * ratio); + expect(c.answer, '${terms[3] * ratio}'); + }); + + test('reverse expects the word backwards', () { + final c = ChallengeGenerator().reverse(); + final word = c.display.split('\n').last; + expect(c.answer, word.split('').reversed.join()); + }); + + test('next() can produce every kind', () { + final kinds = {}; + for (var i = 0; i < 400; i++) { + kinds.add(ChallengeGenerator().next().kind); + } + expect(kinds, hasLength(ChallengeKind.values.length)); + }); + }); +} diff --git a/phone_app/test/services/room_proof_test.dart b/phone_app/test/services/room_proof_test.dart new file mode 100644 index 0000000..4341e53 --- /dev/null +++ b/phone_app/test/services/room_proof_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/room_proof.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late AlarmScheduler scheduler; + int steps = 0; + + setUp(() { + const channel = MethodChannel(AlarmScheduler.channelName); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + if (call.method == 'stepCount') return steps; + return null; + }); + scheduler = AlarmScheduler(channel: channel); + }); + + group('NFC', () { + test('a matching registered tag satisfies the proof', () { + final proof = RoomProof(scheduler: scheduler, registeredTagId: 'tag-1'); + final result = proof.checkNfc('tag-1'); + expect(result.satisfied, isTrue); + expect(result.kind, RoomProofKind.nfc); + }); + + test('a different tag does not', () { + final proof = RoomProof(scheduler: scheduler, registeredTagId: 'tag-1'); + expect(proof.checkNfc('tag-2').satisfied, isFalse); + }); + + test('no registered tag means NFC cannot satisfy, not that all pass', () { + final proof = RoomProof(scheduler: scheduler); + final result = proof.checkNfc('tag-1'); + expect(result.satisfied, isFalse); + expect(result.detail, contains('No NFC tag registered')); + }); + + test('an empty registered tag is treated as unregistered', () { + final proof = RoomProof(scheduler: scheduler, registeredTagId: ''); + expect(proof.checkNfc('').satisfied, isFalse); + }); + }); + + group('QR', () { + test('the expected payload satisfies the proof', () { + final proof = RoomProof(scheduler: scheduler); + final result = proof.checkQr('kitchen', expected: 'kitchen'); + expect(result.satisfied, isTrue); + expect(result.kind, RoomProofKind.qr); + }); + + test('a different payload does not', () { + final proof = RoomProof(scheduler: scheduler); + expect(proof.checkQr('bedroom', expected: 'kitchen').satisfied, isFalse); + }); + + test('an empty expectation never matches', () { + final proof = RoomProof(scheduler: scheduler); + expect(proof.checkQr('', expected: '').satisfied, isFalse); + }); + }); + + group('steps fallback', () { + test('reports the sensor being unavailable', () async { + steps = -1; + final proof = RoomProof(scheduler: scheduler); + final result = await proof.checkSteps(const Duration(minutes: 5)); + expect(result.satisfied, isFalse); + expect(result.detail, contains('unavailable')); + }); + + test('too few steps does not satisfy', () async { + steps = 5; + final proof = RoomProof(scheduler: scheduler); + final result = await proof.checkSteps(const Duration(minutes: 5)); + expect(result.satisfied, isFalse); + expect(result.detail, contains('5/${RoomProof.requiredSteps}')); + }); + + test('enough steps but too little time does not satisfy', () async { + // This is the shake-it-in-bed case the elapsed requirement exists for. + steps = RoomProof.requiredSteps + 10; + final proof = RoomProof(scheduler: scheduler); + final result = await proof.checkSteps(const Duration(seconds: 10)); + expect(result.satisfied, isFalse); + expect(result.detail, contains('Keep moving')); + }); + + test('enough steps and enough time satisfies', () async { + steps = RoomProof.requiredSteps; + final proof = RoomProof(scheduler: scheduler); + final result = await proof.checkSteps(RoomProof.requiredElapsed); + expect(result.satisfied, isTrue); + expect(result.kind, RoomProofKind.steps); + }); + }); +}