Files
second-screen/docs/superpowers/plans/2026-10-22-second-screen.md
2026-10-22 12:57:40 +02:00

25 KiB

Second Screen Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: A Docker container that drives the second Turing screen and shows exactly one Casio-style view, chosen by the VIEW env var: a weather clock (weather) or server stats (server).

Architecture: Flat Python modules like bus-department-schedule (same style, same pinned screen library). A View is a small object with a cheap frame_key(now), a full render(now) and an optional patch(now); a runner loop pushes a full frame when the key changes and a partial patch (the seconds) otherwise. Network and system reads run in background Poller threads so a slow weather or Docker call can never stall the clock.

Tech Stack: Python 3.12, Pillow, numpy, pyserial, requests, pytest; screen library mathoudebine/turing-smart-screen-python at commit 2b33ab4f00a096916dd6a1174441a53a7ec33b03; Open-Meteo; Docker Engine API over /var/run/docker.sock.

Spec: docs/superpowers/specs/2026-10-22-second-screen-design.md. Visual reference for the weather view: docs/reference/weather-mockup.png and docs/reference/casio_spike.py (throwaway; port the drawing code, do not import it).

Global Constraints

  • Screen: Turing Rev A, image 480x320, orientation LANDSCAPE (the bus board uses REVERSE_LANDSCAPE).
  • Device: /dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00; never ttyACM*.
  • Time zone Europe/Prague, 24 h clock, weekdays PO ÚT ST ČT PÁ SO NE, date as 22.10..
  • Weather: Open-Meteo, Zlín (lat 49.2265, lon 17.6627), refresh every 15 min, graph = next 12 hours from now, bars = rain probability, corner = total mm for those hours.
  • One view per container, selected by VIEW; unknown VIEW shows an on-screen error and the container stays up idle holding the port (no exit, no restart loop).
  • Device missing at startup: log once, retry every 30 s, never exit.
  • Stale data is visibly marked in both views; the clock keeps running when anything else fails.
  • Palette (from the mockup): background (170,184,154), ink (28,36,24), ghost segments (158,172,143); digit slant 0.14.
  • Deploy: public Gitea repo, Coolify Docker Compose, compose location /docker-compose.yml, press Deploy after git push. Never create the remote repo, push, or delete anything on the server (apod-test container, ~/apod-test) without asking the owner first.
  • Commit messages end with Co-Authored-By: Claude Sonnet 5.5 <[email protected]>.

Review Focus

  • Rain probability of exactly 100 (real: Zlín is at 100 % today): the three-digit readout must fit its box and not touch the divider.
  • Negative or zero temperatures (-3, -0.4): minus segment drawn, never -0, readout stays inside its box.
  • Open-Meteo returning null entries or fewer than 12 future hours: fewer bars / dashes, never an exception.
  • First CPU sample (no previous reading) and processes that vanish while /proc is being read: no division by zero, no crash.
  • Docker socket missing, refusing, or hanging: the containers section shows NO DOCKER, the rest of the server view still updates.

File structure

File Responsibility
lcdkit.py Palette, 7-segment number, segmented bar helpers, font loader, stale tag
poller.py Poller: background fetch with last-good value, age, version
weather_data.py Open-Meteo fetch + parse, Weather, Icon, icon_for
weather_view.py WeatherView
stats_data.py /proc, /sys, Docker readers, Stats, short_name
server_view.py ServerView
view.py Patch, View protocol, REGISTRY, make_view, UnknownView
runner.py open_screen, render_error, run loop (no env access, takes everything as parameters)
main.py Env vars, signals, wiring
preview.py Renders every view with fake data to docs/previews/*.png
tests/ pytest, tests/fixtures/open-meteo-zlin.json (real response, already saved)
Dockerfile, docker-compose.yml, README.md, .gitignore, requirements.txt, requirements-dev.txt, pytest.ini as in the bus board

Task 1: Project scaffold and LCD kit

Files:

  • Create: lcdkit.py, tests/test_lcdkit.py, tests/conftest.py, pytest.ini (pythonpath = ., testpaths = tests), requirements.txt (Pillow>=11.0, numpy>=2.0, pyserial~=3.5, requests>=2.32), requirements-dev.txt (-r requirements.txt, pytest>=8), .gitignore (.venv/, __pycache__/), assets/fonts/Roboto-Bold.ttf + LICENSE.txt (take them from res/fonts/roboto/ of the pinned library commit's tarball)

Interfaces:

  • Produces:

    • W, H = 480, 320; BG, INK, GHOST: tuple[int,int,int]; SLANT = 0.14
    • number(d: ImageDraw.ImageDraw, text: str, x: float, y: float, w: float, h: float, t: float, gap: float, ghost: bool = True) -> float draws 0-9 : . - as slanted 7-segment glyphs, returns x after the last glyph. Port from docs/reference/casio_spike.py.
    • number_width(text: str, w: float, t: float, gap: float) -> float equals number(...) - x without drawing.
    • v_bar(d, x, y_bottom, pct: float | None, w, n_seg, seg_h, gap) and h_bar(d, x, y, pct: float | None, h, n_seg, seg_w, gap): segmented LCD bars, round(pct/100*n_seg) lit segments, the rest ghost; None draws all ghost.
    • load_font(size: int) -> ImageFont.FreeTypeFont (Roboto-Bold from assets/fonts).
    • tag(d, xy: tuple[int,int], text: str, font) -> tuple[int,int,int,int] inverted label (ink box, background-coloured text), returns its box.
    • fmt_temp(value: float | None) -> str: rounds to int, "--" for None, "0" for any value that rounds to zero (never -0).
  • Step 1: Write failing tests in tests/test_lcdkit.py: test_number_returns_start_plus_width (number(d,"14:32",10,10,54,96,12,9) - 10 == number_width("14:32",54,12,9)); test_eight_lights_more_ink_than_one (render each on a blank BG image with ghost=False, count INK pixels, 8 > 1 > 0); test_ghost_segments_use_ghost_colour ("1" with ghost=True has GHOST pixels, with ghost=False has none); test_minus_draws_ink ("-3" has more ink than "3"); test_h_bar_lights_proportionally (pct=50, n_seg=10 lights 5 segments, counted by sampling segment centres); test_bar_none_is_all_ghost; test_fmt_temp_cases (10.2 -> "10", -3.4 -> "-3", -0.4 -> "0", None -> "--").

  • Step 2: pytest tests/test_lcdkit.py -v. Expected: FAIL (module missing).

  • Step 3: Implement lcdkit.py per Interfaces; reuse the spike's polygon/slant geometry and its gap 1.5.

  • Step 4: pytest tests/test_lcdkit.py -v. Expected: PASS.

  • Step 5: Commit feat: LCD kit (segment digits, bars, fonts).

Task 2: Poller

Files: Create poller.py, tests/test_poller.py.

Interfaces:

  • Produces: class Poller(Generic[T]) with __init__(self, fetch: Callable[[], T], interval: float, clock: Callable[[], float] = time.monotonic); poll_once(self) -> bool (runs fetch, never raises, returns success); start(self) -> None (daemon thread calling poll_once immediately, then every interval s, retrying after min(interval, 60) s after a failure); stop(self) -> None; read-only value: T | None (last good), version: int (+1 per success), failures: int (consecutive), age(self) -> float | None (seconds since last success via clock, None if never).

  • Step 1: Write failing tests: test_success_stores_value_and_bumps_version; test_failure_keeps_last_good_value_and_counts (fetch raises second time: value unchanged, failures == 1, version unchanged); test_success_resets_failures; test_age_uses_injected_clock (fake clock advances 90 -> age() == 90); test_age_none_before_first_success; test_slow_fetch_does_not_block_reader (start with a fetch that waits on a threading.Event; value reads None immediately; set the event; wait for version == 1).

  • Step 2: pytest tests/test_poller.py -v. Expected: FAIL.

  • Step 3: Implement poller.py (lock around state; threading.Event.wait(timeout) for sleeping so stop is prompt; log failures with logging, once per failure streak start and on recovery).

  • Step 4: pytest tests/test_poller.py -v. Expected: PASS.

  • Step 5: Commit feat: background poller.

Task 3: Weather data

Files: Create weather_data.py, tests/test_weather_data.py. Fixture tests/fixtures/open-meteo-zlin.json exists (query: current=temperature_2m,weather_code&hourly=precipitation_probability,precipitation&daily=temperature_2m_max,temperature_2m_min&timezone=Europe/Prague&forecast_days=2; hourly has 48 entries YYYY-MM-DDTHH:00, daily has 2).

Interfaces:

  • Consumes: requests.

  • Produces:

    • @dataclass(frozen=True) Hour(time: datetime, rain_pct: int | None, mm: float | None) (naive local time)
    • @dataclass(frozen=True) Weather(temp: float | None, code: int | None, today_max: float | None, today_min: float | None, hours: tuple[Hour, ...]), at most 12 hours, starting with the hour containing now
    • class Icon(Enum): SUN, PARTLY, CLOUDY, RAIN, SNOW, STORM, FOG; icon_for(code: int | None) -> Icon | None (WMO: 0 SUN; 1,2 PARTLY; 3 CLOUDY; 45,48 FOG; 51-57, 61-67, 80-82 RAIN; 71-77, 85, 86 SNOW; 95-99 STORM; unknown/None -> None)
    • parse_weather(payload: dict, now: datetime) -> Weather
    • fetch_weather(now: datetime, get=requests.get) -> Weather (timeout 10 s, raise_for_status)
    • LAT = 49.2265, LON = 17.6627
  • Step 1: Write failing tests: test_parse_fixture_window (with now = datetime(2026,10,22,12,45): 12 hours, first is 12:00, last 23:00, first rain_pct equals the fixture value at index 12); test_parse_today_max_min (15.0, 6.0); test_icon_mapping (61 -> RAIN, 3 -> CLOUDY, 95 -> STORM, 999 -> None, None -> None); test_null_entries_become_none (set precipitation_probability[13] = None and precipitation[13] = None: that Hour has both None); test_short_hourly_gives_fewer_hours (truncate hourly lists to 14 entries from now at 12:45 -> 2 hours); test_missing_current_gives_none_temp (drop current: temp is None, no exception); test_fetch_passes_coordinates (fake get records params, returns the fixture; assert latitude/longitude and timezone == "Europe/Prague").

  • Step 2: run, expect FAIL.

  • Step 3: Implement. Pick the hourly start by matching now.replace(minute=0) against the time strings; use .get throughout so missing keys never raise.

  • Step 4: run, expect PASS.

  • Step 5: Commit feat: Open-Meteo parsing and icon mapping.

Task 4: View protocol and weather view

Files: Create view.py, weather_view.py, preview.py (weather part), tests/test_weather_view.py, docs/previews/weather.png.

Interfaces:

  • Consumes: lcdkit.*, Poller, Weather, Icon.

  • Produces:

    • view.py: @dataclass Patch(image: Image.Image, x: int, y: int); class View(Protocol): name: str, start() -> None, stop() -> None, frame_key(now: datetime) -> Hashable, render(now: datetime) -> Image.Image (480x320), patch(now: datetime) -> Patch | None (cheap partial update valid while frame_key is unchanged; may return None).
    • weather_view.py: class WeatherView with name = "weather", __init__(self, poller: Poller[Weather]); STALE_AFTER = 3600.0 seconds. frame_key = (now.strftime("%Y%m%d%H%M"), poller.version, is_stale). patch returns the two seconds digits at their layout position.
    • Layout: as docs/reference/weather-mockup.png (top weekday strip with today inverted; HH:MM left; seconds and 22.10. right; bottom-left ZLÍN NYNÍ, icon, current temperature, MAX/MIN, highest rain %; bottom-right 12-bar rain graph with hour labels every 3 hours and mm total). Draw the seconds so that the patch image reproduces exactly the region the full render draws (same coordinates).
    • Icons: one function per Icon in the mockup's chunky ink-only style (the spike's sun_cloud is the PARTLY one).
    • No weather yet: dashes in every weather field and an empty ghost graph. Weather older than STALE_AFTER: show last values plus tag(... "STARÉ") beside ZLÍN NYNÍ.
  • Step 1: Write failing tests using a hand-built Weather and a poller stub (value, version, age()): test_render_size_is_480x320; test_frame_key_changes_each_minute_not_each_second; test_frame_key_changes_when_weather_updates (version bump); test_frame_key_changes_when_stale_flips; test_patch_matches_full_render_region (crop the full render at the patch box and compare to patch.image pixel for pixel); test_no_weather_renders_without_error; test_stale_tag_only_when_old (render with age 60 vs 7200: images differ in the tag box only, check by pixel region); test_hundred_percent_fits (rain 100: no INK pixel in the divider column band x in 204..208 from the readout's rows other than the divider itself, and number_width("100", ...) plus readout x is < 200); test_negative_temp_fits (temp -3.4: minus drawn, right edge of readout < 200); test_sunday_inverts_last_weekday_cell (a Sunday now: the NE cell is ink-filled, PO is not).

  • Step 2: run, expect FAIL.

  • Step 3: Implement view.py and weather_view.py. If the three-digit or negative readout does not fit the mockup's box, narrow the digits for that case rather than moving the divider.

  • Step 4: run, expect PASS.

  • Step 5: Implement preview.py weather part (fake Weather incl. a 100 % case and a negative-temperature case in one contact sheet) and write docs/previews/weather.png; look at it and compare with the mockup.

  • Step 6: Commit feat: weather view.

Task 5: Server stats data

Files: Create stats_data.py, tests/test_stats_data.py, tests/fixtures/ text samples (proc_stat, meminfo, pid_stat_*, docker_containers.json copied from a real GET /containers/json?all=1 on the server via ssh coolify; redact nothing sensitive, they are only names).

Interfaces:

  • Produces:

    • @dataclass(frozen=True) Container(name: str, state: str, health: str | None); status_label(c: Container) -> str returning one of "OK" (running + healthy), "UP" (running, no healthcheck), "UNHEALTHY", "RESTART", "EXITED"
    • @dataclass(frozen=True) Proc(name: str, cpu_pct: float)
    • @dataclass(frozen=True) Stats(cpu_pct: float | None, mem_pct: float | None, disk_pct: float | None, load: tuple[float, float, float] | None, temp_c: float | None, uptime_s: float | None, containers: tuple[Container, ...] | None, procs: tuple[Proc, ...]), containers is None means Docker unavailable
    • short_name(name: str, labels: dict[str, str], image: str) -> str: strip Coolify's random suffix (n8n-ebe62bdjbp9f755kwh59lv8d -> n8n, screen-pe28mpghgqnxaz12vyfyijrg-151725872213 -> screen, task-runners-ebe62... -> task-runners); names without a hash stay (coolify-db); a name that is only a hash (jn5mdu87ituoxzyojk84ugdj-20261018T132559) falls back to label com.docker.compose.service, else the image repository name's last path part
    • parse_cpu_times(proc_stat_text: str) -> tuple[int, int] (busy, total jiffies from the first cpu line); cpu_pct(prev: tuple[int,int] | None, cur: tuple[int,int]) -> float | None (None without a previous sample or zero delta)
    • parse_mem_pct(meminfo_text: str) -> float (1 - MemAvailable/MemTotal, in percent)
    • parse_pid_stat(text: str) -> tuple[str, int] (command name, utime + stime), safe for names containing spaces and parentheses
    • list_containers(sock_path: str, timeout: float = 3.0) -> tuple[Container, ...] (HTTP over the unix socket with http.client, GET /containers/json?all=1)
    • class StatsReader(proc_root: str = "/host/proc", sys_root: str = "/host/sys", disk_path: str = "/host/root", docker_sock: str = "/var/run/docker.sock") with read(self) -> Stats; keeps the previous CPU and per-process samples between calls. Disk percent from os.statvfs(disk_path); temperature from the first readable thermal_zone*/temp (millidegrees) under sys_root; top 5 processes by CPU delta since the previous read.
  • Step 1: Write failing tests: test_parse_cpu_times_and_pct (two samples -> expected percent); test_cpu_pct_none_without_previous; test_cpu_pct_none_on_zero_delta; test_parse_mem_pct (fixture); test_parse_pid_stat_with_parens_and_spaces (4242 (my (odd) proc) S ... -> name my (odd) proc); test_short_name_cases (the five names above plus plex-z0qh1wrbuzxo0jsfiazc3evc -> plex); test_short_name_hash_only_uses_compose_label_then_image; test_status_label_cases; test_list_containers_parses_fixture (tiny fake unix-socket server in the test serving docker_containers.json); test_list_containers_missing_socket_raises (reader turns this into containers=None); test_reader_first_read_has_no_cpu_pct; test_reader_survives_vanished_process (fake proc tree where a pid directory disappears between listing and reading); test_reader_docker_down_still_returns_other_stats (nonexistent socket -> containers is None, mem_pct present); test_reader_docker_hang_times_out (server that accepts and never answers; read() returns within ~timeout+1 s with containers is None).

  • Step 2: run, expect FAIL.

  • Step 3: Implement. Reader failures per source are caught separately and yield None for that field only.

  • Step 4: run, expect PASS.

  • Step 5: Commit feat: server stats readers.

Task 6: Server view

Files: Create server_view.py, extend preview.py, tests/test_server_view.py, docs/previews/server.png.

Interfaces:

  • Consumes: lcdkit.*, Poller[Stats], Stats, status_label.

  • Produces: class ServerView with name = "server", __init__(self, poller: Poller[Stats]); STALE_AFTER = 30.0 seconds; frame_key = (now.second // 5, poller.version, is_stale); patch returns None.

  • Content in priority order (builder designs the layout in the weather view's style, no mockup exists): CPU/RAM/disk segmented bars with numbers; load average, temperature, uptime; container list (readable short name + status label, ones needing attention first, truncate to what fits, +N for the rest); top processes by CPU. containers is None -> the section reads NO DOCKER. Any None number shows --. Old stats (age > STALE_AFTER) keep the last numbers and show a STARÉ tag.

  • Step 1: Write failing tests: test_render_size_is_480x320; test_frame_key_changes_every_five_seconds; test_none_stats_render_without_error (all fields None, containers=None, procs=()); test_many_containers_are_truncated_with_remainder (30 containers render without error and the image differs from 5 containers); test_stale_tag_only_when_old; test_bar_reflects_value (cpu 0 vs 100: ink pixel count in the bar region differs); test_no_docker_text_present (render with containers=None vs a few containers: images differ in the section region).

  • Step 2: run, expect FAIL.

  • Step 3: Implement server_view.py.

  • Step 4: run, expect PASS.

  • Step 5: Add the server sample(s) to preview.py (normal, docker down, stale), write docs/previews/server.png, look at it.

  • Step 6: Stop and show the owner docs/previews/server.png (the spec requires their review of this layout before deployment). Adjust on their feedback, then commit feat: server view.

Task 7: Registry, runner and entry point

Files: Create registry.py (or put into view.py, builder's choice), runner.py, main.py, tests/test_runner.py, tests/test_registry.py.

Interfaces:

  • Consumes: View, WeatherView, ServerView, Poller, fetch_weather, StatsReader.

  • Produces:

    • REGISTRY: dict[str, Callable[[], View]] with keys "weather" (poller on fetch_weather(local_now), interval 900) and "server" (poller on StatsReader().read, interval 5); make_view(name: str) -> View raising UnknownView(name: str, valid: list[str])
    • runner.render_error(lines: Sequence[str]) -> Image.Image (480x320, LCD style, readable)
    • runner.open_screen(factory: Callable[[], Any], *, running: Callable[[], bool], sleep: Callable[[float], None] = time.sleep, retry_s: float = 30.0) -> Any | None: calls factory() until it returns, logging the first failure only, sleeping retry_s between tries; returns None if running() turns false
    • runner.run(view: View, lcd, *, now_fn: Callable[[], datetime], running: Callable[[], bool], sleep: Callable[[float], None] = time.sleep, max_failures: int = 10) -> None: loop at ~20 Hz; full render pushed when frame_key changed, else patch once per new second; a failed draw is retried on the next tick and, after max_failures consecutive failures, the exception is raised so Docker restarts and reopens the port
    • runner.idle_with_message(lcd, lines, *, running, sleep) -> None: draws render_error(lines) once, then waits until running() is false
    • main.py reads VIEW, SCREEN_DEVICE (default the by-id path above), SCREEN_ORIENTATION (LANDSCAPE), SCREEN_BRIGHTNESS (50), BOARD_TZ (Europe/Prague), LCD_LIB_PATH (/opt/lcd); installs SIGTERM/SIGINT handlers that stop loops and call view.stop() and lcd.closeSerial(); sets up logging with force=True as in the bus board.
  • Step 1: Write failing tests with a FakeLcd recording DisplayPILImage(image, x, y) calls and a fake clock: test_make_view_unknown_lists_valid_names; test_run_pushes_full_frame_once_per_key (two ticks, same key: one full push); test_run_pushes_patch_each_new_second (key stable, seconds advance: one patch per second); test_run_pushes_full_frame_when_key_changes; test_run_retries_failed_draw_and_continues (first DisplayPILImage raises, second works); test_run_raises_after_max_failures; test_open_screen_retries_until_available (factory fails twice then works; sleep called twice with 30.0; failure logged once); test_open_screen_returns_none_when_stopped; test_idle_with_message_draws_once_and_returns_on_stop; test_render_error_size_and_has_ink.

  • Step 2: run, expect FAIL.

  • Step 3: Implement. In main.py: open the screen with retry; build the view, and on UnknownView call idle_with_message with a message naming the bad value and the valid views (also logged); otherwise view.start() then run.

  • Step 4: pytest -v. Expected: all tests PASS.

  • Step 5: Commit feat: runner, registry and entry point.

Task 8: Container, deploy and verification

Files: Create Dockerfile, docker-compose.yml, README.md; modify nothing else.

Interfaces: Compose service screen, restart: unless-stopped, env VIEW: weather (plain value to edit), SCREEN_DEVICE defaulting to the by-id path (also passed in devices: as in the bus board), SCREEN_ORIENTATION: LANDSCAPE, TZ/BOARD_TZ: Europe/Prague; read-only mounts of host /proc (at /host/proc), /sys (at /host/sys), the narrowest read-only mount that sits on the host root filesystem for disk usage (a single file is enough, at /host/root), /var/run/docker.sock; pid: host only if reading host processes needs it. The Dockerfile follows the bus board's (python:3.12-slim, library pinned by LCD_COMMIT, library/ and res/ extracted to /opt/lcd).

  • Step 1: Write Dockerfile and docker-compose.yml; docker compose config must validate.
  • Step 2: Write README.md in the bus board's shape: what it is, develop/preview (pytest, python preview.py), how to switch views (edit VIEW, commit, push, Deploy), adding a view (module + REGISTRY entry + README line), deployment steps (Coolify settings from Global Constraints), the Docker-socket and pid: host security note, "if something is wrong" (upside-down: flip SCREEN_ORIENTATION to REVERSE_LANDSCAPE; blank screen; bad VIEW), config table, known limitations.
  • Step 3: Manual run on the server for verification: rsync the project (not .git) to a scratch directory on the server via ssh coolify, docker compose up --build -d. Confirm with docker logs and by asking the owner to confirm the screen: VIEW=weather shows the live weather view with the correct time and ticking seconds. Then change to VIEW=server, up -d, confirm the server view with real container names. Then set VIEW=bogus, confirm the on-screen error and that the container stays up (docker ps) without restarting. Set the owner's chosen view, docker compose down.
  • Step 4: Commit feat: Docker packaging and README. Check git status is clean.
  • Step 5: Ask the owner before each of: creating the Gitea repo, git push, configuring the Coolify application, deleting apod-test and ~/apod-test (only after the Coolify deployment is verified on the screen).
  • Step 6: After the owner's go-ahead and deployment: verify against the live screen (owner confirmation) and the container logs; update the README's deploy date; commit.

Self-review notes (plan author): Spec coverage: views and switching (Tasks 4, 6, 7, 8), weather details and failure behaviour (3, 4), server content and data access (5, 6, 8), startup errors and device retry (7), stale markers on both views (4, 6), preview without hardware (4, 6), owner gates (6, 8). The Poller, View, Weather, Stats names match across tasks.