lockettering, uk
grid142 gCO₂/kWh
solar3.8 kW export
last deploy695181c

Screen-time tokens with a SQLite ledger and one max()

A proof of concept: Home Assistant is the policy brain, UniFi is the enforcement edge, and a 225-line ledger sits between them so two tokens spent five minutes apart add up correctly.

A Home Assistant counter helper is fine for screen time until the second token gets spent mid-session. Then you need stacking, reward credits, an audit trail, and state that survives a rebuild of the Pi. That’s a ledger, not a counter. So it became a small FastAPI service with SQLite behind it.

This is a proof of concept, not a product. The children below are Alice and Bob, because every protocol needs them.

family_tv     tv      45 min   max 3
alice_gaming  gaming  30 min   max 3
bob_gaming    gaming  30 min   max 3
alice_social  social  20 min   max 2
bob_social    social  20 min   max 2

The split

Home Assistant  --->  kids-time API  --->  enforcement hooks  ---> UniFi / DNS / scripts
                           |
                           +--> SQLite ledger
  • Home Assistant decides policy: schedule modes (term, half_term, weekend, holiday), reward buttons, the 30/10/5/1-minute reminders.
  • The API owns balances, active sessions, and an append-only ledger. It is the source of truth.
  • Hooks are two shell commands, ENFORCE_ON_CMD and ENFORCE_OFF_CMD, run with KT_RESOURCE and KT_ACTIVE_UNTIL in the environment. Whatever toggles the UniFi policy or DNS profile lives there.

UniFi objects are deliberately not created by the service. Their API shape moves between controller versions more often than HA YAML or a Docker image does, so that edge stays a script I can rewrite in ten minutes.

The one rule that matters

base = max([dt for dt in [now_dt, current_active_until] if dt is not None])
new_end = base + timedelta(minutes=(duration_minutes * amount))

No active session: time starts now. Active session: time stacks on its end. family_tv tokens are 45 minutes, so a session ending at 18:30 with a second token spent at 18:05 ends at 19:15, not 18:50. The naive now + duration version silently eats 25 minutes and a household argument.

Atomicity

Every write runs inside BEGIN IMMEDIATE, which takes SQLite’s reserved lock at the start of the transaction rather than on first write. Two HA automations firing a redeem in the same second serialise instead of both reading balance = 1 and both succeeding. The balance update and the ledger insert commit together or not at all; credit clamps at max_balance (3 for TV and gaming, 2 for social) so a generous afternoon can’t bank a week.

Expiry is a separate POST /v1/reconcile that clears active_until once it’s in the past, writes a reconcile ledger row with actor = 'system', and re-runs the hooks. HA calls it on a timer.

Known gaps

It’s a PoC, so there are some. Writing this down is how I found them.

  • Hook failure after commit. redeem() commits, then apply_enforcement() runs the hook with check=True. A failing hook raises CalledProcessError, the client gets a 500, and the token is already spent. The ledger is right; the network isn’t. Fix is either an outbox row the reconcile loop retries, or catching the failure and returning 200 with an enforcement: failed field.
  • No inbound auth. HA_TOKEN is for calling Home Assistant, not for callers of this API. Anything on the VLAN can POST /v1/credit. Alice has read the OpenAPI docs at /docs. A bearer token checked by a FastAPI dependency is the obvious first step.
  • shell=True. The hook command comes from env, not from requests, so it’s not injectable today. It would be the first thing to bite if resource names ever came from user input.
  • tests/ is empty. The stacking rule is the one piece of logic worth a test, and it has none.

Reconcile-driven retries and the auth dependency are next. The max() stays.