From 7523cb4225ebf45b22801baaf57f4607ec9ce078 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Mon, 31 Aug 2026 11:45:11 +0200 Subject: [PATCH] Ring the away profile when the phone is not at home Co-Authored-By: Claude Opus 5 (1M context) --- DOCS-phone-alarm.md | 64 +++++++ .../android/app/src/main/AndroidManifest.xml | 13 ++ .../com/kuhy/wake_alarm_sync/AlarmChannel.kt | 10 + .../com/kuhy/wake_alarm_sync/AlarmService.kt | 34 ++-- .../com/kuhy/wake_alarm_sync/AlarmVolume.kt | 79 ++++++++ .../com/kuhy/wake_alarm_sync/HomePresence.kt | 179 ++++++++++++++++++ .../com/kuhy/wake_alarm_sync/LocationFix.kt | 94 +++++++++ .../com/kuhy/wake_alarm_sync/MainActivity.kt | 7 + phone_app/lib/screens/home_body.dart | 2 + .../lib/screens/home_location_screen.dart | 165 ++++++++++++++++ phone_app/lib/screens/home_presence_line.dart | 66 +++++++ phone_app/lib/screens/ring_body.dart | 73 +++++++ phone_app/lib/screens/ring_checklist.dart | 10 +- phone_app/lib/screens/ring_screen.dart | 83 ++++---- phone_app/lib/screens/settings_screen.dart | 12 ++ phone_app/lib/services/alarm_scheduler.dart | 25 +++ phone_app/lib/services/dismiss_gate.dart | 45 ++++- .../lib/services/home_location_settings.dart | 135 +++++++++++++ phone_app/lib/services/home_presence.dart | 128 +++++++++++++ phone_app/lib/services/ring_startup.dart | 84 ++++++++ phone_app/test/home_location_screen_test.dart | 89 +++++++++ phone_app/test/ring_away_test.dart | 144 ++++++++++++++ phone_app/test/ring_bypass_test.dart | 2 + .../test/services/dismiss_gate_test.dart | 73 +++++++ .../services/home_location_settings_test.dart | 87 +++++++++ .../test/services/home_presence_test.dart | 166 ++++++++++++++++ phone_app/test/settings_screen_test.dart | 2 + 27 files changed, 1794 insertions(+), 77 deletions(-) create mode 100644 phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmVolume.kt create mode 100644 phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/HomePresence.kt create mode 100644 phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/LocationFix.kt create mode 100644 phone_app/lib/screens/home_location_screen.dart create mode 100644 phone_app/lib/screens/home_presence_line.dart create mode 100644 phone_app/lib/screens/ring_body.dart create mode 100644 phone_app/lib/services/home_location_settings.dart create mode 100644 phone_app/lib/services/home_presence.dart create mode 100644 phone_app/lib/services/ring_startup.dart create mode 100644 phone_app/test/home_location_screen_test.dart create mode 100644 phone_app/test/ring_away_test.dart create mode 100644 phone_app/test/services/home_location_settings_test.dart create mode 100644 phone_app/test/services/home_presence_test.dart diff --git a/DOCS-phone-alarm.md b/DOCS-phone-alarm.md index 32d0919..c176227 100644 --- a/DOCS-phone-alarm.md +++ b/DOCS-phone-alarm.md @@ -43,6 +43,16 @@ Things that are a hard crash or a silent no-ring, not a warning: change. `raiseAlarmVolume()` does run on this hardware (observed raising `oldIndex:0` → 7, no `SecurityException`), which recovers a stream turned down to zero but not one muted by total silence. +- **The ring fades in; the stream still goes to max.** Two different knobs, + and merging them trades a gentle start for a silent alarm. + `raiseAlarmVolume()` fixes the *system stream* — a stream left at 0 would + silence the alarm outright. `startVolumeRamp()` climbs the *player's own + gain* from `RAMP_START_GAIN` (0.04) to full over `RAMP_DURATION_MS` (60 s), + quadratically, because perceived loudness is not linear in amplitude. + Measured on the Pixel 6a (2026-08-31) from `dumpsys media.audio_flinger` + track gain: −28 dB at 3 s, −21 dB at 15 s, −12 dB at 30 s, 0 dB at 62 s. + Every step re-reads `player`, and `stopSound()` drops the queue before + releasing it, so a dismissal mid-ramp cannot touch a released `MediaPlayer`. - **`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 @@ -104,6 +114,49 @@ minutes and answer questions without standing up, which is weaker than the gate this replaced. Without some such hatch a dead tag at 06:00 leaves an alarm that literally cannot be switched off. +## Home presence — the alarm knows where it is + +Away from home the two tags are screwed to walls in another city, so the +sequence is unsatisfiable. `HomePresence.read` (Kotlin) reports raw +observations and `lib/services/home_presence.dart` decides; away skips the two +*tag* stages and **keeps the normal 3 challenges**. The walk still counts. + +- **Never "modernise" `WifiManager.getConnectionInfo()`.** It is deprecated at + API 31 in favour of `NetworkCapabilities.getTransportInfo()`, and that + replacement does not work here: the *synchronous* + `ConnectivityManager.getNetworkCapabilities()` redacts every + location-sensitive field, so `transportInfo` is null and the BSSID silently + vanishes. Measured on the Pixel 6a (API 36, 2026-08-31) — connected to a + known AP, fine location granted, location services on — the capabilities + route returned `ssid=null bssid=null` while the GPS fallback quietly covered + for it. Un-redacted `transportInfo` needs a `registerNetworkCallback`. +- **A redacted BSSID is `02:00:00:00:00:00`, not null and not an error.** + Android returns it when fine location is missing *or* location services are + off. Untreated it is a valid-looking MAC that never matches, so every + morning reads "away" and the ritual silently stops happening. +- **Unreadable means away** — the user's explicit choice. A revoked permission + therefore weakens the alarm rather than breaking it loudly, which is why + `HomePresenceLine` puts the verdict *and its cause* on the home screen. + **Unconfigured is not unreadable:** an install that never captured a home + keeps the strict sequence, or shipping this would have deleted the gate. +- **Presence resolves before the missing-tags bypass** (`ring_startup.dart`). + Both skips latch one-way, so whichever fires first fixes the count; the + other order would give every away morning with NFC off the punitive 6. + Equally, `activateBypass()` is refused after `activateAwayProfile()` — the + ring screen's 5-minute timer fires unconditionally and an away morning + crosses 5 minutes routinely. +- **Registration passes `withFix: true`; the ring screen does not.** A Wi-Fi + answer short-circuits GPS, which is what makes the verdict instant at home — + but it also meant capture never recorded a coordinate, so the GPS fallback + could only ever be configured with Wi-Fi off, i.e. never. +- **BSSIDs are a list, and the SSID matches too.** A dual-band router answers + to a different BSSID per band and the phone roams overnight; one stored + address would call a band switch "travelling". +- The read runs from `AlarmActivity` (foregrounded, so while-in-use location + suffices). **Do not move it into `AlarmService`** — that would mean + `foregroundServiceType="mediaPlayback|location"` plus + `FOREGROUND_SERVICE_LOCATION`, on the one path that must not break. + **`ringNow` + `lib/main_ring_probe.dart` are a deliberate manual test handle**, the phone-side equivalent of `wake-alarm.service` on the PC: the normal arm path needs a sync backend connected, so there is no other way to @@ -121,6 +174,17 @@ phone (Pixel 6a, `23181JEGR08034`) holds a **release-signed** build, so `phone_deploy.sh` needs `--release` or the install fails with `INSTALL_FAILED_UPDATE_INCOMPATIBLE`. +**Never pass `--build-number` by hand**, including for the probes: use +`phone_deploy.sh --release --target lib/main_ring_probe.dart` and let it +pick. Android compares versionCode only upward, so a hand-picked number puts +the phone above what CI will mint and locks CI out until the commit count +catches up — the only other escape is an uninstall, which wipes the NFC tags, +the home location and the sync identity. This happened on 2026-08-31 (probe +builds at 200/201 stranded the phone at 207 against a ceiling of 156). +`.versioncode-offset` at the repo root is the recovery valve, read by **both** +`release-apk.yml` and the local gate so the two can only move together; it is +currently 101. `hooks/build_number_guard_pretool.sh` now blocks the bypass. + **The ring screen must close itself on dismiss.** `AlarmActivity` handles `closeRingScreen` (the shared `AlarmChannel` holds `applicationContext` and cannot finish an activity). Without it the dismiss screen stays up over the diff --git a/phone_app/android/app/src/main/AndroidManifest.xml b/phone_app/android/app/src/main/AndroidManifest.xml index 8bcdb80..a7d21d6 100644 --- a/phone_app/android/app/src/main/AndroidManifest.xml +++ b/phone_app/android/app/src/main/AndroidManifest.xml @@ -19,6 +19,19 @@ + + + + + + result.success(NfcReader.isAvailable(context)) + // Raw observations only; home_presence.dart decides what they mean. + // Lives here rather than in MainActivity's override (as NfcReader + // does) because WifiManager/LocationManager need no Activity, and + // the ring screen must be able to reach it through AlarmActivity. + "readPresence" -> HomePresence.read( + context, + call.argument("homeLat"), + call.argument("homeLon"), + call.argument("withFix") ?: false, + ) { observations -> result.success(observations) } // Handled by AlarmActivity, which owns the window; reaching here // means the picker asked, where there is no ring screen to close. "closeRingScreen" -> result.success(null) diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmService.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmService.kt index cd699a0..d831866 100644 --- a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmService.kt +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmService.kt @@ -9,11 +9,12 @@ import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo import android.media.AudioAttributes -import android.media.AudioManager import android.media.MediaPlayer import android.media.RingtoneManager import android.os.Build +import android.os.Handler import android.os.IBinder +import android.os.Looper import android.os.PowerManager import android.util.Log import android.os.VibrationEffect @@ -31,6 +32,9 @@ import android.os.VibratorManager class AlarmService : Service() { private var player: MediaPlayer? = null + + /** Drives the volume ramp; cleared in [stopSound]. */ + private val rampHandler = Handler(Looper.getMainLooper()) private var wakeLock: PowerManager.WakeLock? = null private var vibrator: Vibrator? = null @@ -149,30 +153,20 @@ class AlarmService : Service() { ) isLooping = true prepare() + // Start almost silent. The stream still goes to max below, so a + // stream muted to zero cannot silence the alarm -- it is the + // player's own gain that climbs. + setVolume(AlarmVolume.RAMP_START_GAIN, AlarmVolume.RAMP_START_GAIN) start() } - raiseAlarmVolume() - } - - /** - * Alarm stream turned down to zero must not silence the alarm. - * - * Guarded: setStreamVolume can throw under an active zen rule, and by this - * point startForeground() has already posted — an exception here would - * take the whole ring down over a volume bump that is only an - * improvement, not the mechanism. - */ - private fun raiseAlarmVolume() { - try { - val audio = getSystemService(Context.AUDIO_SERVICE) as AudioManager - val max = audio.getStreamMaxVolume(AudioManager.STREAM_ALARM) - audio.setStreamVolume(AudioManager.STREAM_ALARM, max, 0) - } catch (e: SecurityException) { - Log.w(TAG, "could not raise the alarm volume; ringing anyway", e) - } + AlarmVolume.raiseStream(this) + AlarmVolume.startRamp(rampHandler) { player } } private fun stopSound() { + // Before releasing the player: a queued step that runs afterwards + // would touch a released MediaPlayer. + rampHandler.removeCallbacksAndMessages(null) player?.run { if (isPlaying) stop() release() 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 new file mode 100644 index 0000000..31a6c46 --- /dev/null +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmVolume.kt @@ -0,0 +1,79 @@ +package com.kuhy.wake_alarm_sync + +import android.content.Context +import android.media.AudioManager +import android.media.MediaPlayer +import android.os.Handler +import android.util.Log + +/** + * How loud the alarm is, and how it gets there. + * + * Split out of [AlarmService] for the repo's 250-line cap, along a real seam: + * the service owns the ring's lifecycle, this owns its loudness. + * + * **Two knobs, deliberately not merged.** [raiseStream] fixes the *system + * stream*, which must be at max or a stream someone left at zero silences the + * alarm outright. [startRamp] shapes the *player's own gain* within it. + * Collapsing them into one would trade a gentle start for a silent alarm. + */ +object AlarmVolume { + + private const val TAG = "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 + + /** Gap between ramp steps; 30 steps over the full duration. */ + private const val RAMP_STEP_MS = 2_000L + + /** + * An alarm stream turned down to zero must not silence the alarm. + * + * Guarded: setStreamVolume can throw under an active zen rule, and by the + * time this runs startForeground() has already posted — an exception here + * would take the whole ring down over a volume bump that is only an + * improvement, not the mechanism. + */ + fun raiseStream(context: Context) { + try { + val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager + val max = audio.getStreamMaxVolume(AudioManager.STREAM_ALARM) + audio.setStreamVolume(AudioManager.STREAM_ALARM, max, 0) + } catch (e: SecurityException) { + Log.w(TAG, "could not raise the alarm volume; ringing anyway", e) + } + } + + /** + * Climbs the player gain from [RAMP_START_GAIN] to full over + * [RAMP_DURATION_MS]. + * + * 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. + * + * [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 + * caller also clears [handler] before releasing it, which + * `AlarmService.stopSound` does. + */ + fun startRamp(handler: Handler, player: () -> MediaPlayer?) { + val steps = (RAMP_DURATION_MS / RAMP_STEP_MS).toInt() + for (step in 1..steps) { + handler.postDelayed({ + val live = player() ?: return@postDelayed + val progress = step.toFloat() / steps + val gain = + RAMP_START_GAIN + (1f - RAMP_START_GAIN) * progress * progress + runCatching { live.setVolume(gain, gain) } + .onFailure { Log.w(TAG, "volume ramp step failed", it) } + }, RAMP_STEP_MS * step) + } + } +} diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/HomePresence.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/HomePresence.kt new file mode 100644 index 0000000..a7a3461 --- /dev/null +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/HomePresence.kt @@ -0,0 +1,179 @@ +package com.kuhy.wake_alarm_sync + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.location.Location +import android.location.LocationManager +import android.net.wifi.WifiManager +import android.os.Handler +import android.os.Looper +import android.util.Log +import androidx.core.content.ContextCompat +import java.util.concurrent.atomic.AtomicBoolean + +/** + * Where the phone is right now, as raw observations only. + * + * Hand-written on the existing MethodChannel for the same reason the ring path + * is: the stack is AGP 9 / Gradle 9.1 / Kotlin 2.3.20 and a pub plugin that + * fails to compile breaks the build outright instead of degrading. + * + * **This decides nothing.** It reports a BSSID, a fix, and a distance; whether + * that means "home" is `home_presence.dart`'s job, so the policy stays unit + * testable without a device. The one exception is [distanceMeters], computed + * here because [Location.distanceBetween] is already on hand and putting the + * trig in Dart would mean hand-rolling Haversine in the file under test. + * + * Wi-Fi is tried first and, when it answers, GPS is never touched: at home the + * BSSID is instant and indoors a fix may take 30s or never arrive at all. + */ +object HomePresence { + + private const val TAG = "WakeAlarmPresence" + + /** What Android hands back instead of a real BSSID when it redacts one. */ + private const val REDACTED_BSSID = "02:00:00:00:00:00" + + /** A second redaction sentinel seen on some OEM builds. */ + private const val ZERO_BSSID = "00:00:00:00:00:00" + + /** What WifiManager reports for an SSID it will not disclose. */ + private const val UNKNOWN_SSID = "" + + /** + * Reads presence and hands the observations to [callback] on the main + * thread. + * + * Asynchronous because a fix can take seconds and this is called from the + * ring screen: blocking the platform thread there is an ANR while the + * alarm is sounding. + */ + fun read( + context: Context, + homeLat: Double?, + homeLon: Double?, + withFix: Boolean, + callback: (Map) -> Unit, + ) { + val main = Handler(Looper.getMainLooper()) + val answered = AtomicBoolean(false) + fun done(payload: Map) { + if (!answered.compareAndSet(false, true)) return + Log.i(TAG, "presence $payload") + main.post { callback(payload) } + } + + if (!hasLocationPermission(context)) { + done(unreadable("no-permission")) + return + } + val manager = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager + // Location services off redacts the BSSID *and* kills every provider, + // so this single toggle is enough to make presence unreadable. + if (manager == null || !manager.isLocationEnabled) { + done(unreadable("location-disabled")) + return + } + + val wifi = readWifi(context) + // At ring time a Wi-Fi answer ends it: GPS is skipped entirely, which + // is the whole reason the verdict is instant at home. Registration + // passes withFix so it captures a coordinate too — otherwise the GPS + // fallback could only ever be configured with Wi-Fi turned off, which + // means in practice never. + if (wifi != null && !withFix) { + done(observation(wifi = wifi, fix = null, homeLat, homeLon, "ok")) + return + } + + val cached = LocationFix.freshestLastKnown(manager) + if (cached != null) { + done(observation(wifi = wifi, fix = cached, homeLat, homeLon, "ok")) + return + } + LocationFix.requestSingle(manager, main) { fix -> + if (fix == null && wifi == null) { + done(unreadable("no-fix")) + } else { + done(observation(wifi = wifi, fix = fix, homeLat, homeLon, "ok")) + } + } + } + + private fun hasLocationPermission(context: Context): Boolean = + ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == + PackageManager.PERMISSION_GRANTED + + /** + * SSID and BSSID of the connected Wi-Fi, or null when neither can be + * trusted. + * + * Android redacts these to [REDACTED_BSSID] and [UNKNOWN_SSID] rather + * than failing when the fine-location grant or location services is + * missing — a redacted value looks exactly like a successful read, so it + * must be filtered here or every morning silently reads "away". + * + * Both are returned because a router hands out a *different* BSSID per + * band and a mesh node one per box, and the phone roams between them + * overnight. Matching on the BSSID alone would call a band switch + * "travelling". + */ + private fun readWifi(context: Context): Pair? { + // getConnectionInfo() is deprecated at API 31 in favour of + // NetworkCapabilities.getTransportInfo(). Do NOT "modernise" this: + // the *synchronous* ConnectivityManager.getNetworkCapabilities() + // redacts every location-sensitive field, so transportInfo comes back + // null and the BSSID silently vanishes. Measured on the Pixel 6a + // (API 36, 2026-08-31): connected to a known AP, fine location + // granted, location services on, and the capabilities route still + // returned ssid=null bssid=null while the GPS fallback masked it. + // Un-redacted transportInfo needs a registerNetworkCallback, which is + // asynchronous and buys nothing here. + @Suppress("DEPRECATION") + val wm = context.applicationContext.getSystemService(Context.WIFI_SERVICE) + as? WifiManager + @Suppress("DEPRECATION") + val info = wm?.connectionInfo + val bssid = info?.bssid?.lowercase()?.takeUnless { + it.isBlank() || it == REDACTED_BSSID || it == ZERO_BSSID + } + val ssid = info?.ssid?.trim('"')?.takeUnless { + it.isBlank() || it == UNKNOWN_SSID + } + return if (bssid == null && ssid == null) null else Pair(ssid, bssid) + } + + private fun observation( + wifi: Pair?, + fix: Location?, + homeLat: Double?, + homeLon: Double?, + reason: String, + ): Map = mapOf( + "ssid" to wifi?.first, + "bssid" to wifi?.second, + "lat" to fix?.latitude, + "lon" to fix?.longitude, + "accuracy" to fix?.accuracy?.toDouble(), + "distanceMeters" to distanceMeters(fix, homeLat, homeLon), + "reason" to reason, + ) + + private fun distanceMeters(fix: Location?, homeLat: Double?, homeLon: Double?): Double? { + if (fix == null || homeLat == null || homeLon == null) return null + val out = FloatArray(1) + Location.distanceBetween(fix.latitude, fix.longitude, homeLat, homeLon, out) + return out[0].toDouble() + } + + private fun unreadable(reason: String): Map = mapOf( + "ssid" to null, + "bssid" to null, + "lat" to null, + "lon" to null, + "accuracy" to null, + "distanceMeters" to null, + "reason" to reason, + ) +} diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/LocationFix.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/LocationFix.kt new file mode 100644 index 0000000..0c243d8 --- /dev/null +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/LocationFix.kt @@ -0,0 +1,94 @@ +package com.kuhy.wake_alarm_sync + +import android.location.Location +import android.location.LocationListener +import android.location.LocationManager +import android.os.Build +import android.os.CancellationSignal +import android.os.Handler +import android.os.Looper +import java.util.concurrent.atomic.AtomicBoolean + +/** + * A single location fix, hand-written on LocationManager. + * + * Split out of [HomePresence] to hold both files under the repo's 250-line + * cap, and because the two halves fail differently: the Wi-Fi read is + * instant and synchronous, a fix is neither. + * + * Everything here is best-effort — every path can hand back null, which + * [HomePresence] reports as unreadable. + */ +object LocationFix { + + /** How long a single fix may take before the read gives up. */ + private const val FIX_TIMEOUT_MS = 5_000L + + /** How stale a cached fix may be and still count as "where we are". */ + private const val LAST_KNOWN_MAX_AGE_MS = 10 * 60 * 1000L + + /** The newest cached fix across every provider, if recent enough. */ + fun freshestLastKnown(manager: LocationManager): Location? { + val cutoff = System.currentTimeMillis() - LAST_KNOWN_MAX_AGE_MS + return providers(manager) + .mapNotNull { runCatching { manager.getLastKnownLocation(it) }.getOrNull() } + .filter { it.time >= cutoff } + .maxByOrNull { it.time } + } + + /** + * Asks for one fix, giving up after [FIX_TIMEOUT_MS]. + * + * The timeout is the point: without it a ring screen indoors waits on a + * GPS fix that is never coming, and the user waits with it. + */ + fun requestSingle( + manager: LocationManager, + main: Handler, + onResult: (Location?) -> Unit, + ) { + val provider = providers(manager).firstOrNull { manager.isProviderEnabled(it) } + if (provider == null) { + onResult(null) + return + } + val settled = AtomicBoolean(false) + fun settle(fix: Location?) { + if (settled.compareAndSet(false, true)) onResult(fix) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val cancel = CancellationSignal() + main.postDelayed({ + if (!settled.get()) cancel.cancel() + settle(null) + }, FIX_TIMEOUT_MS) + runCatching { + manager.getCurrentLocation( + provider, + cancel, + mainExecutor(main), + ) { fix -> settle(fix) } + }.onFailure { settle(null) } + return + } + val listener = LocationListener { fix -> settle(fix) } + main.postDelayed({ + manager.removeUpdates(listener) + settle(null) + }, FIX_TIMEOUT_MS) + runCatching { + @Suppress("DEPRECATION") + manager.requestSingleUpdate(provider, listener, Looper.getMainLooper()) + }.onFailure { settle(null) } + } + + /** Runs the fix callback on the main looper: one thread, no locking. */ + private fun mainExecutor(main: Handler) = java.util.concurrent.Executor { main.post(it) } + + /** Fused first (API 31+): it answers indoors where bare GPS does not. */ + private fun providers(manager: LocationManager): List = buildList { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) add(LocationManager.FUSED_PROVIDER) + add(LocationManager.NETWORK_PROVIDER) + add(LocationManager.GPS_PROVIDER) + }.filter { it in manager.allProviders } +} 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 603b30f..6b46294 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 @@ -35,11 +35,18 @@ class MainActivity : FlutterActivity() { * without it, so the steps fallback would report "sensor unavailable" * forever. That matters because a room proof that can never be satisfied * makes the alarm undismissable, not merely degraded. + * + * ACCESS_FINE_LOCATION (API 23+): without it the connected Wi-Fi's BSSID + * comes back redacted and every provider is silent, so HomePresence can + * never answer. Unreadable means away, so a missing grant would drop the + * strict tag stages at home too. This is the ONLY place it is asked for: + * a permission dialog must never appear over a ringing alarm. */ private fun requestAlarmPermissions() { val wanted = arrayOf( Manifest.permission.POST_NOTIFICATIONS, Manifest.permission.ACTIVITY_RECOGNITION, + Manifest.permission.ACCESS_FINE_LOCATION, ) val missing = wanted.filter { ContextCompat.checkSelfPermission(this, it) != diff --git a/phone_app/lib/screens/home_body.dart b/phone_app/lib/screens/home_body.dart index fe20c5a..ca16cdb 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_presence_line.dart'; import 'package:wake_alarm_sync/ui/theme.dart'; /// The home screen's body: the armed time, the earlier-only control and the @@ -54,6 +55,7 @@ class HomeBody extends StatelessWidget { 'Alarm is armed for', style: TextStyle(fontSize: 16), ), + const HomePresenceLine(), const SizedBox(height: 16), Text( time, diff --git a/phone_app/lib/screens/home_location_screen.dart b/phone_app/lib/screens/home_location_screen.dart new file mode 100644 index 0000000..9f9d9d9 --- /dev/null +++ b/phone_app/lib/screens/home_location_screen.dart @@ -0,0 +1,165 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/home_location_settings.dart'; + +/// Registers the Wi-Fi and coordinate that mean "home". +/// +/// Capture is a deliberate act, pressed once while at home. Until it is +/// pressed nothing changes: an unregistered home keeps the full strict +/// dismiss sequence everywhere. +/// +/// Pressing capture again on the other Wi-Fi band **adds** that access point +/// rather than replacing it — a dual-band router answers to a different +/// address per band and the phone roams between them overnight. +class HomeLocationScreen extends StatefulWidget { + /// Creates the screen; [scheduler] is injectable so tests need no platform. + const HomeLocationScreen({super.key, this.scheduler}); + + /// Platform bridge; defaults to the real MethodChannel. + final AlarmScheduler? scheduler; + + @override + State createState() => _HomeLocationScreenState(); +} + +class _HomeLocationScreenState extends State { + late final AlarmScheduler _scheduler = widget.scheduler ?? AlarmScheduler(); + + HomeLocationSettings _home = const HomeLocationSettings(); + String _status = ''; + bool _busy = false; + + @override + void initState() { + super.initState(); + unawaited(_reload()); + } + + Future _reload() async { + final home = await HomeLocationSettings.load(); + if (!mounted) return; + setState(() => _home = home); + } + + Future _capture() async { + setState(() { + _busy = true; + _status = 'Reading Wi-Fi and location…'; + }); + Map? reading; + try { + reading = await _scheduler.readPresence(withFix: true); + } on Object { + reading = null; + } + if (!mounted) return; + final observed = reading; + if (observed == null) { + setState(() { + _busy = false; + _status = 'Could not read presence.'; + }); + return; + } + final ssid = observed['ssid'] as String?; + final bssid = observed['bssid'] as String?; + final lat = (observed['lat'] as num?)?.toDouble(); + final lon = (observed['lon'] as num?)?.toDouble(); + if (ssid == null && bssid == null && lat == null) { + setState(() { + _busy = false; + // Naming the reason matters: a redacted BSSID and a denied permission + // both look like "nothing here" but need different fixes. + _status = _reasonText(observed['reason'] as String?); + }); + return; + } + final home = await HomeLocationSettings.capture( + ssid: ssid, + bssid: bssid, + lat: lat, + lon: lon, + ); + if (!mounted) return; + setState(() { + _home = home; + _busy = false; + // Name what actually landed. A capture indoors often gets the Wi-Fi and + // no fix, and a bare "Captured." next to "Coordinate: not captured" + // reads as a bug rather than as the GPS fallback being unset. + _status = home.hasCoordinate + ? 'Captured Wi-Fi and coordinate.' + : 'Captured Wi-Fi. No location fix yet — the GPS fallback is unset.'; + }); + } + + Future _clear() async { + await HomeLocationSettings.clear(); + if (!mounted) return; + setState(() { + _home = const HomeLocationSettings(); + _status = 'Cleared — the full sequence now applies everywhere.'; + }); + } + + static String _reasonText(String? reason) => switch (reason) { + 'no-permission' => 'Grant location permission, then try again.', + 'location-disabled' => 'Turn location services on, then try again.', + 'no-fix' => 'No Wi-Fi and no location fix — try again by a window.', + _ => 'Nothing readable here.', + }; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Scaffold( + appBar: AppBar(title: const Text('Home location')), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + Text( + 'Away from home the two NFC tags are unreachable, so they are ' + 'skipped and the alarm asks the usual questions instead. The ' + 'walk is always required.', + style: theme.textTheme.bodyMedium, + ), + const SizedBox(height: 20), + Text('Home Wi-Fi', style: theme.textTheme.titleMedium), + Text(_home.ssid ?? 'not captured'), + const SizedBox(height: 12), + Text('Access points', style: theme.textTheme.titleMedium), + Text(_home.bssids.isEmpty ? 'none' : _home.bssids.join('\n')), + const SizedBox(height: 12), + Text('Coordinate', style: theme.textTheme.titleMedium), + Text( + _home.hasCoordinate + ? '${_home.lat!.toStringAsFixed(5)}, ' + '${_home.lon!.toStringAsFixed(5)} ' + '(±${_home.radiusMeters.round()} m)' + : 'not captured', + ), + const SizedBox(height: 24), + FilledButton( + onPressed: _busy ? null : _capture, + child: const Text('Capture this place as home'), + ), + const SizedBox(height: 8), + Text( + 'Press once on each Wi-Fi band (2.4 GHz and 5 GHz) so a band ' + 'switch overnight is not mistaken for travelling.', + style: theme.textTheme.bodySmall, + ), + const SizedBox(height: 16), + TextButton( + onPressed: _home.isConfigured ? _clear : null, + child: const Text('Forget home'), + ), + const SizedBox(height: 16), + Text(_status, style: theme.textTheme.bodyMedium), + ], + ), + ); + } +} diff --git a/phone_app/lib/screens/home_presence_line.dart b/phone_app/lib/screens/home_presence_line.dart new file mode 100644 index 0000000..99346b2 --- /dev/null +++ b/phone_app/lib/screens/home_presence_line.dart @@ -0,0 +1,66 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/services/home_presence.dart'; + +/// One line saying what tonight's alarm will demand, and why. +/// +/// This exists because an unreadable signal resolves to *away*, which +/// silently drops the two tag stages. A revoked location permission would +/// otherwise weaken the alarm with no error anywhere; here it is a sentence +/// on the home screen naming the cause. +/// +/// Self-loading rather than fed from `HomeScreen`, so the screen absorbs one +/// widget and none of the state. +class HomePresenceLine extends StatefulWidget { + /// Creates the line; [presence] is injectable so tests need no platform. + const HomePresenceLine({super.key, this.presence}); + + /// Presence resolver; defaults to the real one. + final HomePresence? presence; + + @override + State createState() => _HomePresenceLineState(); +} + +class _HomePresenceLineState extends State { + late final HomePresence _presence = widget.presence ?? HomePresence(); + + PresenceVerdict? _verdict; + + @override + void initState() { + super.initState(); + unawaited(_load()); + } + + Future _load() async { + // Never throws by contract, but a platform-less test binding can still + // fail inside SharedPreferences before resolve() gets to catch anything. + PresenceVerdict? verdict; + try { + verdict = await _presence.resolve(); + } on Object { + verdict = null; + } + if (!mounted) return; + setState(() => _verdict = verdict); + } + + @override + Widget build(BuildContext context) { + final verdict = _verdict; + if (verdict == null) return const SizedBox.shrink(); + final atHome = verdict.state == PresenceState.home; + return Padding( + padding: const EdgeInsets.only(top: 12), + child: Text( + atHome + ? 'Tonight: tags required — ${verdict.detail}' + : 'Tonight: tags skipped — ${verdict.detail}', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodySmall, + ), + ); + } +} diff --git a/phone_app/lib/screens/ring_body.dart b/phone_app/lib/screens/ring_body.dart new file mode 100644 index 0000000..839f300 --- /dev/null +++ b/phone_app/lib/screens/ring_body.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/screens/ring_challenge.dart'; +import 'package:wake_alarm_sync/screens/ring_checklist.dart'; +import 'package:wake_alarm_sync/services/challenge.dart'; +import 'package:wake_alarm_sync/services/dismiss_gate.dart'; + +/// The ring screen's body: the checklist, or the live challenge, plus status. +/// +/// Split out of `ring_screen.dart` for the 250-line cap, following +/// `home_body.dart`. Deliberately stateless: the screen keeps the clocks, the +/// gate and the ordering rules, which is where the bugs lived. +class RingBody extends StatelessWidget { + /// Creates the body from already-resolved state. + const RingBody({ + required this.gate, + required this.challenge, + required this.controller, + required this.status, + required this.onSubmit, + super.key, + }); + + /// The sequence being displayed. + final DismissGate gate; + + /// The challenge shown once the challenge stage is live. + final Challenge challenge; + + /// Controller for the answer field. + final TextEditingController controller; + + /// The status line under the body. + final String status; + + /// Called when an answer is submitted. + final VoidCallback onSubmit; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final inChallenges = gate.stage == DismissStage.challenges; + 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 (inChallenges) + RingChallenge( + challenge: challenge, + controller: controller, + passed: gate.challengesPassed, + total: gate.challengesRequired, + onSubmit: onSubmit, + ) + else + RingChecklist(gate: gate), + const SizedBox(height: 16), + Text(status, style: theme.textTheme.bodyMedium), + ], + ), + ), + ), + ), + ); + } +} diff --git a/phone_app/lib/screens/ring_checklist.dart b/phone_app/lib/screens/ring_checklist.dart index 091de7f..618f2b8 100644 --- a/phone_app/lib/screens/ring_checklist.dart +++ b/phone_app/lib/screens/ring_checklist.dart @@ -56,8 +56,14 @@ class RingChecklist extends StatelessWidget { Padding( padding: const EdgeInsets.only(top: 12), child: Text( - 'Tags unavailable — walk, then answer ' - '${gate.challengesRequired} questions instead.', + // This line persists; the status below it is overwritten by the + // live step count within seconds, so the reason the tags went + // away has to live here or the user never sees it. + gate.awayActive + ? 'Away from home — the tags are elsewhere. Walk, then ' + 'answer ${gate.challengesRequired} questions.' + : 'Tags unavailable — walk, then answer ' + '${gate.challengesRequired} questions instead.', style: theme.textTheme.bodyMedium, ), ), diff --git a/phone_app/lib/screens/ring_screen.dart b/phone_app/lib/screens/ring_screen.dart index 04f8667..077761a 100644 --- a/phone_app/lib/screens/ring_screen.dart +++ b/phone_app/lib/screens/ring_screen.dart @@ -2,14 +2,14 @@ import 'dart:async'; import 'dart:developer' as developer; import 'package:flutter/material.dart'; -import 'package:wake_alarm_sync/screens/ring_challenge.dart'; -import 'package:wake_alarm_sync/screens/ring_checklist.dart'; +import 'package:wake_alarm_sync/screens/ring_body.dart'; import 'package:wake_alarm_sync/services/alarm_policy.dart'; import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; import 'package:wake_alarm_sync/services/challenge.dart'; 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/room_proof_settings.dart'; /// How often the live steps stage re-reads the step counter. const Duration kStepPollInterval = Duration(seconds: 2); @@ -25,6 +25,7 @@ class RingScreen extends StatefulWidget { this.scheduler, this.generator, this.clock, + this.presence, }); /// Platform bridge; defaults to the real MethodChannel. @@ -33,6 +34,9 @@ class RingScreen extends StatefulWidget { /// Challenge source; defaults to a secure-random generator. final ChallengeGenerator? generator; + /// Home-presence resolver; defaults to the real one. + final HomePresence? presence; + /// Time since the ring started; defaults to a real `Stopwatch`. /// /// Injectable because `Stopwatch` reads the wall clock, which @@ -48,6 +52,8 @@ class _RingScreenState extends State { late final AlarmScheduler _scheduler = widget.scheduler ?? AlarmScheduler(); late final ChallengeGenerator _generator = widget.generator ?? ChallengeGenerator(); + late final HomePresence _presence = + widget.presence ?? HomePresence(scheduler: _scheduler); late RoomProof _proof = RoomProof(scheduler: _scheduler); final DismissGate _gate = DismissGate(); late Challenge _challenge = _generator.next(); @@ -72,22 +78,27 @@ class _RingScreenState extends State { _stepTimer = Timer.periodic(kStepPollInterval, (_) => _pollSteps()); } - /// Loads the registered tags and starts listening for NFC taps. + /// Resolves presence and the registered tags, then applies the verdict. + /// + /// The ordering lives in `resolveRingStartup`; this only applies what it + /// decided, in one `setState`. Future _loadRoomProof() async { - final settings = await RoomProofSettings.load(); - final hasNfc = await _scheduler.hasNfc(); + final startup = await resolveRingStartup( + scheduler: _scheduler, + presence: _presence, + ); if (!mounted) return; setState(() { - _proof = RoomProof(scheduler: _scheduler, settings: settings); - // Nothing to wait for: without NFC or without two distinct tags the - // tag stages can never be satisfied, so making the user sit through - // the full timer would be pure punishment for a config problem. - if (!hasNfc || !settings.isComplete) { - _gate.activateBypass(); - _status = hasNfc - ? 'Register two NFC tags in Settings.' - : 'NFC is off or unavailable.'; + _proof = RoomProof(scheduler: _scheduler, settings: startup.settings); + switch (startup.skip) { + case RingSkip.away: + _gate.activateAwayProfile(); + case RingSkip.noTags: + _gate.activateBypass(); + case RingSkip.none: + break; } + _status = startup.status; }); _scheduler.onNfcTag(_onNfcTag); } @@ -196,39 +207,11 @@ class _RingScreenState extends State { } @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final inChallenges = _gate.stage == DismissStage.challenges; - 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 (inChallenges) - RingChallenge( - challenge: _challenge, - controller: _input, - passed: _gate.challengesPassed, - total: _gate.challengesRequired, - onSubmit: _submit, - ) - else - RingChecklist(gate: _gate), - const SizedBox(height: 16), - Text(_status, style: theme.textTheme.bodyMedium), - ], - ), - ), - ), - ), - ); - } - + Widget build(BuildContext context) => RingBody( + gate: _gate, + challenge: _challenge, + controller: _input, + status: _status, + onSubmit: _submit, + ); } diff --git a/phone_app/lib/screens/settings_screen.dart b/phone_app/lib/screens/settings_screen.dart index 5271215..a43b8b9 100644 --- a/phone_app/lib/screens/settings_screen.dart +++ b/phone_app/lib/screens/settings_screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; 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/services/firebase_backend.dart'; import 'package:wake_alarm_sync/services/google_sign_in_backend.dart'; @@ -13,6 +14,8 @@ import 'package:wake_alarm_sync/services/google_sign_in_backend.dart'; /// "Advanced sync (GitHub)" stays app-local ([GitHubMirrorScreen]), and /// "Room proof" registers the two NFC tags ([RoomProofScreen]) — without /// a registered tag, NFC can never satisfy the dismiss room proof. +/// "Home location" ([HomeLocationScreen]) registers where the tags are, so +/// the alarm can skip them when it rings somewhere else. class SettingsScreen extends StatelessWidget { /// Creates a [SettingsScreen]. const SettingsScreen({super.key}); @@ -52,6 +55,15 @@ class SettingsScreen extends StatelessWidget { MaterialPageRoute(builder: (_) => const RoomProofScreen()), ), ), + ListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Home location'), + subtitle: const Text('The Wi-Fi and place that mean you are home'), + trailing: const Icon(Icons.chevron_right), + onTap: () => Navigator.of(context).push( + MaterialPageRoute(builder: (_) => const HomeLocationScreen()), + ), + ), ListTile( contentPadding: EdgeInsets.zero, title: const Text('Advanced sync (GitHub)'), diff --git a/phone_app/lib/services/alarm_scheduler.dart b/phone_app/lib/services/alarm_scheduler.dart index d9f2556..4908ec5 100644 --- a/phone_app/lib/services/alarm_scheduler.dart +++ b/phone_app/lib/services/alarm_scheduler.dart @@ -112,4 +112,29 @@ class AlarmScheduler { /// Steps since [beginStepCount], or -1 when unavailable. Future stepsSinceRingStart() async => await _channel.invokeMethod('stepCount') ?? -1; + + /// Raw presence observations: `ssid`, `bssid`, `lat`, `lon`, `accuracy`, + /// `distanceMeters`, `reason`. + /// + /// The home coordinate goes *in* so Kotlin can return `distanceMeters` from + /// `Location.distanceBetween` — otherwise the policy file would have to + /// hand-roll Haversine to be unit testable. Null when the platform is + /// absent, which `HomePresence` reads as unreadable, i.e. away. + /// + /// [withFix] makes it wait for a location fix even when Wi-Fi already + /// answered. Registration wants that; the ring screen does not, because + /// skipping GPS is what makes the verdict instant at home. + Future?> readPresence({ + double? homeLat, + double? homeLon, + bool withFix = false, + }) async { + final result = await _channel + .invokeMapMethod('readPresence', { + 'homeLat': homeLat, + 'homeLon': homeLon, + 'withFix': withFix, + }); + return result; + } } diff --git a/phone_app/lib/services/dismiss_gate.dart b/phone_app/lib/services/dismiss_gate.dart index dbce195..bf973c4 100644 --- a/phone_app/lib/services/dismiss_gate.dart +++ b/phone_app/lib/services/dismiss_gate.dart @@ -50,6 +50,7 @@ class DismissGate { int _challengesPassed = 0; int _challengesRequired = challengesNormal; bool _bypassed = false; + bool _away = false; /// The stage currently awaiting satisfaction. DismissStage get stage => _stage; @@ -63,6 +64,13 @@ class DismissGate { /// Whether the NFC stages have been skipped. bool get bypassActive => _bypassed; + /// Whether they were skipped because the phone is away from home. + /// + /// Purely for wording: "tags unavailable" reads as a hardware fault, which + /// is the wrong thing to tell someone in a hotel. Kept off the latch so it + /// cannot affect [challengesRequired] or the stage arithmetic. + bool get awayActive => _away; + /// Whether the alarm may now be dismissed. bool get isDone => _stage == DismissStage.done; @@ -122,21 +130,48 @@ class DismissGate { /// Drops the NFC requirement, raising the challenge count instead. /// + /// The escape hatch for tags that cannot be read: a dead tag, an NFC radio + /// that will not poll, a tag that fell off the wall. The count rises so + /// skipping the walk is never the cheap option. + /// + /// Refused once [activateAwayProfile] has fired: away from home the tags + /// are already gone, so the only remaining effect would be the punitive + /// 3 -> 6, which is exactly what the away morning must not get. That guard + /// is load-bearing, not defensive — the ring screen's [bypassAfter] timer + /// fires unconditionally, and an away morning is a two-minute walk plus + /// three questions, which crosses five minutes routinely. + bool activateBypass() => _skipTags(challengesBypass); + + /// Skips the tag stages because the tags are somewhere else entirely. + /// + /// Being away from home is not cheating, so unlike [activateBypass] the + /// count stays at [challengesNormal]. **The walk is still required**: the + /// tags are what cannot be reached in a hotel, not the standing up. + bool activateAwayProfile() { + final skipped = _skipTags(challengesNormal); + if (skipped) _away = true; + return skipped; + } + + /// Skips the two tag stages and fixes the challenge count at [required]. + /// /// **Only the two tag stages are skipped — the walk still counts.** Jumping /// straight to the challenges would let someone lie in bed for /// [bypassAfter] and then answer questions without ever standing up, which /// is a weaker gate than the one this change replaced. /// - /// One-way and idempotent. Deliberately refused once the challenge stage is - /// live: the user has already done the walk by then, and raising 3 to 6 - /// mid-answer would punish them for being slow at arithmetic. - bool activateBypass() { + /// One-way and idempotent, so whichever reason arrives first wins and no + /// later one can raise the count behind the user's back. Deliberately + /// refused once the challenge stage is live: the user has already done the + /// walk by then, and raising 3 to 6 mid-answer would punish them for being + /// slow at arithmetic. + bool _skipTags(int required) { if (_bypassed) return false; if (_stage == DismissStage.challenges || _stage == DismissStage.done) { return false; } _bypassed = true; - _challengesRequired = challengesBypass; + _challengesRequired = required; // Past tag 2 the steps are already banked; otherwise fall back to them. _stage = _stage == DismissStage.tag2 ? DismissStage.challenges diff --git a/phone_app/lib/services/home_location_settings.dart b/phone_app/lib/services/home_location_settings.dart new file mode 100644 index 0000000..1f62bcb --- /dev/null +++ b/phone_app/lib/services/home_location_settings.dart @@ -0,0 +1,135 @@ +import 'dart:convert'; + +import 'package:shared_preferences/shared_preferences.dart'; + +/// Persisted home location: the Wi-Fi that means "home", plus a coordinate. +/// +/// Registered from Settings by pressing capture once while at home. Nothing +/// is inferred and nothing is captured in the background. +/// +/// **Unregistered is not "away".** An install that has never captured a home +/// keeps the full strict dismiss sequence; the geofence only starts +/// restricting once it has been told where home is. Treating unconfigured as +/// away would silently delete the whole NFC ritual on the first morning after +/// an update. +class HomeLocationSettings { + /// Creates settings from stored values. + const HomeLocationSettings({ + this.ssid, + this.bssids = const [], + this.lat, + this.lon, + this.radiusMeters = defaultRadiusMeters, + }); + + /// SharedPreferences key holding the whole record as JSON. + static const String kKey = 'homeLocation.value'; + + /// How far from the stored coordinate still counts as home. + static const double defaultRadiusMeters = 150; + + /// Network name of the home Wi-Fi, or null when none was captured. + final String? ssid; + + /// Every access-point address seen at home, lowercased. + /// + /// A list, not a single value: a dual-band router answers to a different + /// BSSID per band and a mesh node one per box, and the phone roams between + /// them overnight. One stored address would call a band switch "travelling". + final List bssids; + + /// Latitude of the captured home, or null when none was captured. + final double? lat; + + /// Longitude of the captured home, or null when none was captured. + final double? lon; + + /// Radius around ([lat], [lon]) that counts as home. + final double radiusMeters; + + /// Whether a home has ever been captured. + bool get isConfigured => ssid != null || bssids.isNotEmpty || hasCoordinate; + + /// Whether a coordinate is stored, so the GPS fallback can be used. + bool get hasCoordinate => lat != null && lon != null; + + /// Whether [ssid]/[bssid] identify the home network. + /// + /// Either signal is enough. The SSID survives roaming between bands and + /// mesh nodes; the BSSID list is the stricter check for a captured AP. + bool matchesWifi({String? ssid, String? bssid}) { + if (ssid != null && ssid == this.ssid) return true; + return bssid != null && bssids.contains(bssid.toLowerCase()); + } + + /// Loads the stored home; anything malformed reads as unconfigured. + static Future load() async { + final prefs = await SharedPreferences.getInstance(); + final stored = prefs.getString(kKey); + if (stored == null) return const HomeLocationSettings(); + try { + final decoded = jsonDecode(stored); + if (decoded is! Map) return const HomeLocationSettings(); + final bssids = decoded['bssids']; + return HomeLocationSettings( + ssid: decoded['ssid'] as String?, + bssids: bssids is List + ? bssids.whereType().map((b) => b.toLowerCase()).toList() + : const [], + lat: (decoded['lat'] as num?)?.toDouble(), + lon: (decoded['lon'] as num?)?.toDouble(), + radiusMeters: + (decoded['radiusMeters'] as num?)?.toDouble() ?? + defaultRadiusMeters, + ); + } on FormatException { + return const HomeLocationSettings(); + } + } + + /// Records this place as home, merging [bssid] into any already captured. + /// + /// Merging rather than replacing is what lets a second press on the other + /// band add to the set instead of overwriting it. + static Future capture({ + String? ssid, + String? bssid, + double? lat, + double? lon, + }) async { + final current = await load(); + final merged = { + ...current.bssids, + if (bssid != null) bssid.toLowerCase(), + }.toList(); + final next = HomeLocationSettings( + ssid: ssid ?? current.ssid, + bssids: merged, + lat: lat ?? current.lat, + lon: lon ?? current.lon, + radiusMeters: current.radiusMeters, + ); + await _save(next); + return next; + } + + /// Forgets the stored home, returning the app to the strict sequence. + static Future clear() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(kKey); + } + + static Future _save(HomeLocationSettings value) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString( + kKey, + jsonEncode({ + 'ssid': value.ssid, + 'bssids': value.bssids, + 'lat': value.lat, + 'lon': value.lon, + 'radiusMeters': value.radiusMeters, + }), + ); + } +} diff --git a/phone_app/lib/services/home_presence.dart b/phone_app/lib/services/home_presence.dart new file mode 100644 index 0000000..c6ce6fd --- /dev/null +++ b/phone_app/lib/services/home_presence.dart @@ -0,0 +1,128 @@ +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/home_location_settings.dart'; + +/// Where the phone is, as far as the dismiss sequence is concerned. +enum PresenceState { + /// At the registered home: the full strict sequence applies. + home, + + /// Not at the registered home, or presence could not be read at all. + away, +} + +/// A presence verdict and the reason for it. +/// +/// [detail] is shown to the user rather than logged away: an unreadable +/// signal resolves to [PresenceState.away], which silently drops the two tag +/// stages, so the cause has to be visible somewhere. +class PresenceVerdict { + /// Creates a verdict. + const PresenceVerdict(this.state, this.detail); + + /// Whether the phone counts as being at home. + final PresenceState state; + + /// Why, in words fit for the home screen. + final String detail; + + /// Whether the two NFC tag stages should be skipped. + bool get skipsTags => state == PresenceState.away; +} + +/// Decides whether the phone is at its registered home. +/// +/// Wi-Fi first, GPS only as a fallback: at home the network name is instant +/// and works indoors, while a fix at 06:00 with the screen off may take 30 +/// seconds or never arrive. +/// +/// **Unreadable means away.** A denied permission, a disabled location +/// service, Wi-Fi off with no fix — all of it resolves to +/// [PresenceState.away] rather than guessing. The one exception is an +/// unconfigured home, which stays [PresenceState.home]: see +/// [HomeLocationSettings]. +class HomePresence { + /// Creates a resolver; [scheduler] is injectable so tests need no platform. + HomePresence({AlarmScheduler? scheduler}) + : _scheduler = scheduler ?? AlarmScheduler(); + + final AlarmScheduler _scheduler; + + /// Resolves presence. Never throws — any failure is a verdict, not an error. + Future resolve() async { + final settings = await HomeLocationSettings.load(); + if (!settings.isConfigured) { + return const PresenceVerdict( + PresenceState.home, + 'no home registered — full sequence', + ); + } + Map? reading; + try { + reading = await _scheduler.readPresence( + homeLat: settings.lat, + homeLon: settings.lon, + ); + } on Object { + // A missing platform, a channel error, a thrown SecurityException: all + // of it is "cannot tell", which is away. + reading = null; + } + return decide(settings, reading); + } + + /// The whole comparison, pure: no channel, no preferences, no clock. + static PresenceVerdict decide( + HomeLocationSettings settings, + Map? reading, + ) { + if (reading == null) { + return const PresenceVerdict(PresenceState.away, 'presence unreadable'); + } + final ssid = reading['ssid'] as String?; + final bssid = reading['bssid'] as String?; + if (settings.matchesWifi(ssid: ssid, bssid: bssid)) { + return PresenceVerdict( + PresenceState.home, + 'home Wi-Fi (${ssid ?? bssid})', + ); + } + final distance = (reading['distanceMeters'] as num?)?.toDouble(); + if (distance != null && settings.hasCoordinate) { + // The accuracy circle counts in the user's favour. A coarse network fix + // indoors is routinely 100m+, and being lenient here can only ever err + // towards the strict sequence at home — never towards a hotel. + final accuracy = (reading['accuracy'] as num?)?.toDouble() ?? 0; + if (distance <= settings.radiusMeters + accuracy) { + return PresenceVerdict( + PresenceState.home, + 'within ${distance.round()} m of home', + ); + } + return PresenceVerdict( + PresenceState.away, + '${_readableDistance(distance)} from home', + ); + } + if (ssid != null || bssid != null) { + return PresenceVerdict( + PresenceState.away, + 'on ${ssid ?? bssid}, not the home Wi-Fi', + ); + } + return PresenceVerdict( + PresenceState.away, + _reasonText(reading['reason'] as String?), + ); + } + + static String _readableDistance(double metres) => metres >= 1000 + ? '${(metres / 1000).round()} km' + : '${metres.round()} m'; + + static String _reasonText(String? reason) => switch (reason) { + 'no-permission' => 'location permission denied', + 'location-disabled' => 'location services are off', + 'no-fix' => 'no location fix', + _ => 'presence unreadable', + }; +} diff --git a/phone_app/lib/services/ring_startup.dart b/phone_app/lib/services/ring_startup.dart new file mode 100644 index 0000000..1878619 --- /dev/null +++ b/phone_app/lib/services/ring_startup.dart @@ -0,0 +1,84 @@ +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/dismiss_gate.dart'; +import 'package:wake_alarm_sync/services/home_presence.dart'; +import 'package:wake_alarm_sync/services/room_proof_settings.dart'; + +/// Why, if at all, the ring screen should skip the two NFC tag stages. +enum RingSkip { + /// The strict sequence applies: tag 1, walk, tag 2, challenges. + none, + + /// The phone is not at its registered home, so the tags are unreachable. + /// + /// The challenge count stays at [DismissGate.challengesNormal]. + away, + + /// NFC is off, or fewer than two distinct tags are registered. + /// + /// The challenge count rises to [DismissGate.challengesBypass]. + noTags, +} + +/// What the ring screen learned before it could decide anything. +class RingStartup { + /// Creates a startup decision. + const RingStartup({ + required this.settings, + required this.skip, + required this.status, + }); + + /// The registered tags, for `RoomProof`. + final RoomProofSettings settings; + + /// Which skip, if any, to apply to the gate. + final RingSkip skip; + + /// A line for the ring screen; empty when the strict sequence applies. + final String status; +} + +/// Resolves what the ring screen should do, in one strictly ordered pass. +/// +/// **Presence is resolved first, and that ordering is the point.** Both skips +/// latch one-way, so whichever fires first fixes the challenge count. If the +/// missing-tags check ran first it would set 6, the away verdict arriving a +/// moment later could not lower it, and every away morning with NFC off would +/// silently get the punitive count. +/// +/// Sequential rather than concurrent for the same reason `HomeScreen`'s +/// bootstrap is: the later steps read what the earlier ones decide, and the +/// last time these ran in parallel the result was a value captured before it +/// was ever assigned. +Future resolveRingStartup({ + required AlarmScheduler scheduler, + required HomePresence presence, +}) async { + final verdict = await presence.resolve(); + final settings = await RoomProofSettings.load(); + final hasNfc = await scheduler.hasNfc(); + if (verdict.skipsTags) { + return RingStartup( + settings: settings, + skip: RingSkip.away, + status: 'Away from home (${verdict.detail}) — tags skipped.', + ); + } + // Nothing to wait for: without NFC or without two distinct tags the tag + // stages can never be satisfied, so making the user sit through the full + // timer would be pure punishment for a config problem. + if (!hasNfc || !settings.isComplete) { + return RingStartup( + settings: settings, + skip: RingSkip.noTags, + status: hasNfc + ? 'Register two NFC tags in Settings.' + : 'NFC is off or unavailable.', + ); + } + return RingStartup( + settings: settings, + skip: RingSkip.none, + status: '', + ); +} diff --git a/phone_app/test/home_location_screen_test.dart b/phone_app/test/home_location_screen_test.dart new file mode 100644 index 0000000..b2285cb --- /dev/null +++ b/phone_app/test/home_location_screen_test.dart @@ -0,0 +1,89 @@ +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/home_location_screen.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/home_location_settings.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + Map? presence; + + setUp(() { + presence = null; + SharedPreferences.setMockInitialValues({}); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel(AlarmScheduler.channelName), + (call) async => call.method == 'readPresence' ? presence : null, + ); + }); + + Future pumpScreen(WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp(home: HomeLocationScreen()), + ); + await tester.pump(); + } + + testWidgets('a fresh install shows nothing captured', (tester) async { + await pumpScreen(tester); + expect(find.text('not captured'), findsNWidgets(2)); + expect(find.text('none'), findsOneWidget); + }); + + testWidgets('capture stores what the platform reported', (tester) async { + presence = { + 'ssid': 'Orange_Home', + 'bssid': 'CC:00:F1:AE:D6:C4', + 'lat': 52.2291, + 'lon': 20.9512, + 'reason': 'ok', + }; + await pumpScreen(tester); + await tester.tap(find.text('Capture this place as home')); + await tester.pumpAndSettle(); + + expect(find.textContaining('Captured Wi-Fi'), findsOneWidget); + final home = await HomeLocationSettings.load(); + expect(home.ssid, 'Orange_Home'); + expect(home.bssids, ['cc:00:f1:ae:d6:c4']); + expect(home.hasCoordinate, isTrue); + }); + + testWidgets('a Wi-Fi-only capture says the GPS fallback is unset', ( + tester, + ) async { + presence = {'ssid': 'Orange_Home', 'reason': 'ok'}; + await pumpScreen(tester); + await tester.tap(find.text('Capture this place as home')); + await tester.pumpAndSettle(); + + expect(find.textContaining('GPS fallback is unset'), findsOneWidget); + expect((await HomeLocationSettings.load()).hasCoordinate, isFalse); + }); + + testWidgets('a denied permission says so instead of capturing nothing', ( + tester, + ) async { + presence = {'reason': 'no-permission'}; + await pumpScreen(tester); + await tester.tap(find.text('Capture this place as home')); + await tester.pumpAndSettle(); + + expect(find.textContaining('Grant location permission'), findsOneWidget); + expect((await HomeLocationSettings.load()).isConfigured, isFalse); + }); + + testWidgets('forget home returns to the strict sequence', (tester) async { + await HomeLocationSettings.capture(ssid: 'Orange_Home'); + await pumpScreen(tester); + await tester.tap(find.text('Forget home')); + await tester.pumpAndSettle(); + + expect(find.textContaining('full sequence now applies'), findsOneWidget); + expect((await HomeLocationSettings.load()).isConfigured, isFalse); + }); +} diff --git a/phone_app/test/ring_away_test.dart b/phone_app/test/ring_away_test.dart new file mode 100644 index 0000000..befb40f --- /dev/null +++ b/phone_app/test/ring_away_test.dart @@ -0,0 +1,144 @@ +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/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/challenge.dart'; +import 'package:wake_alarm_sync/services/dismiss_gate.dart'; +import 'package:wake_alarm_sync/services/home_location_settings.dart'; +import 'package:wake_alarm_sync/services/room_proof_settings.dart'; + +const String _tag1 = '04a2b3c4'; +const String _tag2 = '04ffee11'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + var steps = 0; + var elapsed = Duration.zero; + Map? presence; + + void mockChannel() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel(AlarmScheduler.channelName), + (call) async { + if (call.method == 'stepCount') return steps; + if (call.method == 'hasNfc') return true; + if (call.method == 'readPresence') return presence; + return null; + }, + ); + } + + setUp(() { + steps = 0; + elapsed = Duration.zero; + presence = null; + SharedPreferences.setMockInitialValues({}); + mockChannel(); + }); + + /// A ring screen with both tags registered and a controllable clock. + Future pumpRing(WidgetTester tester) async { + await RoomProofSettings.saveNfcTagAt(0, _tag1); + await RoomProofSettings.saveNfcTagAt(1, _tag2); + await tester.pumpWidget( + MaterialApp( + home: RingScreen( + generator: ChallengeGenerator(random: Random(1)), + clock: () => elapsed, + ), + ), + ); + await tester.pump(); + await tester.pump(); + } + + testWidgets('at home the strict sequence is unchanged', (tester) async { + await HomeLocationSettings.capture(ssid: 'Orange_Home'); + presence = {'ssid': 'Orange_Home', 'reason': 'ok'}; + await pumpRing(tester); + + expect(find.text('Tap tag 1'), findsOneWidget); + expect(find.text('Tap tag 2'), findsOneWidget); + }); + + testWidgets('away it skips the tags, keeps the walk, and asks 3', ( + tester, + ) async { + await HomeLocationSettings.capture(ssid: 'Orange_Home'); + presence = {'ssid': 'Hotel_Guest', 'reason': 'ok'}; + await pumpRing(tester); + + expect(find.textContaining('Away from home'), findsWidgets); + // The persistent line, not the status that the step poll overwrites. + expect(find.textContaining('the tags are elsewhere'), findsOneWidget); + expect(find.textContaining('Tags unavailable'), findsNothing); + expect(find.text('Tap tag 1'), findsNothing); + expect(find.text('Tap tag 2'), findsNothing); + // The walk is never skipped: away is where the tags are, not the bed. + expect(find.text('Walk 25 steps'), findsOneWidget); + + steps = 500; + elapsed = const Duration(minutes: 3); + await tester.pump(kStepPollInterval); + await tester.pump(); + expect(find.text('Question 1 of 3'), findsOneWidget); + }); + + testWidgets('the five-minute timer does not bump an away morning to 6', ( + tester, + ) async { + await HomeLocationSettings.capture(ssid: 'Orange_Home'); + presence = {'ssid': 'Hotel_Guest', 'reason': 'ok'}; + await pumpRing(tester); + + steps = 500; + elapsed = const Duration(minutes: 3); + await tester.pump(kStepPollInterval); + await tester.pump(); + expect(find.text('Question 1 of 3'), findsOneWidget); + + // An away morning routinely outlasts the bypass timer. + await tester.pump(DismissGate.bypassAfter); + await tester.pump(); + expect(find.text('Question 1 of 3'), findsOneWidget); + expect(find.text('Question 1 of 6'), findsNothing); + }); + + testWidgets('unreadable presence is away, per the chosen fail mode', ( + tester, + ) async { + await HomeLocationSettings.capture(ssid: 'Orange_Home'); + presence = {'reason': 'no-permission'}; + await pumpRing(tester); + + expect(find.textContaining('location permission denied'), findsOneWidget); + expect(find.text('Tap tag 1'), findsNothing); + }); + + testWidgets('away wins over missing tags, so the count stays 3', ( + tester, + ) async { + // Ordering regression: if the missing-tag bypass were applied first it + // would latch 6, and the away verdict arriving later could not lower it. + await HomeLocationSettings.capture(ssid: 'Orange_Home'); + presence = {'ssid': 'Hotel_Guest', 'reason': 'ok'}; + await RoomProofSettings.saveNfcTagAt(0, _tag1); + await tester.pumpWidget( + MaterialApp(home: RingScreen(clock: () => elapsed)), + ); + await tester.pump(); + await tester.pump(); + + steps = 500; + elapsed = const Duration(minutes: 3); + await tester.pump(kStepPollInterval); + await tester.pump(); + expect(find.text('Question 1 of 3'), findsOneWidget); + }); +} diff --git a/phone_app/test/ring_bypass_test.dart b/phone_app/test/ring_bypass_test.dart index 62319a8..94a736b 100644 --- a/phone_app/test/ring_bypass_test.dart +++ b/phone_app/test/ring_bypass_test.dart @@ -81,6 +81,8 @@ void main() { await tester.pump(); expect(find.textContaining('Tags unavailable'), findsOneWidget); + // A hardware bypass must not borrow the away wording. + expect(find.textContaining('Away from home'), findsNothing); expect(find.text('Tap tag 1'), findsNothing); expect(find.text('Walk 25 steps'), findsOneWidget); expect(find.text('Submit'), findsNothing); diff --git a/phone_app/test/services/dismiss_gate_test.dart b/phone_app/test/services/dismiss_gate_test.dart index 009b295..467fa57 100644 --- a/phone_app/test/services/dismiss_gate_test.dart +++ b/phone_app/test/services/dismiss_gate_test.dart @@ -162,4 +162,77 @@ void main() { greaterThan(DismissGate.challengesNormal), ); }); + + group('away from home', () { + test('skips the tags but keeps the normal challenge count', () { + final gate = DismissGate()..activateAwayProfile(); + expect(gate.bypassActive, isTrue); + expect(gate.challengesRequired, DismissGate.challengesNormal); + expect(gate.stage, DismissStage.steps); + }); + + test('still requires the walk', () { + final gate = DismissGate()..activateAwayProfile(); + expect(gate.stage, DismissStage.steps); + expect(gate.passStepsStage(), isTrue); + expect(gate.stage, DismissStage.challenges); + }); + + test('the five-minute bypass cannot raise an away morning to 6', () { + // The ring screen's bypass timer fires unconditionally, and an away + // morning is a two-minute walk plus three questions -- it crosses five + // minutes routinely. If this ever returns true the user is punished + // for travelling, and the only symptom is one wrong digit on screen. + final gate = DismissGate()..activateAwayProfile(); + expect(gate.activateBypass(), isFalse); + expect(gate.challengesRequired, DismissGate.challengesNormal); + }); + + test('a missing-tags bypass already at 6 is not lowered by away', () { + final gate = DismissGate()..activateBypass(); + expect(gate.activateAwayProfile(), isFalse); + expect(gate.challengesRequired, DismissGate.challengesBypass); + }); + + test('is idempotent', () { + final gate = DismissGate()..activateAwayProfile(); + expect(gate.activateAwayProfile(), isFalse); + }); + + test('says away, not "tags unavailable", and only when it is', () { + // Wording only -- a hotel is not a hardware fault. Must stay off the + // latch, so it can never move the challenge count. + expect(DismissGate().awayActive, isFalse); + expect((DismissGate()..activateBypass()).awayActive, isFalse); + final away = DismissGate()..activateAwayProfile(); + expect(away.awayActive, isTrue); + expect(away.challengesRequired, DismissGate.challengesNormal); + }); + + test('a refused away skip does not claim to be away', () { + final gate = DismissGate()..activateBypass(); + expect(gate.activateAwayProfile(), isFalse); + expect(gate.awayActive, isFalse); + expect(gate.challengesRequired, DismissGate.challengesBypass); + }); + + test('is refused once the challenges are live', () { + final gate = DismissGate() + ..passTagStage() + ..passStepsStage() + ..passTagStage(); + expect(gate.stage, DismissStage.challenges); + expect(gate.activateAwayProfile(), isFalse); + expect(gate.challengesRequired, DismissGate.challengesNormal); + }); + + test('past tag 2 the banked steps are not asked for again', () { + final gate = DismissGate()..passTagStage(); + expect(gate.passStepsStage(), isTrue); + expect(gate.stage, DismissStage.tag2); + expect(gate.activateAwayProfile(), isTrue); + expect(gate.stage, DismissStage.challenges); + expect(gate.challengesRequired, DismissGate.challengesNormal); + }); + }); } diff --git a/phone_app/test/services/home_location_settings_test.dart b/phone_app/test/services/home_location_settings_test.dart new file mode 100644 index 0000000..b949554 --- /dev/null +++ b/phone_app/test/services/home_location_settings_test.dart @@ -0,0 +1,87 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/services/home_location_settings.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() => SharedPreferences.setMockInitialValues({})); + + test('a fresh install has no home, which is not the same as away', () async { + final home = await HomeLocationSettings.load(); + expect(home.isConfigured, isFalse); + expect(home.hasCoordinate, isFalse); + expect(home.radiusMeters, HomeLocationSettings.defaultRadiusMeters); + }); + + test('capture round-trips every field', () async { + await HomeLocationSettings.capture( + ssid: 'Orange_Home', + bssid: 'CC:00:F1:AE:D6:C4', + lat: 52.2291, + lon: 20.9512, + ); + final home = await HomeLocationSettings.load(); + expect(home.ssid, 'Orange_Home'); + expect(home.bssids, ['cc:00:f1:ae:d6:c4']); + expect(home.lat, closeTo(52.2291, 1e-6)); + expect(home.hasCoordinate, isTrue); + expect(home.isConfigured, isTrue); + }); + + test('a second capture adds a band rather than replacing it', () async { + await HomeLocationSettings.capture( + ssid: 'Home', + bssid: 'aa:bb:cc:dd:ee:01', + ); + await HomeLocationSettings.capture( + ssid: 'Home', + bssid: 'aa:bb:cc:dd:ee:02', + ); + final home = await HomeLocationSettings.load(); + expect(home.bssids, hasLength(2)); + expect(home.matchesWifi(bssid: 'AA:BB:CC:DD:EE:02'), isTrue); + }); + + test('the same band captured twice is stored once', () async { + await HomeLocationSettings.capture(bssid: 'aa:bb:cc:dd:ee:01'); + await HomeLocationSettings.capture(bssid: 'AA:BB:CC:DD:EE:01'); + final home = await HomeLocationSettings.load(); + expect(home.bssids, hasLength(1)); + }); + + test('capture keeps a coordinate a later Wi-Fi-only capture omits', () async { + await HomeLocationSettings.capture(lat: 52.5, lon: 21.5); + await HomeLocationSettings.capture(ssid: 'Home'); + final home = await HomeLocationSettings.load(); + expect(home.hasCoordinate, isTrue); + expect(home.ssid, 'Home'); + }); + + test('the SSID matches whichever band the phone roamed onto', () { + const home = HomeLocationSettings( + ssid: 'Home', + bssids: ['aa:bb:cc:dd:ee:01'], + ); + // The 5 GHz radio was never captured, but it broadcasts the same name. + expect(home.matchesWifi(ssid: 'Home', bssid: 'aa:bb:cc:dd:ee:99'), isTrue); + expect( + home.matchesWifi(ssid: 'Hotel', bssid: '11:22:33:44:55:66'), + isFalse, + ); + expect(home.matchesWifi(), isFalse); + }); + + test('clear returns the app to the strict sequence', () async { + await HomeLocationSettings.capture(ssid: 'Home'); + await HomeLocationSettings.clear(); + expect((await HomeLocationSettings.load()).isConfigured, isFalse); + }); + + test('a malformed record reads as unconfigured, never as away', () async { + SharedPreferences.setMockInitialValues({ + HomeLocationSettings.kKey: 'not json', + }); + expect((await HomeLocationSettings.load()).isConfigured, isFalse); + }); +} diff --git a/phone_app/test/services/home_presence_test.dart b/phone_app/test/services/home_presence_test.dart new file mode 100644 index 0000000..aade105 --- /dev/null +++ b/phone_app/test/services/home_presence_test.dart @@ -0,0 +1,166 @@ +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/home_location_settings.dart'; +import 'package:wake_alarm_sync/services/home_presence.dart'; + +const HomeLocationSettings _home = HomeLocationSettings( + ssid: 'Orange_Home', + bssids: ['cc:00:f1:ae:d6:c4'], + lat: 52.2291, + lon: 20.9512, +); + +Map _reading({ + String? ssid, + String? bssid, + double? distance, + double? accuracy, + String reason = 'ok', +}) => { + 'ssid': ssid, + 'bssid': bssid, + 'lat': distance == null ? null : 52.0, + 'lon': distance == null ? null : 21.0, + 'accuracy': accuracy, + 'distanceMeters': distance, + 'reason': reason, +}; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('decide', () { + test('the home SSID is home', () { + final verdict = HomePresence.decide(_home, _reading(ssid: 'Orange_Home')); + expect(verdict.state, PresenceState.home); + expect(verdict.skipsTags, isFalse); + }); + + test('a captured BSSID is home even under a different name', () { + final verdict = HomePresence.decide( + _home, + _reading(ssid: 'Orange_Home_5G', bssid: 'CC:00:F1:AE:D6:C4'), + ); + expect(verdict.state, PresenceState.home); + }); + + test('a redacted BSSID is not a match', () { + // Kotlin filters 02:00:00:00:00:00 to null; if it ever leaked through + // as a literal it must still not match a captured address. + final verdict = HomePresence.decide( + _home, + _reading(bssid: '02:00:00:00:00:00'), + ); + expect(verdict.state, PresenceState.away); + }); + + test("someone else's Wi-Fi is away, and says so", () { + final verdict = HomePresence.decide(_home, _reading(ssid: 'Hotel_Guest')); + expect(verdict.state, PresenceState.away); + expect(verdict.detail, contains('Hotel_Guest')); + }); + + test('inside the radius is home', () { + final verdict = HomePresence.decide(_home, _reading(distance: 40)); + expect(verdict.state, PresenceState.home); + }); + + test('outside the radius is away, in readable units', () { + final verdict = HomePresence.decide(_home, _reading(distance: 25712)); + expect(verdict.state, PresenceState.away); + expect(verdict.detail, contains('26 km')); + }); + + test('a coarse fix counts in the user favour, not against it', () { + // 200 m away with a 100 m error circle and a 150 m radius: the fix + // cannot distinguish home from not-home, and erring towards the strict + // sequence at home is the safe direction for a wake-up alarm. + final verdict = HomePresence.decide( + _home, + _reading(distance: 200, accuracy: 100), + ); + expect(verdict.state, PresenceState.home); + }); + + test('a coarse fix still cannot rescue a different city', () { + final verdict = HomePresence.decide( + _home, + _reading(distance: 25712, accuracy: 500), + ); + expect(verdict.state, PresenceState.away); + }); + + test('nothing readable is away, naming the cause', () { + for (final (reason, text) in <(String, String)>[ + ('no-permission', 'permission'), + ('location-disabled', 'services are off'), + ('no-fix', 'no location fix'), + ]) { + final verdict = HomePresence.decide(_home, _reading(reason: reason)); + expect(verdict.state, PresenceState.away, reason: reason); + expect(verdict.detail, contains(text)); + } + }); + + test('a null reading is away, never a crash', () { + expect(HomePresence.decide(_home, null).state, PresenceState.away); + }); + + test('a distance without a stored coordinate falls through', () { + const wifiOnly = HomeLocationSettings(ssid: 'Orange_Home'); + final verdict = HomePresence.decide(wifiOnly, _reading(distance: 40)); + expect(verdict.state, PresenceState.away); + }); + }); + + group('resolve', () { + setUp(() => SharedPreferences.setMockInitialValues({})); + + void mockChannel(Object? Function() reading) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel(AlarmScheduler.channelName), + (call) async => + call.method == 'readPresence' ? reading() : null, + ); + } + + test('an unregistered home stays on the strict sequence', () async { + var called = false; + mockChannel(() { + called = true; + return _reading(ssid: 'Hotel_Guest'); + }); + final verdict = await HomePresence().resolve(); + expect(verdict.state, PresenceState.home); + expect(verdict.skipsTags, isFalse); + // The whole point: no home, no channel call, no permission needed. + expect(called, isFalse); + }); + + test('a registered home consults the platform', () async { + await HomeLocationSettings.capture(ssid: 'Orange_Home'); + mockChannel(() => _reading(ssid: 'Orange_Home')); + expect((await HomePresence().resolve()).state, PresenceState.home); + }); + + test('a platform error is away, not an exception', () async { + await HomeLocationSettings.capture(ssid: 'Orange_Home'); + mockChannel(() => throw PlatformException(code: 'boom')); + final verdict = await HomePresence().resolve(); + expect(verdict.state, PresenceState.away); + }); + + test('a missing platform is away', () async { + await HomeLocationSettings.capture(ssid: 'Orange_Home'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel(AlarmScheduler.channelName), + null, + ); + expect((await HomePresence().resolve()).state, PresenceState.away); + }); + }); +} diff --git a/phone_app/test/settings_screen_test.dart b/phone_app/test/settings_screen_test.dart index 2ec5017..dfdc7d3 100644 --- a/phone_app/test/settings_screen_test.dart +++ b/phone_app/test/settings_screen_test.dart @@ -13,6 +13,8 @@ void main() { expect(find.text('Sync settings'), findsOneWidget); expect(find.text('Advanced sync (GitHub)'), findsOneWidget); + expect(find.text('Room proof'), findsOneWidget); + expect(find.text('Home location'), findsOneWidget); await tester.tap(find.text('Advanced sync (GitHub)')); await tester.pumpAndSettle();