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 usesREVERSE_LANDSCAPE). - Device:
/dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00; neverttyACM*. - Time zone
Europe/Prague, 24 h clock, weekdaysPO ÚT ST ČT PÁ SO NE, date as22.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; unknownVIEWshows 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 slant0.14. - Deploy: public Gitea repo, Coolify Docker Compose, compose location
/docker-compose.yml, press Deploy aftergit push. Never create the remote repo, push, or delete anything on the server (apod-testcontainer,~/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
nullentries or fewer than 12 future hours: fewer bars / dashes, never an exception. - First CPU sample (no previous reading) and processes that vanish while
/procis 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 fromres/fonts/roboto/of the pinned library commit's tarball)
Interfaces:
-
Produces:
W, H = 480, 320;BG, INK, GHOST: tuple[int,int,int];SLANT = 0.14number(d: ImageDraw.ImageDraw, text: str, x: float, y: float, w: float, h: float, t: float, gap: float, ghost: bool = True) -> floatdraws0-9 : . -as slanted 7-segment glyphs, returns x after the last glyph. Port fromdocs/reference/casio_spike.py.number_width(text: str, w: float, t: float, gap: float) -> floatequalsnumber(...) - xwithout drawing.v_bar(d, x, y_bottom, pct: float | None, w, n_seg, seg_h, gap)andh_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;Nonedraws all ghost.load_font(size: int) -> ImageFont.FreeTypeFont(Roboto-Bold fromassets/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,"--"forNone,"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 blankBGimage withghost=False, countINKpixels,8 > 1 > 0);test_ghost_segments_use_ghost_colour("1"withghost=TruehasGHOSTpixels, withghost=Falsehas none);test_minus_draws_ink("-3"has more ink than"3");test_h_bar_lights_proportionally(pct=50,n_seg=10lights 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.pyper Interfaces; reuse the spike's polygon/slant geometry and its gap1.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(runsfetch, never raises, returns success);start(self) -> None(daemon thread callingpoll_onceimmediately, then everyintervals, retrying aftermin(interval, 60)s after a failure);stop(self) -> None; read-onlyvalue: T | None(last good),version: int(+1 per success),failures: int(consecutive),age(self) -> float | None(seconds since last success viaclock,Noneif 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:valueunchanged,failures == 1,versionunchanged);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 athreading.Event;valuereadsNoneimmediately; set the event; wait forversion == 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 sostopis prompt; log failures withlogging, 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 containingnowclass 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) -> Weatherfetch_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(withnow = datetime(2026,10,22,12,45): 12 hours, first is12:00, last23:00, firstrain_pctequals 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(setprecipitation_probability[13] = Noneandprecipitation[13] = None: thatHourhas bothNone);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(dropcurrent:temp is None, no exception);test_fetch_passes_coordinates(fakegetrecords params, returns the fixture; assertlatitude/longitudeandtimezone == "Europe/Prague"). -
Step 2: run, expect FAIL.
-
Step 3: Implement. Pick the hourly start by matching
now.replace(minute=0)against thetimestrings; use.getthroughout 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 whileframe_keyis unchanged; may returnNone).weather_view.py:class WeatherViewwithname = "weather",__init__(self, poller: Poller[Weather]);STALE_AFTER = 3600.0seconds.frame_key = (now.strftime("%Y%m%d%H%M"), poller.version, is_stale).patchreturns the two seconds digits at their layout position.- Layout: as
docs/reference/weather-mockup.png(top weekday strip with today inverted;HH:MMleft; seconds and22.10.right; bottom-leftZLÍ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 thepatchimage reproduces exactly the region the full render draws (same coordinates). - Icons: one function per
Iconin the mockup's chunky ink-only style (the spike'ssun_cloudis the PARTLY one). - No weather yet: dashes in every weather field and an empty ghost graph. Weather older than
STALE_AFTER: show last values plustag(... "STARÉ")besideZLÍN NYNÍ.
-
Step 1: Write failing tests using a hand-built
Weatherand 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 topatch.imagepixel 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: noINKpixel in the divider column bandx in 204..208from the readout's rows other than the divider itself, andnumber_width("100", ...)plus readoutxis< 200);test_negative_temp_fits(temp-3.4: minus drawn, right edge of readout< 200);test_sunday_inverts_last_weekday_cell(a Sundaynow: theNEcell is ink-filled,POis not). -
Step 2: run, expect FAIL.
-
Step 3: Implement
view.pyandweather_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.pyweather part (fakeWeatherincl. a 100 % case and a negative-temperature case in one contact sheet) and writedocs/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) -> strreturning 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 Nonemeans Docker unavailableshort_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 labelcom.docker.compose.service, else the image repository name's last path partparse_cpu_times(proc_stat_text: str) -> tuple[int, int](busy, total jiffies from the firstcpuline);cpu_pct(prev: tuple[int,int] | None, cur: tuple[int,int]) -> float | None(Nonewithout 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 parentheseslist_containers(sock_path: str, timeout: float = 3.0) -> tuple[Container, ...](HTTP over the unix socket withhttp.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")withread(self) -> Stats; keeps the previous CPU and per-process samples between calls. Disk percent fromos.statvfs(disk_path); temperature from the first readablethermal_zone*/temp(millidegrees) undersys_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 ...-> namemy (odd) proc);test_short_name_cases(the five names above plusplex-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 servingdocker_containers.json);test_list_containers_missing_socket_raises(reader turns this intocontainers=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_pctpresent);test_reader_docker_hang_times_out(server that accepts and never answers;read()returns within ~timeout+1 s withcontainers is None). -
Step 2: run, expect FAIL.
-
Step 3: Implement. Reader failures per source are caught separately and yield
Nonefor 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 ServerViewwithname = "server",__init__(self, poller: Poller[Stats]);STALE_AFTER = 30.0seconds;frame_key = (now.second // 5, poller.version, is_stale);patchreturnsNone. -
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,
+Nfor the rest); top processes by CPU.containers is None-> the section readsNO DOCKER. AnyNonenumber shows--. Old stats (age >STALE_AFTER) keep the last numbers and show aSTARÉ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 fieldsNone,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 withcontainers=Nonevs 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), writedocs/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 commitfeat: 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 onfetch_weather(local_now), interval900) and"server"(poller onStatsReader().read, interval5);make_view(name: str) -> ViewraisingUnknownView(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: callsfactory()until it returns, logging the first failure only, sleepingretry_sbetween tries; returnsNoneifrunning()turns falserunner.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; fullrenderpushed whenframe_keychanged, elsepatchonce per new second; a failed draw is retried on the next tick and, aftermax_failuresconsecutive failures, the exception is raised so Docker restarts and reopens the portrunner.idle_with_message(lcd, lines, *, running, sleep) -> None: drawsrender_error(lines)once, then waits untilrunning()is falsemain.pyreadsVIEW,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 callview.stop()andlcd.closeSerial(); sets up logging withforce=Trueas in the bus board.
-
Step 1: Write failing tests with a
FakeLcdrecordingDisplayPILImage(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(firstDisplayPILImageraises, second works);test_run_raises_after_max_failures;test_open_screen_retries_until_available(factory fails twice then works;sleepcalled twice with30.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 onUnknownViewcallidle_with_messagewith a message naming the bad value and the valid views (also logged); otherwiseview.start()thenrun. -
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
Dockerfileanddocker-compose.yml;docker compose configmust validate. - Step 2: Write
README.mdin the bus board's shape: what it is, develop/preview (pytest,python preview.py), how to switch views (editVIEW, commit, push, Deploy), adding a view (module +REGISTRYentry + README line), deployment steps (Coolify settings from Global Constraints), the Docker-socket andpid: hostsecurity note, "if something is wrong" (upside-down: flipSCREEN_ORIENTATIONtoREVERSE_LANDSCAPE; blank screen; badVIEW), config table, known limitations. - Step 3: Manual run on the server for verification:
rsyncthe project (not.git) to a scratch directory on the server viassh coolify,docker compose up --build -d. Confirm withdocker logsand by asking the owner to confirm the screen:VIEW=weathershows the live weather view with the correct time and ticking seconds. Then change toVIEW=server,up -d, confirm the server view with real container names. Then setVIEW=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. Checkgit statusis clean. - Step 5: Ask the owner before each of: creating the Gitea repo,
git push, configuring the Coolify application, deletingapod-testand~/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.