mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-22 15:22:18 +01:00
Count a paused alarm as a bypass
The launcher "Wstrzymaj aplikację" paused WakeAlarm mid-ring on 11-20 and 11-22. WakeAlarm is now a device admin, and a pause, admin removal, revoked notifications or full-screen intent, or a killed ring on a live morning is a bypass: a miss on any weekday, the phone rings again, and the PC rings at once until a newer dismiss or 30 min. The PC rings also go to every connected monitor, since the speakers are off at the knob overnight; a one-shot silent probe checks them at A-5. DOCS-bypass.md has the layers, causes and measurements. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
863b94a7d5
commit
cf0d243ffd
@ -16,6 +16,11 @@ temporary escape hatch (until 2026-10-15). All of it, and the data contract
|
||||
the phone, PC and focus-owner share: **`DOCS-wake-enforcement.md`**. Anything
|
||||
else from the old PC alarm still needs a reason the phone can't do it.
|
||||
|
||||
**Bypasses** (the launcher "Pause app" silenced the ring on 11-20 and
|
||||
11-22): focus-owner pins the enforcement apps, WakeAlarm is a device admin,
|
||||
and a pause, admin removal, revoked permission or killed ring that gets
|
||||
through is a miss plus an immediate PC ring: **`DOCS-bypass.md`**.
|
||||
|
||||
## The dismiss sequence (phone)
|
||||
|
||||
```
|
||||
|
||||
105
DOCS-bypass.md
Normal file
105
DOCS-bypass.md
Normal file
@ -0,0 +1,105 @@
|
||||
# Bypasses of the alarm (2026-11-22)
|
||||
|
||||
On 2026-11-20 and 11-22 kuhy long-pressed WakeAlarm on the home screen and
|
||||
tapped "Wstrzymaj aplikację" (Digital Wellbeing's *Pause app*). The pause
|
||||
suspended the app, the ring stopped, and he went back to sleep. This file
|
||||
covers the three layers that now stop that, what counts as a bypass when
|
||||
one gets through anyway, and what a bypass costs.
|
||||
|
||||
## Layer 1: the pause is refused (focus-owner, `~/src/phone-focus-mode`)
|
||||
|
||||
Every focus-owner pass, for the eight enforcement apps in
|
||||
`focus_policy/packages.py` `ENFORCEMENT_PACKAGES` (wake_alarm_sync,
|
||||
workout_app, diet_guard_app, leetcode_guard, book_guard_app, home_guard,
|
||||
daily_limits, habit_stack):
|
||||
|
||||
- `setUserControlDisabledPackages`: Android refuses to suspend them
|
||||
(`Cannot suspend package ...: protected package`), and Settings' Force stop
|
||||
and Clear storage are greyed out. `am force-stop` and `pm clear` are refused
|
||||
too; `adb install -r` still works, so deploys are unaffected.
|
||||
- `setUninstallBlocked`.
|
||||
- `setPermissionGrantState(POST_NOTIFICATIONS, GRANTED)`. The full-screen
|
||||
intent is an app-op and cannot be pinned (`setPermissionGrantState`
|
||||
returns false), so revoking it is a bypass instead (below).
|
||||
- A suspension found anyway is lifted. Measured on the emulator: a pause
|
||||
made before the pins were applied was lifted 4.3 s later, by the pass that
|
||||
wake_alarm's `UNSUSPEND` signal started.
|
||||
|
||||
Digital Wellbeing itself is hidden in every state (`ALWAYS_BLOCKED_PACKAGES`),
|
||||
so the Pause button is gone as well.
|
||||
|
||||
## Layer 2: WakeAlarm is a device admin
|
||||
|
||||
`WakeAdminReceiver` (`res/xml/wake_admin.xml`, no policies). Android refuses
|
||||
to suspend an active admin. It is activated over adb, never by a tap:
|
||||
|
||||
adb shell dpm set-active-admin com.kuhy.wake_alarm_sync/.WakeAdminReceiver
|
||||
|
||||
Deactivating it in Settings cannot be prevented, so it is a bypass.
|
||||
|
||||
## Layer 3: what counts as a bypass (`Bypass.kt`)
|
||||
|
||||
A bypass counts only on a ringing day (an alarm is stored, not a free or sick
|
||||
day, the ring did not stand down) while the ring or the morning session is
|
||||
live. Causes (`bypass` phone event, `data.cause`):
|
||||
|
||||
| cause | seen by |
|
||||
|---|---|
|
||||
| `suspended` | `SuspendReceiver` on `MY_PACKAGE_SUSPENDED`; also sends focus-owner `UNSUSPEND` |
|
||||
| `admin_removed` | `WakeAdminReceiver.onDisabled` |
|
||||
| `notifications_off` | ring start and every launch (`Bypass.checkOnLaunch`) |
|
||||
| `fsi_revoked` | the same; uid app-op `USE_FULL_SCREEN_INTENT` denied |
|
||||
| `ring_killed` | every launch and boot: today's ring fired, was never dismissed, and is not sounding |
|
||||
|
||||
`ring_killed` reads `watched_fired_date`, a stamp only builds with `Bypass`
|
||||
write, so a ring fired by an older build (11-22, paused, never dismissed) does
|
||||
not count the first time the new build starts. The same cause twice within
|
||||
a minute is recorded once (both activities run the launch check).
|
||||
|
||||
## What a bypass costs
|
||||
|
||||
- **A miss** (`StickCheck`), on any weekday, at once, whatever the dismiss
|
||||
does afterwards: a lockdown through the next day, stacking. The streak
|
||||
links penalty days, stick days (Tue–Thu) plus bypass days; free and sick
|
||||
days are skipped. A plain late dismiss on Fri–Mon still changes nothing.
|
||||
- **The phone rings again** (`Bypass.ringAgain`). During a session it is a
|
||||
re-ring: only the full dismiss sequence silences it and `re_rings` goes up
|
||||
by one when it does (`SessionHandoff.afterDismiss`).
|
||||
- **The PC rings** (`_fallback_policy`, reason `bypass`). The phone pushes
|
||||
the event at once through the headless `publishNowMain` engine. The PC
|
||||
rings from the bypass for up to 30 min (`FALLBACK_RING_CAP` from the
|
||||
bypass, not the day's cap), outside the window, after a session started
|
||||
and after the day's own ring was used. It stops on a `dismissed` newer
|
||||
than the bypass, which the phone also pushes at once. Free and sick days
|
||||
and an escape stand it down. The tick reads the phone until `A + 4 h`
|
||||
(`BYPASS_WATCH`); the fallback timer ticks all day.
|
||||
|
||||
## The monitors ring too
|
||||
|
||||
kuhy turns the speakers off at the knob for the night, so the 11-22 fallback
|
||||
ring played 30 min into silence. Both rings now also play to every connected
|
||||
monitor (ELD name in `aplay -l`: `G27Q` on HDMI, `VG28UQL1A` on DP, both on
|
||||
the NVidia card):
|
||||
|
||||
- root path: `ring_alsa.sh` starts one `aplay` loop per monitor, IEC958
|
||||
unmuted;
|
||||
- PipeWire path: `_ring_monitors.MonitorLoops` runs
|
||||
`ring_alsa.sh --monitors` as the user beside `pw-play` (PipeWire does not
|
||||
expose the NVidia outputs).
|
||||
|
||||
Each monitor logs one `ring_sink sink=<name> ... result=ok|error` line.
|
||||
|
||||
**Silent probe.** `ring_alsa.sh --probe` writes two seconds of digital
|
||||
silence to each monitor with IEC958 muted (restored afterwards) and logs one
|
||||
`ring_probe` line per monitor. `_ring_probe.maybe_probe` starts
|
||||
`wake-alarm-ring-probe.service` once, at `A − 5` on the first morning with no
|
||||
graphical session (the state a fallback ring meets), and writes
|
||||
`ring_probe_done`. Read it with `journalctl -u wake-alarm-ring-probe`.
|
||||
vmbox gate: `ring-alsa-monitor-sinks`, `ring-alsa-monitor-probe`
|
||||
(`scripts/vmbox/guest_cases_monitors.sh`).
|
||||
|
||||
## Found on the way: lockdown signals never arrived
|
||||
|
||||
focus-owner defined `SIGNAL_LOCKDOWN` but did not request it, and wake_alarm
|
||||
sends with it as the receiver permission, so every `LOCKDOWN_UNTIL_EOD` and
|
||||
`LIFT_LOCKDOWN` was dropped. focus-owner now holds it (eeb0def).
|
||||
@ -30,6 +30,10 @@ trigger). Not on a free day, not on a sick day (below). Per-minute tick, `A-5min
|
||||
| `now ≥ A + 2 min` and no `ring_started` for today | ring — `phone_silent` |
|
||||
| `now ≥ A + 15 min` (`SESSION_NONE_GRACE`) | ring — `no_session` |
|
||||
|
||||
A **bypass** (the app paused, its admin removed, a permission revoked, the
|
||||
ring killed) rings before this table, outside the window, until a newer
|
||||
dismiss or 30 min: **`DOCS-bypass.md`**.
|
||||
|
||||
A ring stops on: session start, escape, or the 30-min cap. Firebase
|
||||
unreachable counts as "no ping, no session" (fail toward ringing) and is
|
||||
logged as `firebase_unreachable`. While ringing, stop conditions are polled
|
||||
@ -53,6 +57,7 @@ went quiet after 07:43 on 11-01 is a separate phone question.
|
||||
- Otherwise (night lockdown: lightdm masked, nobody logged in; kuhy is not in
|
||||
`audio`) → root system unit `wake-alarm-ring-alsa.service` playing straight
|
||||
to the speakers' card (`ALC897 Analog`, card name `Generic_1`) via `aplay`.
|
||||
- Both paths also ring every connected monitor (2026-11-22, `DOCS-bypass.md`).
|
||||
|
||||
### PC wakes itself (nights before Tue/Wed/Thu)
|
||||
|
||||
@ -132,6 +137,7 @@ shown comes from Dart constants mirrored against the Python ones by
|
||||
- `com.kuhy.focus_owner.action.LOCKDOWN_UNTIL_EOD` — extra `until`
|
||||
(`YYYY-MM-DD`, inclusive). Missing extra = today (old senders keep working).
|
||||
- `com.kuhy.focus_owner.action.LIFT_LOCKDOWN` — clears any lockdown now.
|
||||
- `com.kuhy.focus_owner.action.UNSUSPEND` — run a pass now (lifts a pause).
|
||||
|
||||
### PC files (`~/.local/state/wake_alarm/`)
|
||||
|
||||
@ -148,7 +154,8 @@ Phone (`phone_events.kind`): `alarm_fired` (data: `reason` =
|
||||
`daily`|`rering`|`free_day`|`sick_day` — only `daily` is the morning's ring),
|
||||
`ring_screen_opened`, `ring_started_published` (data: `date`, `source` =
|
||||
`alarm`|`ring_screen`), `dismissed`, `stick_check` (data: `trigger` =
|
||||
`exact`|`boot`|`watchdog`, `date` judged, `verdict`, incl. `free_day`|`sick_day`), `lockdown_sent` (data:
|
||||
`exact`|`boot`|`watchdog`, `date` judged, `verdict`, incl. `free_day`|`sick_day`), `bypass` (data: `cause`, `date`, `session`; `DOCS-bypass.md`),
|
||||
`bypass_ignored`, `unsuspended`, `lockdown_sent` (data:
|
||||
`until`, `streak`), `lift_sent`, `escape_used`, `boot`.
|
||||
|
||||
`ring_started` is published twice over: a headless Dart engine started by
|
||||
|
||||
@ -57,6 +57,8 @@ readonly PC_DIR="$SCRIPT_DIR/scripts/pc"
|
||||
readonly WAV_DIR="/usr/local/share/wake-alarm"
|
||||
readonly RING_SCRIPT_DST="/usr/local/lib/wake-alarm/ring_alsa.sh"
|
||||
readonly ALSA_UNIT="wake-alarm-ring-alsa.service"
|
||||
# The silent monitor check (wake_alarm/_ring_probe.py starts it once).
|
||||
readonly PROBE_UNIT="wake-alarm-ring-probe.service"
|
||||
readonly SUDOERS_FILE="/etc/sudoers.d/wake-alarm"
|
||||
readonly POWERKEY_DST="/etc/systemd/logind.conf.d/wake-alarm-powerkey.conf"
|
||||
INSTALL_USER="$(id -un)"
|
||||
@ -64,6 +66,7 @@ readonly INSTALL_USER
|
||||
readonly SUDOERS_LINES=(
|
||||
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl start $ALSA_UNIT"
|
||||
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl stop $ALSA_UNIT"
|
||||
"$INSTALL_USER ALL=(root) NOPASSWD: /usr/bin/systemctl start $PROBE_UNIT"
|
||||
)
|
||||
|
||||
TEMP_DIR=""
|
||||
@ -84,8 +87,9 @@ install_ring_audio() {
|
||||
sudo install -D -m 0755 "$PC_DIR/ring_alsa.sh" "$RING_SCRIPT_DST"
|
||||
sed "s/@USER@/$INSTALL_USER/" "$PC_DIR/$ALSA_UNIT" >"$TEMP_DIR/$ALSA_UNIT"
|
||||
sudo install -m 0644 "$TEMP_DIR/$ALSA_UNIT" "/etc/systemd/system/$ALSA_UNIT"
|
||||
sudo install -m 0644 "$PC_DIR/$PROBE_UNIT" "/etc/systemd/system/$PROBE_UNIT"
|
||||
sudo systemctl daemon-reload
|
||||
echo " Ring WAVs, $RING_SCRIPT_DST and $ALSA_UNIT installed."
|
||||
echo " Ring WAVs, $RING_SCRIPT_DST, $ALSA_UNIT and $PROBE_UNIT installed."
|
||||
}
|
||||
|
||||
install_sudoers() {
|
||||
@ -102,7 +106,7 @@ install_sudoers() {
|
||||
done
|
||||
sudo visudo -cf "$merged" >/dev/null
|
||||
sudo install -m 0440 -o root -g root "$merged" "$SUDOERS_FILE"
|
||||
echo " $SUDOERS_FILE: rtcwake + start/stop $ALSA_UNIT (validated)."
|
||||
echo " $SUDOERS_FILE: rtcwake, start/stop $ALSA_UNIT, start $PROBE_UNIT (validated)."
|
||||
}
|
||||
|
||||
install_powerkey_dropin() {
|
||||
|
||||
1
phone_app/android/.gitignore
vendored
1
phone_app/android/.gitignore
vendored
@ -12,3 +12,4 @@ GeneratedPluginRegistrant.java
|
||||
key.properties
|
||||
**/*.keystore
|
||||
**/*.jks
|
||||
.kotlin/
|
||||
|
||||
@ -98,6 +98,28 @@
|
||||
<receiver
|
||||
android:name=".SessionWarnReceiver"
|
||||
android:exported="false"/>
|
||||
<!-- An active device admin cannot be paused from the launcher;
|
||||
removing it is a bypass (Bypass.kt). Activated over adb. -->
|
||||
<receiver
|
||||
android:name=".WakeAdminReceiver"
|
||||
android:exported="true"
|
||||
android:permission="android.permission.BIND_DEVICE_ADMIN">
|
||||
<meta-data
|
||||
android:name="android.app.device_admin"
|
||||
android:resource="@xml/wake_admin"/>
|
||||
<intent-filter>
|
||||
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<!-- Sent by the system to this app only; a pause is a bypass. -->
|
||||
<receiver
|
||||
android:name=".SuspendReceiver"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MY_PACKAGE_SUSPENDED"/>
|
||||
<action android:name="android.intent.action.MY_PACKAGE_UNSUSPENDED"/>
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<receiver
|
||||
android:name=".BootReceiver"
|
||||
android:exported="true">
|
||||
|
||||
@ -47,6 +47,8 @@ class AlarmActivity : FlutterActivity() {
|
||||
// an unlock first, every leg.
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
dismissKeyguard()
|
||||
// A revoke or a killed ring, seen on a relaunch into this screen.
|
||||
Bypass.checkOnLaunch(this)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -49,6 +49,9 @@ class AlarmReceiver : BroadcastReceiver() {
|
||||
// After the sound is started, never before: tells the PC the phone
|
||||
// is ringing even when the ring screen never opens.
|
||||
HeadlessRingStart.start(context)
|
||||
// Notifications or the full-screen intent switched off: the ring has
|
||||
// no screen, so the morning counts as bypassed.
|
||||
Bypass.checkPermissions(context)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
@ -29,6 +29,8 @@ class BootReceiver : BroadcastReceiver() {
|
||||
// missed: this is the path that closes that hole (rearmFromStorage
|
||||
// above has already armed the exact check for a phone back earlier).
|
||||
StickRunner.run(context, "boot")
|
||||
// Switched off mid-ring and back on the same day: the ring was killed.
|
||||
Bypass.checkRingKilled(context)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
@ -0,0 +1,132 @@
|
||||
package com.kuhy.wake_alarm_sync
|
||||
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import java.time.LocalDate
|
||||
|
||||
/** How the alarm was got around; [wire] is the `bypass` event's `cause`. */
|
||||
enum class BypassCause(val wire: String) {
|
||||
SUSPENDED("suspended"),
|
||||
ADMIN_REMOVED("admin_removed"),
|
||||
FSI_REVOKED("fsi_revoked"),
|
||||
NOTIFICATIONS_OFF("notifications_off"),
|
||||
RING_KILLED("ring_killed"),
|
||||
}
|
||||
|
||||
/** The bypass rules as pure functions; [Bypass] gathers the inputs. */
|
||||
object BypassRules {
|
||||
/** A bypass counts on a ringing day while the ring or the morning session is live. */
|
||||
fun counts(ringingDay: Boolean, ringLive: Boolean, sessionLive: Boolean): Boolean =
|
||||
ringingDay && (ringLive || sessionLive)
|
||||
|
||||
/** The same cause recorded less than [windowMs] ago. */
|
||||
fun isRepeat(last: Pair<String, Long>?, cause: String, now: Long, windowMs: Long): Boolean =
|
||||
last != null && last.first == cause && now - last.second in 0 until windowMs
|
||||
|
||||
/** Today's ring fired, was never dismissed, and nothing is ringing now. */
|
||||
fun ringKilled(firedToday: Boolean, dismissedToday: Boolean, ringing: Boolean): Boolean =
|
||||
firedToday && !dismissedToday && !ringing
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a bypass of the alarm: the app paused from the launcher
|
||||
* ("Wstrzymaj aplikację", 2026-11-20 and 11-22), its device admin removed,
|
||||
* notifications or the full-screen intent switched off, or the ring killed.
|
||||
*
|
||||
* A bypass is a miss on any ringing day ([StickCheck]), so it locks the phone
|
||||
* down through the next day and stacks the streak. It is published at once
|
||||
* (the `bypass` phone event), so the PC rings until a fresh dismiss, and the
|
||||
* phone rings again: the morning goes on as if the bypass never happened,
|
||||
* one re-ring richer when a session was live.
|
||||
*/
|
||||
object Bypass {
|
||||
private const val TAG = "WakeAlarmBypass"
|
||||
private const val RING_CHANNEL_ID = "wake_alarm_ring"
|
||||
|
||||
// One launch runs the checks from MainActivity and then AlarmActivity
|
||||
// (emulator, 2026-11-22: two events, two publishes for one revoke).
|
||||
private const val REPEAT_WINDOW_MS = 60_000L
|
||||
private var lastRecorded: Pair<String, Long>? = null
|
||||
|
||||
/** Records [cause] if it counts today; returns whether it did. */
|
||||
@Synchronized
|
||||
fun record(context: Context, cause: BypassCause): Boolean {
|
||||
val today = LocalDate.now()
|
||||
val ringLive = RingWatch.firedToday(context) && !RingWatch.dismissedOn(context, today)
|
||||
val sessionLive = SessionNotice.isLiveToday(context)
|
||||
if (!BypassRules.counts(ringingDay(context, today), ringLive, sessionLive)) {
|
||||
Log.i(TAG, "${cause.wire}: no ring or session live; not a bypass")
|
||||
EventLog.append(context, "bypass_ignored", mapOf("cause" to cause.wire))
|
||||
return false
|
||||
}
|
||||
val now = System.currentTimeMillis()
|
||||
if (BypassRules.isRepeat(lastRecorded, cause.wire, now, REPEAT_WINDOW_MS)) {
|
||||
Log.i(TAG, "bypass: ${cause.wire} again within a minute; already recorded")
|
||||
return true
|
||||
}
|
||||
lastRecorded = cause.wire to now
|
||||
Log.w(TAG, "bypass: ${cause.wire}")
|
||||
RingWatch.markBypass(context, today)
|
||||
EventLog.append(
|
||||
context,
|
||||
"bypass",
|
||||
mapOf("cause" to cause.wire, "date" to today.toString(), "session" to sessionLive),
|
||||
)
|
||||
if (cause == BypassCause.SUSPENDED) WorkdayStick.sendUnsuspend(context)
|
||||
StickRunner.run(context, "bypass")
|
||||
ringAgain(context)
|
||||
HeadlessRingStart.start(context, HeadlessRingStart.PUBLISH_ENTRYPOINT)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Every launch, from either activity: the launcher restores whichever
|
||||
* one was on top (the ring or the session screen), so checking only in
|
||||
* MainActivity missed a revoke made mid-morning (emulator, 2026-11-22).
|
||||
*/
|
||||
fun checkOnLaunch(context: Context) {
|
||||
checkRingKilled(context)
|
||||
checkPermissions(context)
|
||||
}
|
||||
|
||||
/** Checks the permissions the ring needs; a revoked one on a live morning is a bypass. */
|
||||
fun checkPermissions(context: Context) {
|
||||
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
val channel = manager.getNotificationChannel(RING_CHANNEL_ID)
|
||||
val blocked = channel != null && channel.importance == NotificationManager.IMPORTANCE_NONE
|
||||
if (!manager.areNotificationsEnabled() || blocked) {
|
||||
record(context, BypassCause.NOTIFICATIONS_OFF)
|
||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&
|
||||
!manager.canUseFullScreenIntent()
|
||||
) {
|
||||
record(context, BypassCause.FSI_REVOKED)
|
||||
}
|
||||
}
|
||||
|
||||
/** On a launch or boot: today's ring fired, undismissed, and is not ringing. */
|
||||
fun checkRingKilled(context: Context) {
|
||||
val killed = BypassRules.ringKilled(
|
||||
firedToday = RingWatch.firedToday(context),
|
||||
dismissedToday = RingWatch.dismissedOn(context, LocalDate.now()),
|
||||
ringing = AlarmService.running,
|
||||
)
|
||||
if (killed) record(context, BypassCause.RING_KILLED)
|
||||
}
|
||||
|
||||
/** Starts the ring again; a refused start (still suspended) waits for the unsuspend. */
|
||||
fun ringAgain(context: Context) {
|
||||
try {
|
||||
AlarmService.start(context)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "ring not restarted yet: $e")
|
||||
}
|
||||
}
|
||||
|
||||
private fun ringingDay(context: Context, day: LocalDate): Boolean =
|
||||
AlarmScheduler.storedAlarm(context) != null &&
|
||||
!FreeDays.isFree(context, day) &&
|
||||
!SickDays.isSick(context, day) &&
|
||||
RingWatch.skippedOn(context, day) == null
|
||||
}
|
||||
@ -0,0 +1,51 @@
|
||||
package com.kuhy.wake_alarm_sync
|
||||
|
||||
import android.app.admin.DeviceAdminReceiver
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import java.time.LocalDate
|
||||
|
||||
/**
|
||||
* The app's own device admin. An active admin cannot be paused
|
||||
* ("Wstrzymaj aplikację"): Android refuses to suspend it. Deactivating it is
|
||||
* possible in Settings and no one can stop that, so it is a bypass instead.
|
||||
* Activated over adb (`dpm set-active-admin`), never by a tap.
|
||||
*/
|
||||
class WakeAdminReceiver : DeviceAdminReceiver() {
|
||||
override fun onDisabled(context: Context, intent: Intent) {
|
||||
Bypass.record(context, BypassCause.ADMIN_REMOVED)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `MY_PACKAGE_SUSPENDED` / `UNSUSPENDED`, sent by the system to this app
|
||||
* itself. Suspended: record the bypass and ask focus-owner to lift it.
|
||||
* Unsuspended: when today's bypass is live, ring again (the start may have
|
||||
* been refused while suspended).
|
||||
*/
|
||||
class SuspendReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
Intent.ACTION_MY_PACKAGE_SUSPENDED -> {
|
||||
Log.w(TAG, "suspended")
|
||||
Bypass.record(context, BypassCause.SUSPENDED)
|
||||
}
|
||||
Intent.ACTION_MY_PACKAGE_UNSUSPENDED -> {
|
||||
Log.i(TAG, "unsuspended")
|
||||
EventLog.append(context, "unsuspended")
|
||||
if (RingWatch.bypassOn(context, LocalDate.now())) {
|
||||
if (!AlarmService.running) Bypass.ringAgain(context)
|
||||
// Again now the app runs normally: the push made while
|
||||
// suspended may not have gone out.
|
||||
HeadlessRingStart.start(context, HeadlessRingStart.PUBLISH_ENTRYPOINT)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "WakeAlarmSuspend"
|
||||
}
|
||||
}
|
||||
@ -52,12 +52,14 @@ object EnforcementChannel {
|
||||
val isFree = { day: LocalDate -> FreeDays.isFree(context, day) }
|
||||
val isSick = { day: LocalDate -> SickDays.isSick(context, day) }
|
||||
val standsDown = { day: LocalDate -> isFree(day) || isSick(day) }
|
||||
val bypassOn = { day: LocalDate -> RingWatch.bypassOn(context, day) }
|
||||
return mapOf(
|
||||
"today" to today.toString(),
|
||||
"alarmHour" to alarm?.hour,
|
||||
"alarmMinute" to alarm?.minute,
|
||||
"dismissedToday" to RingWatch.dismissedOn(context, today),
|
||||
"escapedToday" to StickStore.escapedOn(context, today),
|
||||
"bypassToday" to RingWatch.bypassOn(context, today),
|
||||
"freeToday" to isFree(today),
|
||||
"freeTomorrow" to isFree(tomorrow),
|
||||
"sickToday" to isSick(today),
|
||||
@ -67,9 +69,9 @@ object EnforcementChannel {
|
||||
"lastMiss" to stick.lastMiss?.toString(),
|
||||
"updatedAt" to StickStore.updatedAt(context),
|
||||
"lockIfMissToday" to
|
||||
StickCheck.afterMiss(today, stick, standsDown).lockedThrough?.toString(),
|
||||
StickCheck.afterMiss(today, stick, standsDown, bypassOn).lockedThrough?.toString(),
|
||||
"lockIfMissTomorrow" to
|
||||
StickCheck.afterMiss(tomorrow, stick, standsDown).lockedThrough?.toString(),
|
||||
StickCheck.afterMiss(tomorrow, stick, standsDown, bypassOn).lockedThrough?.toString(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -30,15 +30,25 @@ object HeadlessRingStart {
|
||||
private const val TAG = "WakeAlarmHeadless"
|
||||
const val CHANNEL = "com.kuhy.wake_alarm_sync/headless"
|
||||
private const val ENTRYPOINT = "ringStartedMain"
|
||||
|
||||
/** Publishes the enforcement fields now (a bypass); `publishNowMain` in `main.dart`. */
|
||||
const val PUBLISH_ENTRYPOINT = "publishNowMain"
|
||||
private const val TIMEOUT_MS = 90_000L
|
||||
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var engine: FlutterEngine? = null
|
||||
|
||||
/** Starts the engine unless one is already running. Main thread only. */
|
||||
fun start(context: Context) {
|
||||
/** A publish asked for while an engine ran; started when that one stops. */
|
||||
private var pending: Pair<Context, String>? = null
|
||||
|
||||
/**
|
||||
* Starts the engine running [entrypoint] unless one is already running,
|
||||
* in which case a publish is queued behind it. Main thread only.
|
||||
*/
|
||||
fun start(context: Context, entrypoint: String = ENTRYPOINT) {
|
||||
if (engine != null) {
|
||||
Log.w(TAG, "headless ring_started engine already running; start ignored")
|
||||
if (entrypoint == PUBLISH_ENTRYPOINT) pending = context.applicationContext to entrypoint
|
||||
Log.w(TAG, "headless engine already running; $entrypoint ${if (pending != null) "queued" else "ignored"}")
|
||||
return
|
||||
}
|
||||
try {
|
||||
@ -55,7 +65,7 @@ object HeadlessRingStart {
|
||||
}
|
||||
val bundle = FlutterInjector.instance().flutterLoader().findAppBundlePath()
|
||||
created.dartExecutor.executeDartEntrypoint(
|
||||
DartExecutor.DartEntrypoint(bundle, ENTRYPOINT),
|
||||
DartExecutor.DartEntrypoint(bundle, entrypoint),
|
||||
)
|
||||
handler.postDelayed({ stop("timeout") }, TIMEOUT_MS)
|
||||
Log.i(TAG, "headless ring_started engine started")
|
||||
@ -70,5 +80,9 @@ object HeadlessRingStart {
|
||||
engine?.destroy()
|
||||
engine = null
|
||||
Log.i(TAG, "headless engine stopped: $reason")
|
||||
pending?.let { (context, entrypoint) ->
|
||||
pending = null
|
||||
handler.post { start(context, entrypoint) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -20,6 +20,9 @@ class MainActivity : FlutterActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
// A ring that fired, went undismissed and is not sounding was killed
|
||||
// (force stop, a pause that got through): a bypass, which rings again.
|
||||
Bypass.checkOnLaunch(this)
|
||||
if (resumeMorning()) return
|
||||
requestAlarmPermissions()
|
||||
}
|
||||
|
||||
@ -33,9 +33,18 @@ object RingWatch {
|
||||
private const val KEY_DISMISSED_DATE = "dismissed_date"
|
||||
private const val KEY_DISMISSED_DATES = "dismissed_dates"
|
||||
private const val KEY_SKIPPED_PREFIX = "skipped_dates_"
|
||||
private const val KEY_BYPASS_DATES = "bypass_dates"
|
||||
|
||||
// Written only by builds that have [Bypass], next to KEY_FIRED_DATE. A
|
||||
// ring fired by an older build (11-22: paused, never dismissed) must not
|
||||
// read as a killed ring the first time the new build launches.
|
||||
private const val KEY_WATCHED_FIRED_DATE = "watched_fired_date"
|
||||
|
||||
fun markFired(context: Context) {
|
||||
prefs(context).edit().putString(KEY_FIRED_DATE, today()).apply()
|
||||
prefs(context).edit()
|
||||
.putString(KEY_FIRED_DATE, today())
|
||||
.putString(KEY_WATCHED_FIRED_DATE, today())
|
||||
.apply()
|
||||
}
|
||||
|
||||
fun markDismissed(context: Context) {
|
||||
@ -52,6 +61,19 @@ object RingWatch {
|
||||
DateHistory.add(prefs(context), KEY_SKIPPED_PREFIX + skip.wire, LocalDate.now())
|
||||
}
|
||||
|
||||
/** Whether today's fresh ring fired under a build with [Bypass]; [Bypass] asks it. */
|
||||
fun firedToday(context: Context): Boolean =
|
||||
prefs(context).getString(KEY_WATCHED_FIRED_DATE, null) == today()
|
||||
|
||||
/** Latches a bypass ([Bypass]) on [day]; the stick reads it as a miss. */
|
||||
fun markBypass(context: Context, day: LocalDate) {
|
||||
DateHistory.add(prefs(context), KEY_BYPASS_DATES, day)
|
||||
}
|
||||
|
||||
/** Whether a bypass was recorded on [day]. */
|
||||
fun bypassOn(context: Context, day: LocalDate): Boolean =
|
||||
DateHistory.contains(prefs(context), KEY_BYPASS_DATES, day)
|
||||
|
||||
/** Why the ring stood down on [day], or null when it was not skipped. */
|
||||
fun skippedOn(context: Context, day: LocalDate): RingSkip? =
|
||||
RingSkip.entries.firstOrNull {
|
||||
|
||||
@ -46,6 +46,12 @@ data class StickInputs(
|
||||
* (2026-11-11).
|
||||
*/
|
||||
val ringSkippedOn: (LocalDate) -> RingSkip? = { null },
|
||||
/**
|
||||
* Whether a bypass ([Bypass]) was recorded on a day: the app paused,
|
||||
* its admin removed, a permission revoked, the ring killed. A miss on
|
||||
* any ringing day, stick day or not (2026-11-22).
|
||||
*/
|
||||
val bypassOn: (LocalDate) -> Boolean = { false },
|
||||
)
|
||||
|
||||
/** One day's verdict within a run. */
|
||||
@ -67,6 +73,9 @@ data class StickRun(
|
||||
* The stick's decision, as pure functions -- no Context, no clock, no I/O,
|
||||
* so every rule here is checkable in isolation.
|
||||
*
|
||||
* A **bypass** ([StickInputs.bypassOn]) is a miss on any day that is neither
|
||||
* free nor sick, at once and whatever the dismiss did afterwards.
|
||||
*
|
||||
* A **miss** is a stick day (Tue/Wed/Thu, [WorkdayStick.STICK_DAYS]) that is
|
||||
* neither a free day nor a sick day (now, or when its ring stood down), whose alarm passed by at least [Stakes.STICK_GRACE_MINUTES]
|
||||
* with no dismiss and no escape, and that has not already been penalised.
|
||||
@ -124,7 +133,7 @@ object StickCheck {
|
||||
state: StickState,
|
||||
): Pair<StickVerdict, StickState> {
|
||||
val alarm = inputs.alarm ?: return StickVerdict.NO_ALARM to state
|
||||
if (!isStickDay(day)) return StickVerdict.NOT_STICK_DAY to state
|
||||
if (!isStickDay(day) && !inputs.bypassOn(day)) return StickVerdict.NOT_STICK_DAY to state
|
||||
if (inputs.isFree(day)) return StickVerdict.FREE_DAY to state
|
||||
// A sick day stands the stick down like a free day: no miss, no
|
||||
// streak change, no lockdown -- and nothing carried to tomorrow.
|
||||
@ -138,10 +147,14 @@ object StickCheck {
|
||||
// shown and synced drops to 0 (a lockdown already sent stays).
|
||||
if (inputs.escapedOn(day)) return StickVerdict.ESCAPED to state.copy(streak = 0)
|
||||
if (state.lastMiss == day) return StickVerdict.ALREADY_PENALISED to state
|
||||
// A bypass is a miss at once, and a later dismiss does not undo it.
|
||||
if (inputs.bypassOn(day)) {
|
||||
return StickVerdict.MISS to afterMiss(day, state, inputs.standsDown, inputs.bypassOn)
|
||||
}
|
||||
if (inputs.dismissedOn(day)) return StickVerdict.DISMISSED to state.copy(streak = 0)
|
||||
val due = day.atTime(alarm).plusMinutes(Stakes.STICK_GRACE_MINUTES)
|
||||
if (now.isBefore(due)) return StickVerdict.TOO_EARLY to state
|
||||
return StickVerdict.MISS to afterMiss(day, state, inputs.standsDown)
|
||||
return StickVerdict.MISS to afterMiss(day, state, inputs.standsDown, inputs.bypassOn)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -151,20 +164,31 @@ object StickCheck {
|
||||
* lockdown already in force: a chain restarting at 1 must not report
|
||||
* an earlier end than the one focus-owner was already sent.
|
||||
*/
|
||||
fun afterMiss(day: LocalDate, state: StickState, standsDown: (LocalDate) -> Boolean): StickState {
|
||||
val streak = streakAfterMiss(day, state, standsDown)
|
||||
fun afterMiss(
|
||||
day: LocalDate,
|
||||
state: StickState,
|
||||
standsDown: (LocalDate) -> Boolean,
|
||||
bypassOn: (LocalDate) -> Boolean = { false },
|
||||
): StickState {
|
||||
val streak = streakAfterMiss(day, state, standsDown, bypassOn)
|
||||
val computed = lockedThrough(day, streak)
|
||||
val locked = state.lockedThrough?.let { maxOf(it, computed) } ?: computed
|
||||
return StickState(streak = streak, lockedThrough = locked, lastMiss = day)
|
||||
}
|
||||
|
||||
/**
|
||||
* Consecutive stick-day misses including one on [day]: the chain
|
||||
* continues only when the previous stick day (free and sick days
|
||||
* skipped, per [standsDown]) is exactly the last miss.
|
||||
* Consecutive misses including one on [day]: the chain continues only
|
||||
* when the previous penalty day -- a stick day, or any day with a
|
||||
* bypass; free and sick days skipped, per [standsDown] -- is exactly
|
||||
* the last miss.
|
||||
*/
|
||||
fun streakAfterMiss(day: LocalDate, state: StickState, standsDown: (LocalDate) -> Boolean): Int {
|
||||
val previous = previousStickDay(day, standsDown)
|
||||
fun streakAfterMiss(
|
||||
day: LocalDate,
|
||||
state: StickState,
|
||||
standsDown: (LocalDate) -> Boolean,
|
||||
bypassOn: (LocalDate) -> Boolean = { false },
|
||||
): Int {
|
||||
val previous = previousStickDay(day, standsDown, bypassOn)
|
||||
return if (previous != null && previous == state.lastMiss) state.streak + 1 else 1
|
||||
}
|
||||
|
||||
@ -172,12 +196,16 @@ object StickCheck {
|
||||
fun lockedThrough(day: LocalDate, streak: Int): LocalDate =
|
||||
day.plusDays(minOf(streak, Stakes.STICK_LOCKDOWN_MAX_DAYS - 1).toLong())
|
||||
|
||||
/** The nearest earlier stick day that does not [standsDown], or null. */
|
||||
fun previousStickDay(day: LocalDate, standsDown: (LocalDate) -> Boolean): LocalDate? {
|
||||
/** The nearest earlier penalty day (stick or bypass) that does not [standsDown], or null. */
|
||||
fun previousStickDay(
|
||||
day: LocalDate,
|
||||
standsDown: (LocalDate) -> Boolean,
|
||||
bypassOn: (LocalDate) -> Boolean = { false },
|
||||
): LocalDate? {
|
||||
var step = day.minusDays(1)
|
||||
val floor = day.minusDays(LOOKBACK_DAYS)
|
||||
while (step.isAfter(floor)) {
|
||||
if (isStickDay(step) && !standsDown(step)) return step
|
||||
if ((isStickDay(step) || bypassOn(step)) && !standsDown(step)) return step
|
||||
step = step.minusDays(1)
|
||||
}
|
||||
return null
|
||||
|
||||
@ -36,6 +36,7 @@ object StickRunner {
|
||||
state = before,
|
||||
checkedThrough = StickStore.checkedThrough(context),
|
||||
ringSkippedOn = { RingWatch.skippedOn(context, it) },
|
||||
bypassOn = { RingWatch.bypassOn(context, it) },
|
||||
),
|
||||
)
|
||||
for ((day, verdict) in run.verdicts) {
|
||||
|
||||
@ -23,6 +23,7 @@ object WorkdayStick {
|
||||
|
||||
private const val ACTION_LOCKDOWN = "com.kuhy.focus_owner.action.LOCKDOWN_UNTIL_EOD"
|
||||
private const val ACTION_LIFT = "com.kuhy.focus_owner.action.LIFT_LOCKDOWN"
|
||||
private const val ACTION_UNSUSPEND = "com.kuhy.focus_owner.action.UNSUSPEND"
|
||||
private const val EXTRA_UNTIL = "until"
|
||||
private const val PERMISSION_SIGNAL = "com.kuhy.focus_owner.permission.SIGNAL_LOCKDOWN"
|
||||
private const val FOCUS_OWNER_PACKAGE = "com.kuhy.focus_owner"
|
||||
@ -48,4 +49,13 @@ object WorkdayStick {
|
||||
PERMISSION_SIGNAL,
|
||||
)
|
||||
}
|
||||
|
||||
/** Asks focus-owner for a pass now, which lifts a suspension of this app. */
|
||||
fun sendUnsuspend(context: Context) {
|
||||
Log.i(TAG, "signalling focus-owner unsuspend")
|
||||
context.sendBroadcast(
|
||||
Intent(ACTION_UNSUSPEND).setPackage(FOCUS_OWNER_PACKAGE),
|
||||
PERMISSION_SIGNAL,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
5
phone_app/android/app/src/main/res/xml/wake_admin.xml
Normal file
5
phone_app/android/app/src/main/res/xml/wake_admin.xml
Normal file
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- No policies: the admin exists only so Android refuses to pause the app. -->
|
||||
<device-admin>
|
||||
<uses-policies />
|
||||
</device-admin>
|
||||
@ -0,0 +1,127 @@
|
||||
package com.kuhy.wake_alarm_sync
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.LocalTime
|
||||
|
||||
/**
|
||||
* A bypass (the app paused, its admin removed, a permission revoked, the
|
||||
* ring killed) is a miss on any ringing day, 2026-11-22.
|
||||
*/
|
||||
class StickCheckBypassTest {
|
||||
// 2026-11-20 is a Friday, 22 a Sunday, 24 a Tuesday.
|
||||
private val fri = LocalDate.of(2026, 11, 20)
|
||||
private val sun = LocalDate.of(2026, 11, 22)
|
||||
private val mon = sun.plusDays(1)
|
||||
private val tue = sun.plusDays(2)
|
||||
|
||||
private fun inputs(
|
||||
now: LocalDateTime,
|
||||
bypass: Set<LocalDate> = emptySet(),
|
||||
dismissed: Set<LocalDate> = emptySet(),
|
||||
free: Set<LocalDate> = emptySet(),
|
||||
sick: Set<LocalDate> = emptySet(),
|
||||
state: StickState = StickState(),
|
||||
checkedThrough: LocalDate? = null,
|
||||
) = StickInputs(
|
||||
now = now,
|
||||
alarm = LocalTime.of(7, 30),
|
||||
dismissedOn = { it in dismissed },
|
||||
escapedOn = { false },
|
||||
isFree = { it in free },
|
||||
isSick = { it in sick },
|
||||
state = state,
|
||||
checkedThrough = checkedThrough,
|
||||
bypassOn = { it in bypass },
|
||||
)
|
||||
|
||||
@Test
|
||||
fun aSundayBypassIsAMissLockingThroughMonday() {
|
||||
val run = StickCheck.run(inputs(sun.atTime(7, 40), bypass = setOf(sun)))
|
||||
assertEquals(StickVerdict.MISS, run.verdicts.single().verdict)
|
||||
assertEquals(StickState(streak = 1, lockedThrough = mon, lastMiss = sun), run.state)
|
||||
assertEquals(mon, run.signalUntil)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aBypassCountsEvenBeforeTheGraceAndAfterADismiss() {
|
||||
val run = StickCheck.run(
|
||||
inputs(tue.atTime(7, 35), bypass = setOf(tue), dismissed = setOf(tue)),
|
||||
)
|
||||
assertEquals(StickVerdict.MISS, run.verdicts.single().verdict)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTuesdayMissAfterASundayBypassStacks() {
|
||||
val afterSunday = StickState(streak = 1, lockedThrough = mon, lastMiss = sun)
|
||||
val run = StickCheck.run(
|
||||
inputs(
|
||||
tue.atTime(9, 0),
|
||||
bypass = setOf(sun),
|
||||
state = afterSunday,
|
||||
checkedThrough = mon,
|
||||
),
|
||||
)
|
||||
assertEquals(StickVerdict.MISS, run.verdicts.last().verdict)
|
||||
assertEquals(2, run.state.streak)
|
||||
assertEquals(tue.plusDays(2), run.state.lockedThrough)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLateFridayWithNoBypassChangesNothing() {
|
||||
val run = StickCheck.run(inputs(fri.atTime(11, 0)))
|
||||
assertEquals(StickVerdict.NOT_STICK_DAY, run.verdicts.single().verdict)
|
||||
assertEquals(StickState(), run.state)
|
||||
assertNull(run.signalUntil)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun freeAndSickDaysStayNeutralEvenWithABypass() {
|
||||
val free = StickCheck.run(inputs(sun.atTime(8, 0), bypass = setOf(sun), free = setOf(sun)))
|
||||
assertEquals(StickVerdict.FREE_DAY, free.verdicts.single().verdict)
|
||||
val sick = StickCheck.run(inputs(tue.atTime(8, 0), bypass = setOf(tue), sick = setOf(tue)))
|
||||
assertEquals(StickVerdict.SICK_DAY, sick.verdicts.single().verdict)
|
||||
assertEquals(StickState(), sick.state)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSecondBypassTheSameDayIsAlreadyPenalised() {
|
||||
val afterSunday = StickState(streak = 1, lockedThrough = mon, lastMiss = sun)
|
||||
val run = StickCheck.run(
|
||||
inputs(sun.atTime(8, 0), bypass = setOf(sun), state = afterSunday, checkedThrough = sun),
|
||||
)
|
||||
assertEquals(StickVerdict.ALREADY_PENALISED, run.verdicts.single().verdict)
|
||||
assertNull(run.signalUntil)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aBypassCountsOnlyOnARingingDayWithARingOrSessionLive() {
|
||||
assertTrue(BypassRules.counts(ringingDay = true, ringLive = true, sessionLive = false))
|
||||
assertTrue(BypassRules.counts(ringingDay = true, ringLive = false, sessionLive = true))
|
||||
assertFalse(BypassRules.counts(ringingDay = true, ringLive = false, sessionLive = false))
|
||||
assertFalse(BypassRules.counts(ringingDay = false, ringLive = true, sessionLive = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRingIsKilledWhenItFiredUndismissedAndNothingRings() {
|
||||
assertTrue(BypassRules.ringKilled(firedToday = true, dismissedToday = false, ringing = false))
|
||||
assertFalse(BypassRules.ringKilled(firedToday = true, dismissedToday = false, ringing = true))
|
||||
assertFalse(BypassRules.ringKilled(firedToday = true, dismissedToday = true, ringing = false))
|
||||
assertFalse(BypassRules.ringKilled(firedToday = false, dismissedToday = false, ringing = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theSameCauseWithinAMinuteIsARepeat() {
|
||||
val last = "fsi_revoked" to 1_000L
|
||||
assertFalse(BypassRules.isRepeat(null, "fsi_revoked", 1_000L, 60_000L))
|
||||
assertTrue(BypassRules.isRepeat(last, "fsi_revoked", 60_999L, 60_000L))
|
||||
assertFalse(BypassRules.isRepeat(last, "fsi_revoked", 61_000L, 60_000L))
|
||||
assertFalse(BypassRules.isRepeat(last, "suspended", 2_000L, 60_000L))
|
||||
assertFalse(BypassRules.isRepeat(last, "fsi_revoked", 999L, 60_000L))
|
||||
}
|
||||
}
|
||||
@ -60,7 +60,7 @@ class StickCheckSickTest {
|
||||
fun aSickDayIsSkippedWhenTheStreakLooksBack() {
|
||||
// Missed Tuesday, sick Wednesday: Thursday's miss continues the chain.
|
||||
val before = StickState(streak = 1, lockedThrough = wed, lastMiss = tue)
|
||||
val after = StickCheck.afterMiss(thu, before) { it == wed }
|
||||
val after = StickCheck.afterMiss(thu, before, standsDown = { it == wed })
|
||||
assertEquals(2, after.streak)
|
||||
}
|
||||
|
||||
|
||||
@ -11,6 +11,7 @@ import 'package:wake_alarm_sync/screens/session_screen.dart';
|
||||
import 'package:wake_alarm_sync/services/alarm_policy.dart';
|
||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||
import 'package:wake_alarm_sync/services/day_pool_refresh.dart';
|
||||
import 'package:wake_alarm_sync/services/enforcement_publish.dart';
|
||||
import 'package:wake_alarm_sync/services/headless_ring_start.dart';
|
||||
import 'package:wake_alarm_sync/ui/app_name.dart';
|
||||
import 'package:wake_alarm_sync/ui/theme.dart';
|
||||
@ -45,6 +46,10 @@ Future<void> main() async {
|
||||
@pragma('vm:entry-point')
|
||||
Future<void> ringStartedMain() => runHeadlessRingStart();
|
||||
|
||||
/// Headless entry point: `Bypass.kt` starts it to push a bypass at once.
|
||||
@pragma('vm:entry-point')
|
||||
Future<void> publishNowMain() => runHeadlessPublish();
|
||||
|
||||
/// Headless entry point: `PoolSyncReceiver.kt` starts it in the evening and
|
||||
/// shortly before the alarm, so a free or sick day marked on the PC reaches
|
||||
/// the native ring-path caches with the app closed.
|
||||
|
||||
64
phone_app/lib/services/enforcement_publish.dart
Normal file
64
phone_app/lib/services/enforcement_publish.dart
Normal file
@ -0,0 +1,64 @@
|
||||
/// Pushes the enforcement fields now, not at the next sync.
|
||||
///
|
||||
/// Two moments need it (2026-11-22): a bypass (the app paused, its admin
|
||||
/// removed, a permission revoked, the ring killed), which the native side
|
||||
/// records and then starts `publishNowMain` for, and a completed dismiss.
|
||||
/// The PC rings for a bypass until it reads a `dismissed` newer than it, so
|
||||
/// both have to reach Firebase within a poll, not minutes later.
|
||||
library;
|
||||
|
||||
import 'dart:developer' as developer;
|
||||
import 'dart:ui' show DartPluginRegistrant;
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
||||
import 'package:wake_alarm_sync/services/enforcement_sync.dart';
|
||||
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
||||
import 'package:wake_alarm_sync/services/headless_ring_start.dart';
|
||||
import 'package:wake_alarm_sync/services/sync_settings.dart';
|
||||
|
||||
/// Stages the enforcement fields (the event log included) and pushes.
|
||||
///
|
||||
/// Returns whether the push reached a backend. Never throws: the caller is
|
||||
/// a ring or a dismiss, and neither may wait on a broken network.
|
||||
Future<bool> publishEnforcementNow({
|
||||
Future<AlarmSyncService> Function()? open,
|
||||
Future<void> Function(AlarmSyncService service, String token)? push,
|
||||
}) async {
|
||||
try {
|
||||
final settings = await SyncSettings.load();
|
||||
final hasFirebase = await loadAccount() != null;
|
||||
if (!settings.isConfigured && !hasFirebase) {
|
||||
debugPrint('WakeAlarmPublish: no sync backend');
|
||||
return false;
|
||||
}
|
||||
final service = await (open ?? AlarmSyncService.open)();
|
||||
await stageEnforcementData(service);
|
||||
await (push ?? ((s, token) => s.push(token)))(service, settings.token);
|
||||
debugPrint('WakeAlarmPublish: pushed');
|
||||
return true;
|
||||
} on Object catch (e) {
|
||||
debugPrint('WakeAlarmPublish: not pushed: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// The `publishNowMain` engine's whole job: publish, then say done.
|
||||
Future<void> runHeadlessPublish({
|
||||
Future<bool> Function()? publish,
|
||||
MethodChannel? channel,
|
||||
}) async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
DartPluginRegistrant.ensureInitialized();
|
||||
try {
|
||||
await (publish ?? publishEnforcementNow)();
|
||||
} finally {
|
||||
try {
|
||||
await (channel ?? const MethodChannel(headlessChannelName))
|
||||
.invokeMethod<void>('done');
|
||||
} on Object catch (e) {
|
||||
developer.log('headless done not delivered: $e', name: 'WakeAlarmRing');
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,7 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
||||
import 'package:wake_alarm_sync/services/enforcement_publish.dart';
|
||||
import 'package:wake_alarm_sync/services/morning_session.dart';
|
||||
import 'package:wake_alarm_sync/services/session_rules.dart';
|
||||
import 'package:wake_alarm_sync/services/session_store.dart';
|
||||
@ -16,8 +19,10 @@ class SessionHandoff {
|
||||
required this.scheduler,
|
||||
SessionStore? store,
|
||||
DateTime Function()? now,
|
||||
Future<bool> Function()? publishNow,
|
||||
}) : store = store ?? SessionStore(),
|
||||
_now = now ?? DateTime.now;
|
||||
_now = now ?? DateTime.now,
|
||||
_publishNow = publishNow ?? publishEnforcementNow;
|
||||
|
||||
/// Platform bridge, for the NFC availability check.
|
||||
final AlarmScheduler scheduler;
|
||||
@ -27,6 +32,10 @@ class SessionHandoff {
|
||||
|
||||
final DateTime Function() _now;
|
||||
|
||||
/// Pushes the `dismissed` event at once: the PC rings for a bypass until
|
||||
/// it reads one newer than the bypass.
|
||||
final Future<bool> Function() _publishNow;
|
||||
|
||||
/// Starts or resumes today's session; false when the ring should just end.
|
||||
///
|
||||
/// [away] is the ring's verdict that the phone is not at home: no scale,
|
||||
@ -38,6 +47,8 @@ class SessionHandoff {
|
||||
// recorded before anything else so an interrupted await below still
|
||||
// leaves the native side knowing the ring was answered.
|
||||
await scheduler.markRingDismissed();
|
||||
// Not awaited: the session must not wait on the network.
|
||||
unawaited(_publishNow());
|
||||
final now = _now();
|
||||
final today = SessionRules.dateKey(now);
|
||||
final current = await store.loadCurrent();
|
||||
|
||||
67
phone_app/test/services/enforcement_publish_test.dart
Normal file
67
phone_app/test/services/enforcement_publish_test.dart
Normal file
@ -0,0 +1,67 @@
|
||||
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/enforcement_publish.dart';
|
||||
import 'package:wake_alarm_sync/services/headless_ring_start.dart';
|
||||
import 'package:wake_alarm_sync/services/session_handoff.dart';
|
||||
|
||||
/// A bypass and a dismiss reach the PC at once, not at the next sync
|
||||
/// (2026-11-22): the PC rings for a bypass until it sees a newer dismiss.
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late List<String> calls;
|
||||
|
||||
setUp(() {
|
||||
calls = <String>[];
|
||||
SharedPreferences.setMockInitialValues(<String, Object>{});
|
||||
for (final name in [headlessChannelName, AlarmScheduler.channelName]) {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(MethodChannel(name), (call) async {
|
||||
calls.add(call.method);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('the headless publish pushes once, then says done', () async {
|
||||
var published = 0;
|
||||
await runHeadlessPublish(
|
||||
publish: () async {
|
||||
published++;
|
||||
return true;
|
||||
},
|
||||
);
|
||||
expect(published, 1);
|
||||
expect(calls, ['done']);
|
||||
});
|
||||
|
||||
test('done is sent even when the publish blows up', () async {
|
||||
await expectLater(
|
||||
runHeadlessPublish(publish: () async => throw StateError('boom')),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(calls, ['done']);
|
||||
});
|
||||
|
||||
test('with no sync backend nothing is pushed', () async {
|
||||
expect(await publishEnforcementNow(), isFalse);
|
||||
});
|
||||
|
||||
test('a dismiss publishes at once, after telling native', () async {
|
||||
final order = <String>[];
|
||||
final handoff = SessionHandoff(
|
||||
scheduler: AlarmScheduler(),
|
||||
now: () => DateTime(2026, 11, 22, 7, 40),
|
||||
publishNow: () async {
|
||||
order
|
||||
..addAll(calls)
|
||||
..add('publish');
|
||||
return true;
|
||||
},
|
||||
);
|
||||
await handoff.afterDismiss(away: true);
|
||||
expect(order, ['markRingDismissed', 'publish']);
|
||||
});
|
||||
}
|
||||
@ -17,7 +17,19 @@
|
||||
# non-zero. Needs WAKE_ALARM_USER (set by the unit; install.sh fills it in)
|
||||
# and psmisc's fuser.
|
||||
#
|
||||
# Usage: ring_alsa.sh <rise.wav> <loop.wav>
|
||||
# The monitors ring too (2026-11-22): kuhy switches the speakers off at the
|
||||
# knob for the night, so the 07:51 ring of 11-22 played 30 min into silence.
|
||||
# Every HDMI/DP output whose ELD names a connected monitor gets its own
|
||||
# aplay loop, IEC958 unmuted; each output logs one `ring_sink` line.
|
||||
#
|
||||
# --probe proves the monitors without a sound: two seconds of digital
|
||||
# silence to each, IEC958 muted, one `ring_probe` line per sink, exit 1 when
|
||||
# any fails or none is connected (wake-alarm-ring-probe.service).
|
||||
#
|
||||
# --monitors <rise> <loop> rings only the monitors, until SIGTERM: the
|
||||
# PipeWire path runs it as the user beside pw-play (wake_alarm/_ring_monitors).
|
||||
#
|
||||
# Usage: ring_alsa.sh <rise.wav> <loop.wav> | --monitors <rise> <loop> | --probe
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
@ -35,9 +47,15 @@ readonly RING_USER="${WAKE_ALARM_USER:-}"
|
||||
readonly PY="${WAKE_ALARM_PYTHON:-/usr/bin/python3}"
|
||||
# A failed aplay (device briefly held elsewhere) must not spin the CPU.
|
||||
readonly RETRY_SECONDS=1
|
||||
# How long a monitor's aplay must survive to count as opened.
|
||||
readonly OPEN_CHECK_SECONDS=1
|
||||
# The monitors as card:dev:name:hdmi-index lines; unset = read `aplay -l`.
|
||||
# Set (even empty) only by the vmbox gate.
|
||||
MONITORS_OVERRIDE="${WAKE_ALARM_MONITORS-__unset__}"
|
||||
readonly MONITORS_OVERRIDE
|
||||
|
||||
usage() {
|
||||
echo "Usage: $(basename "$0") <rise.wav> <loop.wav>" >&2
|
||||
echo "Usage: $(basename "$0") <rise.wav> <loop.wav> | --monitors <rise> <loop> | --probe" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
@ -70,6 +88,88 @@ play() {
|
||||
sleep "$RETRY_SECONDS"
|
||||
}
|
||||
|
||||
# One line per connected monitor: card:dev:name:hdmi-index. `aplay -l` names
|
||||
# an HDMI/DP device after its ELD ("HDMI 0 [G27Q]"); an empty port keeps
|
||||
# "HDMI n [HDMI n]".
|
||||
monitor_sinks() {
|
||||
if [[ "$MONITORS_OVERRIDE" != "__unset__" ]]; then
|
||||
tr ' ' '\n' <<<"$MONITORS_OVERRIDE" | grep -v '^$' || true
|
||||
return
|
||||
fi
|
||||
aplay -l 2>/dev/null |
|
||||
sed -nE 's/^card [0-9]+: ([^ ]+) \[[^]]*\], device ([0-9]+): HDMI ([0-9]+) \[(.+)\]$/\1:\2:\4:\3/p' |
|
||||
grep -vE ':HDMI [0-9]+:[0-9]+$' || true
|
||||
}
|
||||
|
||||
# One sink's ring: the rise, a `ring_sink` line saying whether it opened,
|
||||
# then the loop until SIGTERM. The rise lasts a minute, so "opened" means
|
||||
# aplay is still playing after OPEN_CHECK_SECONDS. A sink that cannot open
|
||||
# logs and gives up, so one dead monitor never stops the others.
|
||||
ring_sink() {
|
||||
local card="$1" dev="$2" name="$3" rise="$4" loop="$5" device err pid rc=0
|
||||
device="plughw:CARD=${card},DEV=${dev}"
|
||||
err="$(mktemp)"
|
||||
aplay -q -D "$device" "$rise" 2>"$err" &
|
||||
pid=$!
|
||||
sleep "$OPEN_CHECK_SECONDS"
|
||||
if ! kill -0 "$pid" 2>/dev/null; then
|
||||
wait "$pid" || rc=$?
|
||||
fi
|
||||
if [[ $rc -ne 0 ]]; then
|
||||
echo "ring_sink sink=$name device=$card,$dev result=error $(tr '\n' ' ' <"$err")"
|
||||
rm -f "$err"
|
||||
return 1
|
||||
fi
|
||||
echo "ring_sink sink=$name device=$card,$dev result=ok"
|
||||
rm -f "$err"
|
||||
wait "$pid" 2>/dev/null || true
|
||||
while true; do
|
||||
aplay -q -D "$device" "$loop" 2>/dev/null || sleep "$RETRY_SECONDS"
|
||||
done
|
||||
}
|
||||
|
||||
# Every monitor in the background, IEC958 unmuted first.
|
||||
start_monitors() {
|
||||
local rise="$1" loop="$2" card dev name index
|
||||
while IFS=: read -r card dev name index; do
|
||||
[[ -n "$card" ]] || continue
|
||||
amixer -q -c "$card" sset "IEC958,${index}" unmute >/dev/null 2>&1 || true
|
||||
ring_sink "$card" "$dev" "$name" "$rise" "$loop" &
|
||||
done < <(monitor_sinks)
|
||||
}
|
||||
|
||||
# Silence into every monitor; 0 only when each opened and took >= 1.5 s.
|
||||
# IEC958 is muted for the check and put back the way it was found.
|
||||
probe() {
|
||||
local card dev name index start ms rc err was failed=0 found=0
|
||||
while IFS=: read -r card dev name index; do
|
||||
[[ -n "$card" ]] || continue
|
||||
found=1
|
||||
was=unmute
|
||||
if amixer -c "$card" sget "IEC958,${index}" 2>/dev/null | grep -q '\[off\]'; then
|
||||
was=mute
|
||||
fi
|
||||
amixer -q -c "$card" sset "IEC958,${index}" mute >/dev/null 2>&1 || true
|
||||
start="$(date +%s%N)"
|
||||
rc=0
|
||||
err="$(aplay -q -D "plughw:CARD=${card},DEV=${dev}" -t raw -f S16_LE -r 48000 \
|
||||
-c 2 -d 2 /dev/zero 2>&1)" || rc=$?
|
||||
ms=$((($(date +%s%N) - start) / 1000000))
|
||||
amixer -q -c "$card" sset "IEC958,${index}" "$was" >/dev/null 2>&1 || true
|
||||
if [[ $rc -eq 0 && $ms -ge 1500 ]]; then
|
||||
echo "ring_probe sink=$name device=$card,$dev result=ok ms=$ms"
|
||||
else
|
||||
echo "ring_probe sink=$name device=$card,$dev result=error rc=$rc ms=$ms ${err//$'\n'/ }"
|
||||
failed=1
|
||||
fi
|
||||
done < <(monitor_sinks)
|
||||
if [[ $found -eq 0 ]]; then
|
||||
echo "ring_probe result=error no connected monitor"
|
||||
return 1
|
||||
fi
|
||||
return "$failed"
|
||||
}
|
||||
|
||||
# Ring through the user's PipeWire until systemd's SIGTERM; non-zero if it
|
||||
# cannot play (the fallback itself reports ring_backend FAILED).
|
||||
user_fallback() {
|
||||
@ -109,16 +209,32 @@ handle_busy() {
|
||||
}
|
||||
|
||||
main() {
|
||||
if [[ "${1:-}" == "--probe" ]]; then
|
||||
probe
|
||||
return
|
||||
fi
|
||||
if [[ "${1:-}" == "--monitors" ]]; then
|
||||
[[ $# -eq 3 ]] || usage
|
||||
# SIGTERM from the PipeWire path: end every loop, then exit.
|
||||
trap 'kill $(jobs -p) 2>/dev/null || true; exit 0' TERM INT
|
||||
start_monitors "$2" "$3"
|
||||
wait
|
||||
return
|
||||
fi
|
||||
[[ $# -eq 2 ]] || usage
|
||||
local rise="$1" loop="$2"
|
||||
[[ -r "$rise" && -r "$loop" ]] || {
|
||||
echo "Error: cannot read $rise / $loop" >&2
|
||||
exit 1
|
||||
}
|
||||
# The monitor loops die with this script, whatever ends it.
|
||||
trap 'kill $(jobs -p) 2>/dev/null || true' EXIT
|
||||
start_monitors "$rise" "$loop"
|
||||
unmute_all
|
||||
local rc=0
|
||||
play "$rise" || rc=$?
|
||||
[[ $rc -ne 3 ]] || handle_busy "$rise" "$loop"
|
||||
[[ $rc -ne 0 ]] || echo "ring_sink sink=speakers device=$CARD,0 result=ok"
|
||||
while true; do
|
||||
play "$loop" || sleep "$RETRY_SECONDS"
|
||||
done
|
||||
|
||||
13
scripts/pc/wake-alarm-ring-probe.service
Normal file
13
scripts/pc/wake-alarm-ring-probe.service
Normal file
@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Wake Alarm silent check that the monitors can ring (ALSA, root)
|
||||
Documentation=https://github.com/kuhyx/wake-alarm
|
||||
|
||||
[Service]
|
||||
# Started once by the user's wake-alarm-fallback.service at A - 5 on a
|
||||
# morning with no graphical session (the state the fallback rings in),
|
||||
# through `sudo -n systemctl start` (see /etc/sudoers.d/wake-alarm).
|
||||
# Plays digital silence only: `journalctl -u wake-alarm-ring-probe` shows
|
||||
# one ring_probe line per monitor.
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/lib/wake-alarm/ring_alsa.sh --probe
|
||||
TimeoutStartSec=60
|
||||
48
scripts/vmbox/guest_cases_monitors.sh
Executable file
48
scripts/vmbox/guest_cases_monitors.sh
Executable file
@ -0,0 +1,48 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================================
|
||||
# wake_alarm vmbox harness — the monitors ring too (2026-11-22). Two fake
|
||||
# monitors on snd-dummy's extra PCM devices (WAKE_ALARM_MONITORS stands in
|
||||
# for the ELD names `aplay -l` reads on the PC): each must log its own
|
||||
# `ring_sink ... result=ok`, a dead one must log an error without stopping
|
||||
# the others, and --probe must pass on silence. Sourced by guest_cases_v2.sh.
|
||||
# ============================================================================
|
||||
|
||||
# snd-dummy with three PCM devices: 0 = speakers, 1 and 2 = the monitors.
|
||||
monitors_card() {
|
||||
sudo modprobe -r snd-dummy >/dev/null 2>&1 || true
|
||||
sudo modprobe snd-dummy pcm_devs=3
|
||||
sudo udevadm settle
|
||||
}
|
||||
|
||||
case_ring_monitor_sinks() {
|
||||
local name="ring-alsa-monitor-sinks" out
|
||||
monitors_card
|
||||
out="$(sudo WAKE_ALARM_CARD=Dummy WAKE_ALARM_USER="$USER" \
|
||||
WAKE_ALARM_MONITORS="Dummy:1:MonA:0 Dummy:2:MonB:1 Nope:0:Dead:2" \
|
||||
timeout 5 "$RING_SCRIPT" "$RING_WAV_DIR/ring.wav" "$RING_WAV_DIR/ring_loop.wav" 2>&1)" || true
|
||||
if grep -q "ring_sink sink=MonA device=Dummy,1 result=ok" <<<"$out" &&
|
||||
grep -q "ring_sink sink=MonB device=Dummy,2 result=ok" <<<"$out" &&
|
||||
grep -q "ring_sink sink=Dead device=Nope,0 result=error" <<<"$out"; then
|
||||
pass "$name"
|
||||
else
|
||||
fail "$name" "ring_sink lines: $(grep ring_sink <<<"$out" | tr '\n' '|')"
|
||||
fi
|
||||
}
|
||||
|
||||
case_ring_monitor_probe() {
|
||||
local name="ring-alsa-monitor-probe" out rc=0
|
||||
monitors_card
|
||||
out="$(sudo WAKE_ALARM_MONITORS="Dummy:1:MonA:0 Dummy:2:MonB:1" \
|
||||
"$RING_SCRIPT" --probe 2>&1)" || rc=$?
|
||||
if [[ $rc -eq 0 ]] && [[ "$(grep -c 'ring_probe .*result=ok' <<<"$out")" -eq 2 ]]; then
|
||||
pass "$name"
|
||||
else
|
||||
fail "$name" "rc=$rc: $(tr '\n' '|' <<<"$out")"
|
||||
fi
|
||||
}
|
||||
|
||||
run_monitor_cases() {
|
||||
case_ring_monitor_sinks
|
||||
case_ring_monitor_probe
|
||||
}
|
||||
@ -18,6 +18,8 @@ readonly WAKEALARM=/sys/class/rtc/rtc0/wakealarm
|
||||
# (~/wake-alarm, or ~/wt from a worktree), so derive it, never hard-code it.
|
||||
GUEST_REPO="$(readlink -f "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../..")"
|
||||
readonly GUEST_REPO
|
||||
# shellcheck source=guest_cases_monitors.sh source-path=SCRIPTDIR
|
||||
source "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/guest_cases_monitors.sh"
|
||||
|
||||
# A timer present but disabled fails silently every morning.
|
||||
case_v2_timers() {
|
||||
@ -236,6 +238,7 @@ run_v2_cases() {
|
||||
case_ring_script_plays
|
||||
case_ring_busy_fallback
|
||||
case_ring_busy_fails_loudly
|
||||
run_monitor_cases
|
||||
case_sudoers
|
||||
case_powerkey_dropin
|
||||
case_rtc_arm
|
||||
|
||||
@ -24,8 +24,10 @@ readonly SYSTEMD_USER_DIR="$HOME/.config/systemd/user"
|
||||
# Enforcement v2 (DOCS-wake-enforcement.md): user units, then root pieces.
|
||||
readonly V2_UNITS=(wake-alarm-fallback wake-alarm-rtc wake-alarm-audit)
|
||||
readonly ALSA_UNIT="wake-alarm-ring-alsa.service"
|
||||
readonly PROBE_UNIT="wake-alarm-ring-probe.service"
|
||||
readonly ROOT_FILES=(
|
||||
"/etc/systemd/system/$ALSA_UNIT"
|
||||
"/etc/systemd/system/$PROBE_UNIT"
|
||||
"/usr/local/lib/wake-alarm/ring_alsa.sh"
|
||||
"/usr/local/share/wake-alarm/ring.wav"
|
||||
"/usr/local/share/wake-alarm/ring_loop.wav"
|
||||
@ -105,7 +107,7 @@ remove_enforcement() {
|
||||
done
|
||||
echo " Fallback, RTC and audit timers removed"
|
||||
|
||||
sudo systemctl stop "$ALSA_UNIT" >/dev/null 2>&1 || true
|
||||
sudo systemctl stop "$ALSA_UNIT" "$PROBE_UNIT" >/dev/null 2>&1 || true
|
||||
for path in "${ROOT_FILES[@]}"; do
|
||||
sudo rm -f "$path"
|
||||
done
|
||||
|
||||
@ -5,7 +5,8 @@ Documentation=https://github.com/kuhyx/wake-alarm
|
||||
[Timer]
|
||||
# 04:00-09:59 covers A-5min..A+45min for any alarm the phone can set (A is
|
||||
# clamped to <= 08:00). Outside that window a tick reads only local files.
|
||||
OnCalendar=*-*-* 04..09:*:00
|
||||
# Through 11:59: a phone bypass rings the PC up to A + 4 h (A <= 08:00).
|
||||
OnCalendar=*-*-* 04..11:*:00
|
||||
AccuracySec=1s
|
||||
# Catch up at once after the RTC resume or a boot.
|
||||
Persistent=true
|
||||
|
||||
@ -35,6 +35,7 @@ from wake_alarm._enforcement_records import (
|
||||
RingStarted,
|
||||
StickState,
|
||||
escape_from,
|
||||
parse_instant,
|
||||
phone_event_from,
|
||||
ring_started_from,
|
||||
stick_state_from,
|
||||
@ -42,6 +43,7 @@ from wake_alarm._enforcement_records import (
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
@ -69,6 +71,29 @@ class EnforcementView:
|
||||
"""The first honoured escape excusing ``day``, or None."""
|
||||
return next((e for e in self.honoured_escapes() if e.date == day), None)
|
||||
|
||||
def bypass_on(self, day: str) -> datetime | None:
|
||||
"""The newest ``bypass`` of ``day``, unless a ``dismissed`` came after it.
|
||||
|
||||
The PC rings for a bypass until the phone proves the full dismiss
|
||||
sequence again, which logs ``dismissed``.
|
||||
"""
|
||||
bypasses = [
|
||||
at
|
||||
for event in self.phone_events
|
||||
if event.kind == "bypass" and event.data.get("date") == day
|
||||
if (at := parse_instant(event.at)) is not None
|
||||
]
|
||||
if not bypasses:
|
||||
return None
|
||||
newest = max(bypasses)
|
||||
dismissed = any(
|
||||
event.kind == "dismissed"
|
||||
and (at := parse_instant(event.at)) is not None
|
||||
and at > newest
|
||||
for event in self.phone_events
|
||||
)
|
||||
return None if dismissed else newest
|
||||
|
||||
def escaped_dates(self) -> frozenset[str]:
|
||||
"""Every morning an honoured escape excuses."""
|
||||
return frozenset(e.date for e in self.honoured_escapes())
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
"""The PC fallback alarm: one per-minute tick, 04:00-09:59.
|
||||
"""The PC fallback alarm: one per-minute tick, 04:00-11:59.
|
||||
|
||||
``wake-alarm-fallback.timer`` runs ``--tick`` every minute. Outside
|
||||
``A - 5 min .. A + 45 min`` (or on a free or sick day) a tick decides from local
|
||||
@ -35,14 +35,17 @@ from wake_alarm._fallback_observe import (
|
||||
settled_reason,
|
||||
)
|
||||
from wake_alarm._fallback_policy import (
|
||||
BYPASS,
|
||||
Decision,
|
||||
Facts,
|
||||
alarm_instant,
|
||||
bypass_stop_reason,
|
||||
decide,
|
||||
stop_reason,
|
||||
)
|
||||
from wake_alarm._fallback_ring import ring
|
||||
from wake_alarm._logging_setup import configure_logging
|
||||
from wake_alarm._ring_probe import maybe_probe
|
||||
from wake_alarm._ring_wav import SYSTEM_WAV_DIR, USER_WAV_DIR, ensure_pair
|
||||
from wake_alarm._sick import alarm_stands_down
|
||||
from wake_alarm._sync import get_alarm
|
||||
@ -80,6 +83,41 @@ def _poll(day: str) -> str | None:
|
||||
return reason
|
||||
|
||||
|
||||
def _poll_bypass(bypass_at: datetime | None) -> str | None:
|
||||
"""Re-observe while ringing for a bypass; the reason to stop, or None.
|
||||
|
||||
An unreachable Firebase keeps the bypass it started with: fail toward
|
||||
ringing, never toward silence.
|
||||
"""
|
||||
seen = observe(_now(), sync=True)
|
||||
record(seen)
|
||||
facts = seen.facts if seen.reachable else replace(seen.facts, bypass_at=bypass_at)
|
||||
return bypass_stop_reason(facts)
|
||||
|
||||
|
||||
def ring_bypass(facts: Facts) -> str:
|
||||
"""Ring for a bypass until it is cleared or capped; returns the stop reason.
|
||||
|
||||
Never touches the daily latch: a bypass has its own 30 minutes, measured
|
||||
from the phone's event, whatever the day's own ring already used.
|
||||
"""
|
||||
bypass_at = facts.bypass_at
|
||||
emit(
|
||||
"fallback_ring_start",
|
||||
BYPASS,
|
||||
reason=BYPASS,
|
||||
bypass_at=bypass_at.isoformat() if bypass_at else None,
|
||||
alarm=facts.alarm_at.isoformat(),
|
||||
)
|
||||
stopped = TERMINATED
|
||||
try:
|
||||
rise, loop = ensure_pair(SYSTEM_WAV_DIR, USER_WAV_DIR)
|
||||
stopped = ring(lambda: _poll_bypass(bypass_at), rise=rise, loop=loop)
|
||||
finally:
|
||||
emit("fallback_ring_stop", stopped, stop_reason=stopped, reason=BYPASS)
|
||||
return stopped
|
||||
|
||||
|
||||
def ring_now(facts: Facts, reason: str) -> str:
|
||||
"""Latch, ring until a stop condition, unlatch; returns the stop reason."""
|
||||
day = facts.now.date().isoformat()
|
||||
@ -109,6 +147,8 @@ def tick(now: datetime) -> Decision:
|
||||
seen = observe(now, sync=True)
|
||||
record(seen)
|
||||
facts, day = seen.facts, now.date().isoformat()
|
||||
# Before any ring can start: the probe needs the monitors free.
|
||||
maybe_probe(now, facts.alarm_at)
|
||||
decision = decide(facts)
|
||||
emit_on_change(
|
||||
"fallback_tick",
|
||||
@ -121,7 +161,9 @@ def tick(now: datetime) -> Decision:
|
||||
)
|
||||
remember_final(day, decision.reason)
|
||||
latch = facts.latch
|
||||
if decision.ring:
|
||||
if decision.ring and decision.reason == BYPASS:
|
||||
ring_bypass(facts)
|
||||
elif decision.ring:
|
||||
ring_now(facts, decision.reason)
|
||||
elif latch is not None and latch.started_at and not latch.stopped_at:
|
||||
_close(latch, decision.reason)
|
||||
@ -138,7 +180,8 @@ def describe(seen: Observation, decision: Decision) -> str:
|
||||
f"sick_day={facts.sick_day} "
|
||||
f"firebase={'ok' if seen.reachable else 'UNREACHABLE'}\n"
|
||||
f" escaped={facts.escaped} session_started={facts.session_started} "
|
||||
f"ring_started={facts.ring_started} settled={facts.settled}\n"
|
||||
f"ring_started={facts.ring_started} settled={facts.settled} "
|
||||
f"bypass_at={facts.bypass_at}\n"
|
||||
f" latch={facts.latch}\n"
|
||||
)
|
||||
|
||||
|
||||
@ -93,6 +93,7 @@ def observe(now: datetime, *, sync: bool) -> Observation:
|
||||
escaped=view.escape_for(day) is not None,
|
||||
session_started=session is not None and session.date == day,
|
||||
ring_started=view.ring_started_on(day),
|
||||
bypass_at=view.bypass_on(day),
|
||||
),
|
||||
view=view,
|
||||
)
|
||||
|
||||
@ -10,6 +10,12 @@ ring already ran 30 min today (``FALLBACK_RING_CAP``) never again today
|
||||
``now >= A + 15 min`` (``SESSION_NONE_GRACE``) ring: no_session
|
||||
========================================================= ==================
|
||||
|
||||
A **bypass** comes before the table (2026-11-22): a ``bypass`` phone event
|
||||
today (the app paused, its admin removed, a permission revoked, the ring
|
||||
killed) with no newer ``dismissed`` rings ``bypass`` for 30 minutes from the
|
||||
event, ignoring the window, a started session, a final reason and the
|
||||
day's own cap. Only a free or sick day, or an escape, stands it down.
|
||||
|
||||
The window gates *starting* a ring only. A ring that already started today
|
||||
and has not hit its cap is judged by the table alone, so a ringing process
|
||||
killed by a hibernate resumes after the resume instead of going quiet
|
||||
@ -53,6 +59,13 @@ CAP = "cap"
|
||||
PHONE_SILENT = "phone_silent"
|
||||
NO_SESSION = "no_session"
|
||||
WAITING = "waiting"
|
||||
BYPASS = "bypass"
|
||||
BYPASS_CLEARED = "bypass_cleared"
|
||||
|
||||
# How long after A the tick keeps reading the phone for a bypass. The morning
|
||||
# session's last cutoff is 11:00 and A is never later than 08:00 (07:00 at
|
||||
# the end of the ramp), so A + 4 h covers every live ring and session.
|
||||
BYPASS_WATCH: timedelta = timedelta(hours=4)
|
||||
|
||||
# Once seen, these hold for the rest of the day even if Firebase later stops
|
||||
# answering: an unreachable backend fails toward ringing, but never toward
|
||||
@ -76,6 +89,8 @@ class Facts:
|
||||
ring_started: bool = False
|
||||
latch: Latch | None = None
|
||||
settled: str | None = None
|
||||
# The newest bypass today not followed by a dismiss; None = none live.
|
||||
bypass_at: datetime | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@ -101,17 +116,25 @@ def _ring_started_today(latch: Latch | None) -> bool:
|
||||
return latch is not None and latch.started() is not None
|
||||
|
||||
|
||||
def needs_facts(now: datetime, alarm_at: datetime, latch: Latch | None) -> bool:
|
||||
"""Whether this tick must fetch the phone's state at all.
|
||||
|
||||
Outside the window with nothing rung today the answer is already
|
||||
``outside_window``, so the per-minute tick stays off the network.
|
||||
"""
|
||||
def in_window(now: datetime, alarm_at: datetime, latch: Latch | None) -> bool:
|
||||
"""Whether the table's rows may start (or resume) a ring now."""
|
||||
if _ring_started_today(latch):
|
||||
return True
|
||||
return alarm_at - FALLBACK_WINDOW_START <= now < alarm_at + FALLBACK_WINDOW_END
|
||||
|
||||
|
||||
def needs_facts(now: datetime, alarm_at: datetime, latch: Latch | None) -> bool:
|
||||
"""Whether this tick must fetch the phone's state at all.
|
||||
|
||||
The window, or the bypass watch after it (``BYPASS_WATCH``). Outside
|
||||
both the answer is already ``outside_window``, so the per-minute tick
|
||||
stays off the network.
|
||||
"""
|
||||
if in_window(now, alarm_at, latch):
|
||||
return True
|
||||
return alarm_at - FALLBACK_WINDOW_START <= now < alarm_at + BYPASS_WATCH
|
||||
|
||||
|
||||
def is_capped(facts: Facts) -> bool:
|
||||
"""Whether today's ring has used its 30 minutes."""
|
||||
latch = facts.latch
|
||||
@ -154,12 +177,33 @@ def stop_reason(facts: Facts) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def bypass_stop_reason(facts: Facts) -> str | None:
|
||||
"""Why a bypass ring must stop now, or None while the bypass stands."""
|
||||
off = day_off(facts)
|
||||
if off is not None:
|
||||
return off
|
||||
if facts.escaped:
|
||||
return ESCAPE
|
||||
if facts.bypass_at is None:
|
||||
return BYPASS_CLEARED
|
||||
if facts.now >= facts.bypass_at + FALLBACK_RING_CAP:
|
||||
return CAP
|
||||
return None
|
||||
|
||||
|
||||
def decide(facts: Facts) -> Decision:
|
||||
"""The table above; first match wins."""
|
||||
"""A live bypass first, then the table above; first match wins."""
|
||||
off = day_off(facts)
|
||||
if off is not None:
|
||||
return Decision(ring=False, reason=off)
|
||||
if not needs_facts(facts.now, facts.alarm_at, facts.latch):
|
||||
if facts.bypass_at is not None and bypass_stop_reason(facts) is None:
|
||||
return Decision(ring=True, reason=BYPASS)
|
||||
return _decide_table(facts)
|
||||
|
||||
|
||||
def _decide_table(facts: Facts) -> Decision:
|
||||
"""The table's rows, on a day that is neither off nor bypassed."""
|
||||
if not in_window(facts.now, facts.alarm_at, facts.latch):
|
||||
return Decision(ring=False, reason=OUTSIDE_WINDOW)
|
||||
stop = stop_reason(facts)
|
||||
if stop is not None:
|
||||
|
||||
59
wake_alarm/_ring_monitors.py
Normal file
59
wake_alarm/_ring_monitors.py
Normal file
@ -0,0 +1,59 @@
|
||||
"""The monitors' share of a PipeWire ring.
|
||||
|
||||
The night's speakers are switched off at the knob (2026-11-22), so a ring
|
||||
must reach the two monitors too. PipeWire does not expose them (the NVidia
|
||||
card's profile is off), but the active session's ACL lets this user open
|
||||
their ALSA devices, so ``ring_alsa.sh --monitors`` plays to each one
|
||||
directly, logging one ``ring_sink`` line per monitor to this unit's journal.
|
||||
The script runs in its own session so :meth:`MonitorLoops.stop` can end
|
||||
every ``aplay`` it started at once.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Where install.sh puts scripts/pc/ring_alsa.sh.
|
||||
RING_SCRIPT = Path("/usr/local/lib/wake-alarm/ring_alsa.sh")
|
||||
|
||||
|
||||
def _spawn(cmd: list[str]) -> subprocess.Popen[bytes]:
|
||||
"""Start ``cmd`` as its own process group; the seam tests replace."""
|
||||
return subprocess.Popen(cmd, start_new_session=True)
|
||||
|
||||
|
||||
class MonitorLoops:
|
||||
"""One ``ring_alsa.sh --monitors`` process group."""
|
||||
|
||||
def __init__(self, proc: subprocess.Popen[bytes]) -> None:
|
||||
"""Wrap a started group."""
|
||||
self._proc: subprocess.Popen[bytes] | None = proc
|
||||
|
||||
@classmethod
|
||||
def start(cls, rise: Path, loop: Path) -> MonitorLoops | None:
|
||||
"""Start the loops; None (logged) when they cannot start.
|
||||
|
||||
Never fatal: the speakers' ring must not depend on the monitors.
|
||||
"""
|
||||
try:
|
||||
proc = _spawn([str(RING_SCRIPT), "--monitors", str(rise), str(loop)])
|
||||
except OSError as exc:
|
||||
_logger.warning("Monitor ring not started: %s", exc)
|
||||
return None
|
||||
return cls(proc)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""SIGTERM the whole group. Safe to call twice."""
|
||||
proc, self._proc = self._proc, None
|
||||
if proc is None or proc.poll() is not None:
|
||||
return
|
||||
try:
|
||||
os.killpg(proc.pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
return
|
||||
@ -4,7 +4,8 @@ Two backends, chosen per ring by :func:`select_backend`:
|
||||
|
||||
* **PipeWire** -- an active graphical session on seat0 belongs to this user,
|
||||
so its PipeWire is reachable: unmute and max the default sink with
|
||||
``wpctl`` and play with ``pw-play``.
|
||||
``wpctl`` and play with ``pw-play``; the monitors ring beside it
|
||||
(:mod:`wake_alarm._ring_monitors`).
|
||||
* **ALSA unit** -- anything else (the night lockdown: lightdm masked, nobody
|
||||
logged in, and the user is not in ``audio``): start the root system unit
|
||||
``wake-alarm-ring-alsa.service`` through its NOPASSWD sudoers entry. The
|
||||
@ -21,6 +22,8 @@ import os
|
||||
import subprocess
|
||||
from typing import TYPE_CHECKING, Protocol
|
||||
|
||||
from wake_alarm._ring_monitors import MonitorLoops
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
@ -111,6 +114,7 @@ class PipeWireBackend:
|
||||
"""Play ``rise`` once, then ``loop`` forever."""
|
||||
self._rise, self._loop = rise, loop
|
||||
self._proc: subprocess.Popen[bytes] | None = None
|
||||
self._monitors: MonitorLoops | None = None
|
||||
|
||||
def _play(self, path: Path) -> None:
|
||||
"""Start ``pw-play`` on ``path`` at full stream volume."""
|
||||
@ -129,6 +133,7 @@ class PipeWireBackend:
|
||||
self._play(self._rise)
|
||||
except OSError as exc:
|
||||
return False, f"pw-play failed: {exc}"
|
||||
self._monitors = MonitorLoops.start(self._rise, self._loop)
|
||||
return True, "pw-play started"
|
||||
|
||||
def pump(self) -> bool:
|
||||
@ -148,7 +153,10 @@ class PipeWireBackend:
|
||||
return True
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Terminate the current ``pw-play``."""
|
||||
"""Terminate the current ``pw-play`` and the monitor loops."""
|
||||
monitors, self._monitors = self._monitors, None
|
||||
if monitors is not None:
|
||||
monitors.stop()
|
||||
proc, self._proc = self._proc, None
|
||||
if proc is None or proc.poll() is not None:
|
||||
return
|
||||
|
||||
44
wake_alarm/_ring_probe.py
Normal file
44
wake_alarm/_ring_probe.py
Normal file
@ -0,0 +1,44 @@
|
||||
"""The silent monitor probe: once, at A - 5, on a morning with no session.
|
||||
|
||||
On 2026-11-22 the fallback rang 30 minutes into the analog speakers, which
|
||||
kuhy switches off at the knob for the night, so nothing was heard. The ring
|
||||
now plays to every connected monitor too (``scripts/pc/ring_alsa.sh``).
|
||||
Whether a monitor really takes the stream with no graphical session can be
|
||||
known only in that state, and kuhy asked for no test sound, so this starts
|
||||
``wake-alarm-ring-probe.service`` once: digital silence into each monitor,
|
||||
one ``ring_probe`` journal line per sink. The first real fallback morning's
|
||||
``ring_sink`` lines are the follow-up check.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from wake_alarm._constants import LOG_STATE_DIR
|
||||
from wake_alarm._events import emit
|
||||
from wake_alarm._ring_player import _ok, graphical_session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import datetime
|
||||
|
||||
PROBE_UNIT = "wake-alarm-ring-probe.service"
|
||||
PROBE_DONE_FILE = LOG_STATE_DIR / "ring_probe_done"
|
||||
PROBE_LEAD = timedelta(minutes=5)
|
||||
|
||||
|
||||
def maybe_probe(now: datetime, alarm_at: datetime) -> str | None:
|
||||
"""Start the probe if it is due; what happened, or None when not due."""
|
||||
if PROBE_DONE_FILE.exists() or not alarm_at - PROBE_LEAD <= now < alarm_at:
|
||||
return None
|
||||
graphical, why = graphical_session()
|
||||
if graphical:
|
||||
# Not the state a fallback ring meets; try again tomorrow.
|
||||
return "waiting_for_no_session"
|
||||
started, out = _ok(["sudo", "-n", "systemctl", "start", PROBE_UNIT])
|
||||
emit("ring_probe", "started" if started else "failed", session=why, output=out)
|
||||
if not started:
|
||||
return "failed"
|
||||
PROBE_DONE_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
PROBE_DONE_FILE.write_text(now.isoformat(), encoding="utf-8")
|
||||
return "started"
|
||||
@ -52,6 +52,13 @@ def _no_process(cmd: list[str]) -> object:
|
||||
raise AssertionError(msg)
|
||||
|
||||
|
||||
def _probe_done(tmp_path: Path) -> Path:
|
||||
"""An already-run probe, so a tick at A - 5 never reaches loginctl."""
|
||||
path = tmp_path / "ring_probe_done"
|
||||
path.write_text("test", encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
class FakeClock:
|
||||
"""A monotonic clock that only moves when ``sleep`` is called.
|
||||
|
||||
@ -166,6 +173,10 @@ def _hermetic(tmp_path: Path) -> Generator[None]:
|
||||
tmp_path / "morning_session.json",
|
||||
),
|
||||
patch("wake_alarm._session_strip._popen", _no_process),
|
||||
# The silent monitor probe sudo-starts a root unit: never from a test
|
||||
# unless that test patches its own done file and process seam.
|
||||
patch("wake_alarm._ring_probe._ok", _no_process),
|
||||
patch("wake_alarm._ring_probe.PROBE_DONE_FILE", _probe_done(tmp_path)),
|
||||
patch("wake_alarm._session_strip._once", _session_strip._Once()),
|
||||
patch(
|
||||
"wake_alarm._workday_penalty.WORKDAY_PENALTY_FILE",
|
||||
@ -199,6 +210,7 @@ def _hermetic(tmp_path: Path) -> Generator[None]:
|
||||
patch("wake_alarm._rtc_hw.RTC_ARMED_FILE", tmp_path / "rtc_armed.json"),
|
||||
patch("wake_alarm._ring_player._run", _no_process),
|
||||
patch("wake_alarm._ring_player._popen", _no_process),
|
||||
patch("wake_alarm._ring_monitors._spawn", _no_process),
|
||||
patch("wake_alarm._rtc_hw._run", _no_process),
|
||||
patch("wake_alarm._audit_sources._run", _no_process),
|
||||
# The shared free-day pool lives under ~/.local/share, outside every
|
||||
|
||||
164
wake_alarm/tests/test_fallback_bypass.py
Normal file
164
wake_alarm/tests/test_fallback_bypass.py
Normal file
@ -0,0 +1,164 @@
|
||||
"""A bypass on the phone rings the PC, outside every other rule (2026-11-22).
|
||||
|
||||
kuhy paused WakeAlarm from the launcher mid-ring twice and went back to
|
||||
sleep. The phone now publishes a ``bypass`` event; the PC rings for 30
|
||||
minutes from it, ignoring the window, a started session, a final reason
|
||||
and the day's own cap, until a newer ``dismissed`` arrives.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from wake_alarm._enforcement_payload import EnforcementView
|
||||
from wake_alarm._enforcement_records import PhoneEvent
|
||||
from wake_alarm._fallback_latch import Latch
|
||||
from wake_alarm._fallback_policy import (
|
||||
BYPASS,
|
||||
BYPASS_CLEARED,
|
||||
CAP,
|
||||
ESCAPE,
|
||||
FREE_DAY,
|
||||
OUTSIDE_WINDOW,
|
||||
SESSION_STARTED,
|
||||
SICK_DAY,
|
||||
Facts,
|
||||
bypass_stop_reason,
|
||||
decide,
|
||||
needs_facts,
|
||||
)
|
||||
|
||||
A = datetime(2026, 11, 22, 7, 0).astimezone()
|
||||
DAY = "2026-11-22"
|
||||
|
||||
|
||||
def _at(minutes: float) -> datetime:
|
||||
return A + timedelta(minutes=minutes)
|
||||
|
||||
|
||||
def _facts(minutes: float, bypass_minutes: float | None, **overrides: object) -> Facts:
|
||||
bypass_at = None if bypass_minutes is None else _at(bypass_minutes)
|
||||
fields: dict[str, object] = {"free_day": False, **overrides}
|
||||
return Facts(now=_at(minutes), alarm_at=A, bypass_at=bypass_at, **fields) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def _capped_latch() -> Latch:
|
||||
return Latch(
|
||||
date=DAY,
|
||||
started_at=_at(2).isoformat(),
|
||||
stopped_at=_at(32).isoformat(),
|
||||
stop_reason=CAP,
|
||||
)
|
||||
|
||||
|
||||
class TestDecide:
|
||||
def test_a_bypass_rings_over_a_started_session_and_a_used_cap(self) -> None:
|
||||
facts = _facts(
|
||||
50,
|
||||
45,
|
||||
session_started=True,
|
||||
settled=SESSION_STARTED,
|
||||
latch=_capped_latch(),
|
||||
ring_started=True,
|
||||
)
|
||||
assert decide(facts).ring
|
||||
assert decide(facts).reason == BYPASS
|
||||
|
||||
def test_a_bypass_rings_at_half_past_ten_outside_the_window(self) -> None:
|
||||
assert decide(_facts(210, 205)).reason == BYPASS
|
||||
|
||||
def test_thirty_minutes_after_the_bypass_it_is_quiet(self) -> None:
|
||||
decision = decide(_facts(240, 210, session_started=True))
|
||||
assert not decision.ring
|
||||
assert decision.reason == OUTSIDE_WINDOW
|
||||
|
||||
def test_no_bypass_outside_the_window_stays_quiet(self) -> None:
|
||||
assert decide(_facts(210, None)).reason == OUTSIDE_WINDOW
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("overrides", "reason"),
|
||||
[({"free_day": True}, FREE_DAY), ({"sick_day": True}, SICK_DAY)],
|
||||
)
|
||||
def test_free_and_sick_days_never_ring(
|
||||
self, overrides: dict[str, object], reason: str
|
||||
) -> None:
|
||||
decision = decide(_facts(50, 45, **overrides))
|
||||
assert not decision.ring
|
||||
assert decision.reason == reason
|
||||
|
||||
|
||||
class TestStop:
|
||||
def test_keeps_ringing_while_the_bypass_stands(self) -> None:
|
||||
assert bypass_stop_reason(_facts(50, 45, session_started=True)) is None
|
||||
|
||||
def test_a_newer_dismiss_clears_it(self) -> None:
|
||||
assert bypass_stop_reason(_facts(50, None)) == BYPASS_CLEARED
|
||||
|
||||
def test_the_cap_is_thirty_minutes_from_the_bypass(self) -> None:
|
||||
assert bypass_stop_reason(_facts(74.9, 45)) is None
|
||||
assert bypass_stop_reason(_facts(75, 45)) == CAP
|
||||
|
||||
def test_an_escape_or_a_day_off_stops_it(self) -> None:
|
||||
assert bypass_stop_reason(_facts(50, 45, escaped=True)) == ESCAPE
|
||||
assert bypass_stop_reason(_facts(50, 45, free_day=True)) == FREE_DAY
|
||||
|
||||
|
||||
class TestNeedsFacts:
|
||||
def test_the_bypass_watch_runs_four_hours_past_the_alarm(self) -> None:
|
||||
assert needs_facts(_at(239), A, None)
|
||||
assert not needs_facts(_at(240), A, None)
|
||||
assert not needs_facts(_at(-6), A, None)
|
||||
|
||||
|
||||
def _event(kind: str, at: str, **data: object) -> PhoneEvent:
|
||||
return PhoneEvent(at=at, kind=kind, data=dict(data))
|
||||
|
||||
|
||||
class TestView:
|
||||
def test_the_newest_bypass_of_the_day(self) -> None:
|
||||
view = EnforcementView(
|
||||
phone_events=(
|
||||
_event(
|
||||
"bypass", "2026-11-22T07:20:00+01:00", cause="suspended", date=DAY
|
||||
),
|
||||
_event(
|
||||
"bypass", "2026-11-22T07:10:00+01:00", cause="ring_killed", date=DAY
|
||||
),
|
||||
_event(
|
||||
"bypass",
|
||||
"2026-11-21T07:10:00+01:00",
|
||||
cause="suspended",
|
||||
date="2026-11-21",
|
||||
),
|
||||
),
|
||||
)
|
||||
assert view.bypass_on(DAY) == datetime.fromisoformat(
|
||||
"2026-11-22T07:20:00+01:00"
|
||||
)
|
||||
|
||||
def test_a_later_dismiss_clears_it(self) -> None:
|
||||
view = EnforcementView(
|
||||
phone_events=(
|
||||
_event("dismissed", "2026-11-22T07:30:00+01:00"),
|
||||
_event(
|
||||
"bypass", "2026-11-22T07:20:00+01:00", cause="suspended", date=DAY
|
||||
),
|
||||
),
|
||||
)
|
||||
assert view.bypass_on(DAY) is None
|
||||
|
||||
def test_an_earlier_dismiss_does_not(self) -> None:
|
||||
view = EnforcementView(
|
||||
phone_events=(
|
||||
_event(
|
||||
"bypass", "2026-11-22T07:40:00+01:00", cause="suspended", date=DAY
|
||||
),
|
||||
_event("dismissed", "2026-11-22T07:30:00+01:00"),
|
||||
),
|
||||
)
|
||||
assert view.bypass_on(DAY) is not None
|
||||
|
||||
def test_no_bypass_today(self) -> None:
|
||||
assert EnforcementView().bypass_on(DAY) is None
|
||||
89
wake_alarm/tests/test_fallback_bypass_tick.py
Normal file
89
wake_alarm/tests/test_fallback_bypass_tick.py
Normal file
@ -0,0 +1,89 @@
|
||||
"""The tick rings for a phone bypass, on its own clock (2026-11-22)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from wake_alarm import _fallback, _fallback_observe
|
||||
from wake_alarm._fallback_latch import read_latch
|
||||
from wake_alarm._fallback_policy import Decision
|
||||
from wake_alarm._sync import Alarm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Generator
|
||||
|
||||
DAY = "2026-11-22"
|
||||
A = datetime(2026, 11, 22, 7, 0).astimezone()
|
||||
|
||||
|
||||
def _log(*events: dict[str, object]) -> list[tuple[str, str]]:
|
||||
session = {"date": DAY, "started_at": f"{DAY}T07:20:00", "outcome": "active"}
|
||||
fields = {
|
||||
"current_session": [session, "h"],
|
||||
"phone_events": [list(events), "h2"],
|
||||
}
|
||||
return [("p", json.dumps({"alarm": {"fields": fields}}))]
|
||||
|
||||
|
||||
def _bypass(minutes: float) -> dict[str, object]:
|
||||
at = (A + timedelta(minutes=minutes)).isoformat()
|
||||
return {"at": at, "kind": "bypass", "data": {"cause": "suspended", "date": DAY}}
|
||||
|
||||
|
||||
def _dismissed(minutes: float) -> dict[str, object]:
|
||||
return {"at": (A + timedelta(minutes=minutes)).isoformat(), "kind": "dismissed"}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def world() -> Generator[MagicMock]:
|
||||
with (
|
||||
patch.object(_fallback_observe, "get_alarm", return_value=Alarm(7, 0, "c")),
|
||||
patch.object(_fallback, "get_alarm", return_value=Alarm(7, 0, "c")),
|
||||
patch.object(_fallback, "ensure_pair", return_value=("r", "l")),
|
||||
patch.object(_fallback, "_now", return_value=A + timedelta(minutes=215)),
|
||||
patch.object(_fallback, "ring") as ring,
|
||||
):
|
||||
|
||||
def fake_ring(poll: Callable[[], str | None], **_: object) -> str:
|
||||
return poll() or "still"
|
||||
|
||||
ring.side_effect = fake_ring
|
||||
yield ring
|
||||
|
||||
|
||||
def test_a_bypass_rings_at_half_past_ten_until_a_newer_dismiss(
|
||||
world: MagicMock,
|
||||
) -> None:
|
||||
with patch.object(
|
||||
_fallback_observe,
|
||||
"fetch_firebase_logs",
|
||||
side_effect=[_log(_bypass(205)), _log(_dismissed(214), _bypass(205))],
|
||||
):
|
||||
decision = _fallback.tick(A + timedelta(minutes=210))
|
||||
assert decision == Decision(ring=True, reason="bypass")
|
||||
world.assert_called_once()
|
||||
assert read_latch(DAY) is None
|
||||
|
||||
|
||||
def test_an_unreachable_poll_keeps_ringing(world: MagicMock) -> None:
|
||||
with patch.object(
|
||||
_fallback_observe, "fetch_firebase_logs", side_effect=[_log(_bypass(205)), None]
|
||||
):
|
||||
_fallback.tick(A + timedelta(minutes=210))
|
||||
assert world.call_count == 1
|
||||
assert world.call_args is not None
|
||||
|
||||
|
||||
def test_dry_run_reports_the_bypass(capsys: pytest.CaptureFixture[str]) -> None:
|
||||
with patch.object(
|
||||
_fallback_observe, "fetch_firebase_logs", return_value=_log(_bypass(205))
|
||||
):
|
||||
_fallback.main(["--dry-run", "--at", (A + timedelta(minutes=210)).isoformat()])
|
||||
out = capsys.readouterr().out
|
||||
assert "WOULD RING: bypass" in out
|
||||
assert "bypass_at=2026-11-22" in out
|
||||
@ -20,6 +20,7 @@ from wake_alarm._fallback_policy import (
|
||||
Facts,
|
||||
alarm_instant,
|
||||
decide,
|
||||
in_window,
|
||||
is_capped,
|
||||
needs_facts,
|
||||
stop_reason,
|
||||
@ -63,7 +64,7 @@ class TestWindow:
|
||||
def test_window_is_a_minus_5_to_a_plus_45(
|
||||
self, minutes: float, *, inside: bool
|
||||
) -> None:
|
||||
assert needs_facts(_at(minutes), A, None) is inside
|
||||
assert in_window(_at(minutes), A, None) is inside
|
||||
|
||||
def test_a_ring_already_started_is_judged_outside_the_window(self) -> None:
|
||||
assert needs_facts(_at(60), A, _latch(40))
|
||||
|
||||
74
wake_alarm/tests/test_ring_monitors.py
Normal file
74
wake_alarm/tests/test_ring_monitors.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""The monitor loops beside the PipeWire ring, with every process faked."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from wake_alarm import _ring_monitors, _ring_player
|
||||
from wake_alarm._ring_monitors import RING_SCRIPT, MonitorLoops
|
||||
from wake_alarm._ring_player import PipeWireBackend
|
||||
|
||||
# Bound at import, before conftest swaps the seam for a raiser.
|
||||
REAL_SPAWN = _ring_monitors._spawn
|
||||
|
||||
|
||||
def _done() -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.CompletedProcess([], 0, stdout="", stderr="")
|
||||
|
||||
|
||||
class TestMonitorLoops:
|
||||
def test_start_runs_the_script_in_monitors_mode(self) -> None:
|
||||
proc = MagicMock()
|
||||
with patch.object(_ring_monitors, "_spawn", return_value=proc) as spawn:
|
||||
loops = MonitorLoops.start(Path("rise.wav"), Path("loop.wav"))
|
||||
assert spawn.call_args.args[0] == [
|
||||
str(RING_SCRIPT),
|
||||
"--monitors",
|
||||
"rise.wav",
|
||||
"loop.wav",
|
||||
]
|
||||
assert loops is not None
|
||||
|
||||
def test_a_missing_script_never_fails_the_ring(self) -> None:
|
||||
with patch.object(_ring_monitors, "_spawn", side_effect=OSError("enoent")):
|
||||
assert MonitorLoops.start(Path("r"), Path("l")) is None
|
||||
|
||||
def test_stop_signals_the_whole_group_once(self) -> None:
|
||||
proc = MagicMock(pid=4242)
|
||||
proc.poll.return_value = None
|
||||
loops = MonitorLoops(proc)
|
||||
with patch.object(_ring_monitors.os, "killpg") as killpg:
|
||||
loops.stop()
|
||||
proc.poll.return_value = 0
|
||||
loops.stop()
|
||||
killpg.assert_called_once_with(4242, signal.SIGTERM)
|
||||
|
||||
def test_stop_ignores_a_group_already_gone(self) -> None:
|
||||
proc = MagicMock(pid=4242)
|
||||
proc.poll.return_value = None
|
||||
with patch.object(_ring_monitors.os, "killpg", side_effect=ProcessLookupError):
|
||||
MonitorLoops(proc).stop()
|
||||
|
||||
def test_real_seam_starts_its_own_session(self) -> None:
|
||||
with patch.object(subprocess, "Popen") as popen:
|
||||
REAL_SPAWN(["x"])
|
||||
assert popen.call_args.kwargs["start_new_session"] is True
|
||||
|
||||
|
||||
class TestPipeWireRingsTheMonitors:
|
||||
def test_start_and_stop_drive_the_monitor_loops(self) -> None:
|
||||
loops = MagicMock()
|
||||
backend = PipeWireBackend(Path("rise.wav"), Path("loop.wav"))
|
||||
with (
|
||||
patch.object(_ring_player, "_run", return_value=_done()),
|
||||
patch.object(_ring_player, "_popen", return_value=MagicMock()),
|
||||
patch.object(_ring_player.MonitorLoops, "start", return_value=loops) as st,
|
||||
):
|
||||
assert backend.start()[0]
|
||||
st.assert_called_once_with(Path("rise.wav"), Path("loop.wav"))
|
||||
backend.stop()
|
||||
backend.stop()
|
||||
loops.stop.assert_called_once()
|
||||
@ -97,6 +97,7 @@ class TestPipeWire:
|
||||
with (
|
||||
patch.object(_ring_player, "_run", run),
|
||||
patch.object(_ring_player, "_popen", return_value=proc) as popen,
|
||||
patch.object(_ring_player.MonitorLoops, "start"),
|
||||
):
|
||||
assert self._backend().start() == (True, "pw-play started")
|
||||
assert [c.args[0][1] for c in run.call_args_list] == ["set-mute", "set-volume"]
|
||||
|
||||
67
wake_alarm/tests/test_ring_probe.py
Normal file
67
wake_alarm/tests/test_ring_probe.py
Normal file
@ -0,0 +1,67 @@
|
||||
"""The silent monitor probe runs once, at A - 5, with no graphical session."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from wake_alarm import _ring_probe
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
|
||||
A = datetime(2026, 11, 23, 7, 0).astimezone()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def done_file(tmp_path: Path) -> Generator[Path]:
|
||||
path = tmp_path / "fresh" / "ring_probe_done"
|
||||
with patch.object(_ring_probe, "PROBE_DONE_FILE", path):
|
||||
yield path
|
||||
|
||||
|
||||
def _run(minutes: float, *, graphical: bool, started: bool = True) -> str | None:
|
||||
with (
|
||||
patch.object(_ring_probe, "graphical_session", return_value=(graphical, "why")),
|
||||
patch.object(_ring_probe, "_ok", return_value=(started, "out")) as ok,
|
||||
):
|
||||
result = _ring_probe.maybe_probe(A + timedelta(minutes=minutes), A)
|
||||
_run.calls = ok.call_args_list # type: ignore[attr-defined]
|
||||
return result
|
||||
|
||||
|
||||
def test_it_starts_the_unit_at_a_minus_five_with_no_session(done_file: Path) -> None:
|
||||
assert _run(-5, graphical=False) == "started"
|
||||
assert _run.calls[0].args[0] == [ # type: ignore[attr-defined]
|
||||
"sudo",
|
||||
"-n",
|
||||
"systemctl",
|
||||
"start",
|
||||
"wake-alarm-ring-probe.service",
|
||||
]
|
||||
assert done_file.exists()
|
||||
|
||||
|
||||
def test_it_runs_only_once(done_file: Path) -> None:
|
||||
done_file.parent.mkdir()
|
||||
done_file.write_text("x")
|
||||
assert _run(-4, graphical=False) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("minutes", [-6, 0, 30])
|
||||
def test_only_in_the_five_minutes_before_the_alarm(minutes: float) -> None:
|
||||
assert _run(minutes, graphical=False) is None
|
||||
|
||||
|
||||
def test_it_waits_for_a_morning_with_no_session(done_file: Path) -> None:
|
||||
assert _run(-3, graphical=True) == "waiting_for_no_session"
|
||||
assert not done_file.exists()
|
||||
|
||||
|
||||
def test_a_refused_start_is_retried_next_morning(done_file: Path) -> None:
|
||||
assert _run(-3, graphical=False, started=False) == "failed"
|
||||
assert not done_file.exists()
|
||||
Loading…
Reference in New Issue
Block a user