Files
2026-10-07 09:19:23 +02:00

61 KiB
Raw Permalink Blame History

Bus Departure Board 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: Show the next bus/trolleybus departures from Štípa,u potoka and Štípa,družstvo (lines 4, 5, 35, 36) on the Turing Smart Screen, driven by a Docker container on the home server.

Architecture: The container downloads four DSZO per-stop timetable pages (on start, then daily ~03:00), caches the raw HTML on a volume, parses them into departures, picks the right day-type column, and redraws a 480x320 board image once a minute. If there is nothing to show it falls back to the existing analog clock. Pure logic (timetable, schedule, store, board, app) is unit-tested on the Mac; only main.py touches the screen.

Tech Stack: Python 3.12, Pillow, pyserial + numpy (screen library, pinned commit), PyYAML, holidays (Czech state holidays), pytest, Docker Compose.

Spec: docs/superpowers/specs/2026-10-06-bus-board-design.md

All paths are relative to the project root (the bus-department-schedule directory). Run every command from that directory.

Global Constraints

  • Python 3.12; runtime dependencies only: pyserial~=3.5, Pillow>=11.0, numpy>=2.0, PyYAML>=6.0, holidays>=0.60. Dev: pytest>=8.
  • Time zone Europe/Prague. All datetimes in the code are naive Prague local time; never rely on the container's TZ.
  • Scheduled times only — no live delay data.
  • Parse result with zero departures is a failure; a failed or unparseable download never replaces a good cache.
  • Fetch on container start and daily at 03:00 local; retry every 15 min while the last attempt failed; at most 4 requests per refresh with the User-Agent bus-department-schedule/1.0 (personal home display; 4 requests/day).
  • Timetable is "stale" when any line's cache is missing or older than 3 days; the board then shows jízdní řád zastaralý.
  • Every departure is kept (footnote marks like v, A, z are stored, never displayed, never filtered).
  • Screen: 480x320 landscape, default orientation REVERSE_LANDSCAPE, device by /dev/serial/by-id/usb-2017-2-25_UsbMonitor_USB35INCHIPSV2-if00.
  • Board redraws once per minute; the clock fallback keeps its per-second dial.
  • All on-screen text Czech; Roboto fonts vendored in assets/fonts/.
  • Screen library stays pinned to commit 2b33ab4f00a096916dd6a1174441a53a7ec33b03.

Review Focus

Spec-implied failure modes, most likely first, each pinned by a test in the task that owns the code:

  1. Past the last bus of the day (e.g. 23:52): the board must list tomorrow's first departures marked zítra, never go empty. → Task 4 test_rolls_into_next_day_after_last_departure, Task 6 test_countdown_text.
  2. State holiday on a weekday (Wed 28.10.2026): must use the rest-day column, not the workday one. → Task 4 test_state_holiday_on_weekday_uses_rest_day_column.
  3. Special school-holiday dates (29–30.10.2026, 23.12.2026): the special column replaces the workday column on those dates only. → Task 3 test_special_date_replaces_workday_column / test_special_column_ignored_on_other_days, Task 4 test_real_special_date_includes_line35.
  4. DSZO page redesigned, empty, or the network down: cache is kept, the board keeps working. → Task 5 test_unparseable_page_does_not_replace_cache, test_failed_download_keeps_previous_cache, test_load_timetables_skips_corrupt_cache_file.
  5. Container runs in UTC (TZ missing): board times would be 1–2 h off. → Task 7 test_local_now_is_naive_prague_time.

Task 1: Repo scaffold, test setup, real-page fixtures

Files:

  • Create: .venv/ (ignored), pytest.ini, requirements-dev.txt, tests/helpers.py, tests/conftest.py, tests/test_fixtures.py, tests/fixtures/line4_u_potoka.html, tests/fixtures/line5_u_potoka.html, tests/fixtures/line35_druzstvo.html, tests/fixtures/line36_druzstvo.html, lines.yaml
  • Modify: requirements.txt, .gitignore, .dockerignore
  • Move: preview.png → docs/previews/clock.png

Interfaces:

  • Produces: tests.helpers.SOURCES, tests.helpers.FIXTURES, tests.helpers.fixture_html(name) -> str, tests.helpers.load_timetables() -> list[Timetable] (the last one is added in Task 2 once timetable.py exists), pytest fixture cz (a holidays.CZ()), constant tests.helpers.FONT_DIR.

  • Step 1: Initialise git and ignore generated files

git init -b main
cat > .gitignore <<'EOF'
__pycache__/
*.pyc
.env
.venv/
.pytest_cache/
EOF
printf '.git\n.venv\n.pytest_cache\n__pycache__/\n*.pyc\n.env\ntests\ndocs\nREADME.md\n' > .dockerignore
mkdir -p docs/previews && mv preview.png docs/previews/clock.png
  • Step 2: Dependencies and pytest config

requirements.txt becomes:

pyserial~=3.5
Pillow>=11.0
numpy>=2.0
PyYAML>=6.0
holidays>=0.60

requirements-dev.txt:

-r requirements.txt
pytest>=8

pytest.ini:

[pytest]
pythonpath = .
testpaths = tests
python3 -m venv .venv
.venv/bin/pip install -q -r requirements-dev.txt
.venv/bin/python -c "import holidays, yaml, PIL, pytest; print('deps ok')"

Expected: deps ok

  • Step 3: Download the four real timetable pages as fixtures
mkdir -p tests/fixtures
U=https://www.dszo.cz/jr/workhtml.php
curl -fsS -o tests/fixtures/line4_u_potoka.html   "$U?htmlfile=L2JhbmsxL3Ryb2xlamJ1c3kvMDRiXzIyLmh0bWw%3D&grafikon=eCxz"
curl -fsS -o tests/fixtures/line5_u_potoka.html   "$U?htmlfile=L2JhbmsxL3Ryb2xlamJ1c3kvMDVhXzAzLmh0bWw=&grafikon=eCxz"
curl -fsS -o tests/fixtures/line35_druzstvo.html  "$U?htmlfile=L2JhbmsxL2F1dG9idXN5LzM1Yl8wNi5odG1s&grafikon=eCxzLGw="
curl -fsS -o tests/fixtures/line36_druzstvo.html  "$U?htmlfile=L2JhbmsxL2F1dG9idXN5LzM2Yl8wNi5odG1s&grafikon=eCxzLGw="
ls -l tests/fixtures

Expected: four files, each roughly 10–17 KB. These are frozen snapshots of the pages as of 2026-10-06 (validity "od 1.10.2026"); tests assert against them, so never re-download them casually.

  • Step 4: Create lines.yaml
# One entry per line per stop. `url` is the DSZO per-stop timetable page.
lines:
  - line: "4"
    stop: "Štípa,u potoka"
    url: "https://www.dszo.cz/jr/workhtml.php?htmlfile=L2JhbmsxL3Ryb2xlamJ1c3kvMDRiXzIyLmh0bWw%3D&grafikon=eCxz"
  - line: "5"
    stop: "Štípa,u potoka"
    url: "https://www.dszo.cz/jr/workhtml.php?htmlfile=L2JhbmsxL3Ryb2xlamJ1c3kvMDVhXzAzLmh0bWw=&grafikon=eCxz"
  - line: "35"
    stop: "Štípa,družstvo"
    url: "https://www.dszo.cz/jr/workhtml.php?htmlfile=L2JhbmsxL2F1dG9idXN5LzM1Yl8wNi5odG1s&grafikon=eCxzLGw="
  - line: "36"
    stop: "Štípa,družstvo"
    url: "https://www.dszo.cz/jr/workhtml.php?htmlfile=L2JhbmsxL2F1dG9idXN5LzM2Yl8wNi5odG1s&grafikon=eCxzLGw="
  • Step 5: Test helpers and a smoke test (write the test first, see it fail)

tests/helpers.py:

"""Shared test data: the four frozen DSZO pages and where they came from."""
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
FIXTURES = Path(__file__).parent / "fixtures"
FONT_DIR = str(ROOT / "assets" / "fonts")

# (fixture file, line, stop) — same order as lines.yaml
SOURCES = [
    ("line4_u_potoka.html", "4", "Štípa,u potoka"),
    ("line5_u_potoka.html", "5", "Štípa,u potoka"),
    ("line35_druzstvo.html", "35", "Štípa,družstvo"),
    ("line36_druzstvo.html", "36", "Štípa,družstvo"),
]


def fixture_html(name: str) -> str:
    return (FIXTURES / name).read_text(encoding="utf-8")

tests/conftest.py:

import holidays
import pytest


@pytest.fixture
def cz():
    """Czech state holidays; supports `date in cz` for any year."""
    return holidays.CZ()

tests/test_fixtures.py:

import yaml

from tests.helpers import ROOT, SOURCES, fixture_html


def test_fixtures_are_dszo_stop_timetables():
    for name, line, stop in SOURCES:
        html = fixture_html(name)
        assert 'class="stop-timetable"' in html, name
        assert f'zast. {stop}' in html and f'linka "{line}"' in html, name


def test_lines_yaml_matches_fixture_sources():
    entries = yaml.safe_load((ROOT / "lines.yaml").read_text(encoding="utf-8"))["lines"]
    assert [(e["line"], e["stop"]) for e in entries] == [(l, s) for _, l, s in SOURCES]
  • Step 6: Run the tests

Run: .venv/bin/pytest -v Expected: 2 passed.

  • Step 7: Commit
git add -A
git commit -m "chore: scaffold repo, pytest, DSZO fixtures, clock container"

(The first commit also captures the existing clock container files, docs/superpowers/ spec and this plan.)


Task 2: Timetable parser

Files:

  • Create: timetable.py, tests/test_timetable.py
  • Modify: tests/helpers.py (add load_timetables)

Interfaces:

  • Produces (all in timetable.py):

    • constants KIND_WORKDAY = "workday", KIND_REST_DAY = "rest_day", KIND_SPECIAL = "special"
    • class ParseError(Exception)
    • @dataclass(frozen=True) Departure(line: str, stop: str, time: datetime.time, mark: str | None = None)
    • @dataclass(frozen=True) Column(label: str, kind: str, valid_from: date, dates: tuple[date, ...], departures: tuple[Departure, ...]) — dates is non-empty only for KIND_SPECIAL
    • @dataclass(frozen=True) Timetable(line: str, stop: str, columns: tuple[Column, ...])
    • parse_page(html: str, line: str, stop: str) -> Timetable — raises ParseError for anything that is not a DSZO stop timetable or has zero departures overall.
  • Produces (in tests/helpers.py): load_timetables() -> list[Timetable] parsing all four fixtures.

  • Step 1: Write the failing tests

tests/test_timetable.py:

from datetime import date, time

import pytest

from tests.helpers import fixture_html
from timetable import (
    KIND_REST_DAY,
    KIND_SPECIAL,
    KIND_WORKDAY,
    ParseError,
    parse_page,
)


def load(name, line, stop):
    return parse_page(fixture_html(name), line, stop)


@pytest.fixture(scope="module")
def line4():
    return load("line4_u_potoka.html", "4", "Štípa,u potoka")


def summary(timetable):
    return [(c.kind, c.valid_from, len(c.departures)) for c in timetable.columns]


def test_line4_columns(line4):
    assert summary(line4) == [
        (KIND_WORKDAY, date(2026, 10, 1), 36),
        (KIND_REST_DAY, date(2026, 10, 3), 29),
    ]


def test_line4_first_workday_departures(line4):
    deps = line4.columns[0].departures
    assert [d.time for d in deps[:3]] == [time(4, 16), time(4, 46), time(5, 32)]
    assert all(d.line == "4" and d.stop == "Štípa,u potoka" for d in deps)


def test_line4_footnote_mark_is_kept_not_dropped(line4):
    last = line4.columns[0].departures[-1]
    assert (last.time, last.mark) == (time(23, 6), "v")


def test_line5_counts_and_mark():
    t = load("line5_u_potoka.html", "5", "Štípa,u potoka")
    assert summary(t) == [
        (KIND_WORKDAY, date(2026, 10, 1), 16),
        (KIND_REST_DAY, date(2026, 10, 3), 14),
    ]
    marked = {(d.time, d.mark) for d in t.columns[0].departures if d.mark}
    assert (time(7, 16), "A") in marked


def test_line35_has_special_school_holiday_column():
    t = load("line35_druzstvo.html", "35", "Štípa,družstvo")
    assert summary(t) == [
        (KIND_WORKDAY, date(2026, 10, 1), 4),
        (KIND_REST_DAY, date(2026, 10, 3), 0),
        (KIND_SPECIAL, date(2026, 10, 29), 3),
    ]
    assert t.columns[2].dates == (date(2026, 10, 29), date(2026, 10, 30), date(2026, 12, 23))
    assert t.columns[0].dates == ()


def test_line36_counts():
    t = load("line36_druzstvo.html", "36", "Štípa,družstvo")
    assert [len(c.departures) for c in t.columns] == [4, 1, 3]


HEADER = '<table class="stop-timetable"><thead><tr><th>Hod.</th>{ths}</tr></thead><tbody>{rows}</tbody></table>'
WORKDAY_TH = "<th>Pracovní dny<br/>platnost od 1.10.2026</th>"


def test_zero_departures_is_a_parse_error():
    html = HEADER.format(
        ths=WORKDAY_TH, rows='<tr><td class="hour-cell">00</td><td class="minutes-cell"></td></tr>'
    )
    with pytest.raises(ParseError, match="no departures"):
        parse_page(html, "4", "X")


@pytest.mark.parametrize("html", ["", "<html>redesigned page</html>", "<table></table>"])
def test_unrecognised_page_is_a_parse_error(html):
    with pytest.raises(ParseError):
        parse_page(html, "4", "X")


def test_unknown_column_header_is_a_parse_error():
    html = HEADER.format(
        ths="<th>Něco nového<br/>platnost od 1.10.2026</th>",
        rows='<tr><td class="hour-cell">04</td><td class="minutes-cell">16 </td></tr>',
    )
    with pytest.raises(ParseError, match="unknown column"):
        parse_page(html, "4", "X")


def test_cell_count_mismatch_is_a_parse_error():
    html = HEADER.format(
        ths=WORKDAY_TH,
        rows='<tr><td class="hour-cell">04</td><td class="minutes-cell">16 </td><td class="minutes-cell">30 </td></tr>',
    )
    with pytest.raises(ParseError, match="cells"):
        parse_page(html, "4", "X")

Add to tests/helpers.py:

from timetable import Timetable, parse_page  # noqa: E402  (placed with the other imports)


def load_timetables() -> list[Timetable]:
    return [parse_page(fixture_html(name), line, stop) for name, line, stop in SOURCES]
  • Step 2: Run to verify failure

Run: .venv/bin/pytest tests/test_timetable.py -v Expected: collection error ModuleNotFoundError: No module named 'timetable'.

  • Step 3: Implement timetable.py
"""Parse a DSZO per-stop timetable page into departures."""
import re
from dataclasses import dataclass
from datetime import date, time

KIND_WORKDAY = "workday"
KIND_REST_DAY = "rest_day"
KIND_SPECIAL = "special"


class ParseError(Exception):
    """The page did not look like a DSZO stop timetable."""


@dataclass(frozen=True)
class Departure:
    line: str
    stop: str
    time: time
    mark: str | None = None  # footnote letter such as "v"; stored, not displayed


@dataclass(frozen=True)
class Column:
    label: str
    kind: str
    valid_from: date
    dates: tuple[date, ...]  # explicit dates, only for KIND_SPECIAL
    departures: tuple[Departure, ...]


@dataclass(frozen=True)
class Timetable:
    line: str
    stop: str
    columns: tuple[Column, ...]


_DATE_RE = re.compile(r"(\d{1,2})\.(?:\s*[–-]\s*(\d{1,2})\.)?(\d{1,2})\.(\d{4})")
_TAG_RE = re.compile(r"<[^>]+>")
_ROW_RE = re.compile(r'<td class="hour-cell">(\d\d)</td>(.*?)</tr>', re.S)
_CELL_RE = re.compile(r'<td class="minutes-cell">(.*?)</td>', re.S)
_MINUTE_RE = re.compile(r'(\d\d)(?:<span class="idx">(.*?)</span>)?')


def _text(html: str) -> str:
    return re.sub(r"\s+", " ", _TAG_RE.sub(" ", html)).strip()


def _dates_in(text: str) -> list[date]:
    """All dates in text; 'd1.–d2.m.yyyy' expands to every day of the range."""
    found: list[date] = []
    for d1, d2, month, year in _DATE_RE.findall(text):
        first, last = int(d1), int(d2 or d1)
        found += [date(int(year), int(month), d) for d in range(first, last + 1)]
    return found


def _column_header(label_html: str) -> tuple[str, str, date, tuple[date, ...]]:
    label = _text(label_html.replace("<br/>", " / "))
    try:
        dates = _dates_in(label)
    except ValueError as exc:  # e.g. 31.2.
        raise ParseError(f"invalid date in column header: {label!r}") from exc
    if not dates:
        raise ParseError(f"no validity date in column header: {label!r}")
    lowered = label.lower()
    if "prázdniny" in lowered:
        return label, KIND_SPECIAL, min(dates), tuple(dates)
    if lowered.startswith("dny pracovního klidu"):
        return label, KIND_REST_DAY, dates[0], ()
    if lowered.startswith("pracovní dny"):
        return label, KIND_WORKDAY, dates[0], ()
    raise ParseError(f"unknown column header: {label!r}")


def parse_page(html: str, line: str, stop: str) -> Timetable:
    headers = re.findall(r"<th>(.*?)</th>", html, re.S)
    if not headers or "Hod" not in headers[0]:
        raise ParseError("timetable header not found")
    specs = [_column_header(h) for h in headers[1:]]
    if not specs:
        raise ParseError("timetable has no columns")

    rows = _ROW_RE.findall(html)
    if not rows:
        raise ParseError("no timetable rows found")

    per_column: list[list[Departure]] = [[] for _ in specs]
    for hour, row_html in rows:
        cells = _CELL_RE.findall(row_html)
        if len(cells) != len(specs):
            raise ParseError(f"hour {hour}: {len(cells)} cells for {len(specs)} columns")
        for column, cell in zip(per_column, cells):
            for minute, mark in _MINUTE_RE.findall(cell):
                column.append(Departure(line, stop, time(int(hour), int(minute)), mark or None))

    if not any(per_column):
        raise ParseError("timetable contains no departures")

    columns = tuple(
        Column(label, kind, valid_from, dates, tuple(deps))
        for (label, kind, valid_from, dates), deps in zip(specs, per_column)
    )
    return Timetable(line, stop, columns)
  • Step 4: Run to verify pass

Run: .venv/bin/pytest -v Expected: all tests pass (2 from Task 1 + 12 here).

  • Step 5: Commit
git add timetable.py tests/test_timetable.py tests/helpers.py
git commit -m "feat: parse DSZO stop timetable pages"

Task 3: Choosing the timetable column (your function)

Files:

  • Create: schedule.py, tests/test_schedule.py

Interfaces:

  • Consumes: timetable.Column, KIND_* constants.
  • Produces (in schedule.py):
    • is_rest_day(day: date, state_holidays: Container[date]) -> bool — Saturday, Sunday or a state holiday.
    • select_column(columns: Sequence[Column], day: date, rest_day: bool) -> Column | None

Learning-mode step: select_column is a small piece of real judgment — what wins when a date is a special school-holiday date and a rest day, and what to do when a timetable has no column valid yet. The executing session asks you to write it (about 8 lines) after the tests below exist. A reference implementation follows, to use as a fallback or to compare against.

  • Step 1: Write the failing tests

tests/test_schedule.py:

from datetime import date

from schedule import is_rest_day, select_column
from timetable import KIND_REST_DAY, KIND_SPECIAL, KIND_WORKDAY, Column


def col(kind, valid_from, dates=()):
    return Column(label=f"{kind} {valid_from}", kind=kind, valid_from=valid_from, dates=tuple(dates), departures=())


WORK_OLD = col(KIND_WORKDAY, date(2026, 3, 1))
WORK_NEW = col(KIND_WORKDAY, date(2026, 10, 1))
REST = col(KIND_REST_DAY, date(2026, 10, 3))
SPECIAL = col(
    KIND_SPECIAL, date(2026, 10, 29), [date(2026, 10, 29), date(2026, 10, 30), date(2026, 12, 23)]
)


def test_is_rest_day(cz):
    assert not is_rest_day(date(2026, 10, 6), cz)  # Tuesday
    assert is_rest_day(date(2026, 10, 10), cz)  # Saturday
    assert is_rest_day(date(2026, 10, 11), cz)  # Sunday
    assert is_rest_day(date(2026, 10, 28), cz)  # Wednesday, Statehood Day
    assert is_rest_day(date(2026, 12, 24), cz)  # Thursday, Christmas Eve


def test_workday_uses_workday_column():
    assert select_column([WORK_NEW, REST], date(2026, 10, 6), rest_day=False) is WORK_NEW


def test_rest_day_uses_rest_column():
    assert select_column([WORK_NEW, REST], date(2026, 10, 10), rest_day=True) is REST


def test_latest_started_column_of_a_kind_wins():
    assert select_column([WORK_OLD, WORK_NEW], date(2026, 10, 6), rest_day=False) is WORK_NEW
    assert select_column([WORK_OLD, WORK_NEW], date(2026, 9, 15), rest_day=False) is WORK_OLD


def test_column_not_valid_yet_is_used_when_nothing_else_exists():
    assert select_column([WORK_NEW], date(2026, 9, 1), rest_day=False) is WORK_NEW
    assert select_column([WORK_NEW, REST], date(2026, 9, 27), rest_day=True) is REST


def test_special_date_replaces_workday_column():
    assert select_column([WORK_NEW, REST, SPECIAL], date(2026, 10, 29), rest_day=False) is SPECIAL
    assert select_column([WORK_NEW, REST, SPECIAL], date(2026, 12, 23), rest_day=False) is SPECIAL


def test_special_column_ignored_on_other_days():
    # 28.10. is a holiday right before the special dates: must use the rest column.
    assert select_column([WORK_NEW, REST, SPECIAL], date(2026, 10, 28), rest_day=True) is REST
    assert select_column([WORK_NEW, REST, SPECIAL], date(2026, 10, 31), rest_day=True) is REST
    assert select_column([WORK_NEW, REST, SPECIAL], date(2026, 11, 2), rest_day=False) is WORK_NEW


def test_special_date_beats_rest_day():
    # Default precedence (your call to change): a special date wins even on a rest day.
    assert select_column([WORK_NEW, REST, SPECIAL], date(2026, 10, 29), rest_day=True) is SPECIAL


def test_no_column_of_the_needed_kind_returns_none():
    assert select_column([WORK_NEW], date(2026, 10, 10), rest_day=True) is None
    assert select_column([], date(2026, 10, 6), rest_day=False) is None
  • Step 2: Run to verify failure

Run: .venv/bin/pytest tests/test_schedule.py -v Expected: ModuleNotFoundError: No module named 'schedule'.

  • Step 3: Create schedule.py with is_rest_day and the function stub
"""Pick the right timetable column for a day and list upcoming departures."""
from datetime import date
from typing import Container, Sequence

from timetable import KIND_REST_DAY, KIND_SPECIAL, KIND_WORKDAY, Column


def is_rest_day(day: date, state_holidays: Container[date]) -> bool:
    """Saturday, Sunday or a Czech state holiday."""
    return day.weekday() >= 5 or day in state_holidays


def select_column(columns: Sequence[Column], day: date, rest_day: bool) -> Column | None:
    """The column that applies on `day`, or None if the timetable has no usable column.

    Rules (see spec "Choosing the column"):
      1. a KIND_SPECIAL column whose `dates` contain `day` wins;
      2. otherwise rest days use KIND_REST_DAY columns, other days KIND_WORKDAY;
      3. among columns of that kind the one with the latest valid_from <= day;
         if none has started yet, the one with the earliest valid_from;
      4. no column of the needed kind -> None.
    """
    raise NotImplementedError("your turn")
  • Step 4: Ask the user to write select_column

Stop and ask the user to implement the body (about 8 lines) in schedule.py, explaining the trade-off: with a special date on a rest day, the default tests make the special column win; if the user prefers otherwise, they change test_special_date_beats_rest_day too. If the user declines, use this reference implementation:

    for column in columns:
        if column.kind == KIND_SPECIAL and day in column.dates:
            return column

    wanted = KIND_REST_DAY if rest_day else KIND_WORKDAY
    candidates = sorted((c for c in columns if c.kind == wanted), key=lambda c: c.valid_from)
    if not candidates:
        return None
    started = [c for c in candidates if c.valid_from <= day]
    return started[-1] if started else candidates[0]
  • Step 5: Run to verify pass

Run: .venv/bin/pytest tests/test_schedule.py -v Expected: 8 passed.

  • Step 6: Commit
git add schedule.py tests/test_schedule.py
git commit -m "feat: choose timetable column by day type and validity"

Task 4: Next departures

Files:

  • Modify: schedule.py, tests/test_schedule.py

Interfaces:

  • Consumes: select_column, is_rest_day, timetable.Timetable/Departure.

  • Produces (in schedule.py):

    • LOOKAHEAD_DAYS = 3
    • @dataclass(frozen=True) Upcoming(departure: Departure, when: datetime, minutes: int, next_day: bool) — minutes is whole minutes from now truncated to the minute (0 means leaving now); next_day is true when when.date() != now.date().
    • next_departures(timetables: Sequence[Timetable], now: datetime, count: int, state_holidays: Container[date]) -> list[Upcoming] — earliest first, ties broken by line; [] if nothing found within today + LOOKAHEAD_DAYS.
  • Step 1: Write the failing tests

Append to tests/test_schedule.py (add the new imports at the top of the file):

from datetime import datetime, time

from schedule import next_departures
from tests.helpers import load_timetables
from timetable import Departure, Timetable


def dep(line, stop, h, m):
    return Departure(line, stop, time(h, m))


def column(kind, valid_from, deps, dates=()):
    return Column(kind, kind, valid_from, tuple(dates), tuple(deps))


V = date(2026, 10, 1)
STOP_A, STOP_B = "U potoka", "Družstvo"
A = Timetable(
    "4",
    STOP_A,
    (
        column(KIND_WORKDAY, V, [dep("4", STOP_A, 10, 0), dep("4", STOP_A, 10, 30), dep("4", STOP_A, 23, 6)]),
        column(KIND_REST_DAY, V, [dep("4", STOP_A, 9, 15)]),
        column(KIND_SPECIAL, V, [dep("4", STOP_A, 6, 45)], dates=[date(2026, 10, 29)]),
    ),
)
B = Timetable("35", STOP_B, (column(KIND_WORKDAY, V, [dep("35", STOP_B, 10, 10)]),))
TUE_0950 = datetime(2026, 10, 6, 9, 50, 0)


def lines_and_times(upcoming):
    return [(u.departure.line, u.when.strftime("%H:%M")) for u in upcoming]


def test_merges_timetables_earliest_first(cz):
    up = next_departures([A, B], TUE_0950, 3, cz)
    assert lines_and_times(up) == [("4", "10:00"), ("35", "10:10"), ("4", "10:30")]


def test_minutes_until_departure(cz):
    first = next_departures([A, B], TUE_0950, 1, cz)[0]
    assert first.minutes == 10 and first.next_day is False


def test_departure_in_the_current_minute_is_now(cz):
    first = next_departures([A], datetime(2026, 10, 6, 10, 0, 40), 1, cz)[0]
    assert first.when == datetime(2026, 10, 6, 10, 0) and first.minutes == 0


def test_departed_bus_is_dropped(cz):
    first = next_departures([A], datetime(2026, 10, 6, 10, 1, 0), 1, cz)[0]
    assert first.when == datetime(2026, 10, 6, 10, 30)


def test_rolls_into_next_day_after_last_departure(cz):
    up = next_departures([A], datetime(2026, 10, 6, 23, 30), 2, cz)  # last bus today was 23:06
    assert [(u.when, u.next_day) for u in up] == [
        (datetime(2026, 10, 7, 10, 0), True),
        (datetime(2026, 10, 7, 10, 30), True),
    ]
    assert up[0].minutes == 630


def test_state_holiday_on_weekday_uses_rest_day_column(cz):
    first = next_departures([A], datetime(2026, 10, 28, 8, 0), 1, cz)[0]  # Wednesday, Statehood Day
    assert first.when == datetime(2026, 10, 28, 9, 15)


def test_saturday_uses_rest_day_column(cz):
    first = next_departures([A], datetime(2026, 10, 10, 8, 0), 1, cz)[0]
    assert first.when == datetime(2026, 10, 10, 9, 15)


def test_special_date_uses_special_column(cz):
    first = next_departures([A], datetime(2026, 10, 29, 6, 0), 1, cz)[0]
    assert first.when == datetime(2026, 10, 29, 6, 45)


def test_nothing_usable_returns_empty_list(cz):
    empty = Timetable("9", "X", ())
    assert next_departures([empty], TUE_0950, 3, cz) == []
    assert next_departures([], TUE_0950, 3, cz) == []


def test_real_timetables_in_the_afternoon(cz):
    up = next_departures(load_timetables(), datetime(2026, 10, 6, 13, 28, 20), 5, cz)
    assert lines_and_times(up) == [
        ("4", "13:33"),
        ("4", "13:53"),
        ("4", "14:08"),
        ("5", "14:25"),
        ("36", "14:27"),
    ]
    assert up[0].minutes == 5


def test_real_special_date_includes_line35(cz):
    first = next_departures(load_timetables(), datetime(2026, 10, 29, 5, 0), 1, cz)[0]
    assert (first.departure.line, first.departure.mark) == ("35", "v")
    assert first.when == datetime(2026, 10, 29, 5, 16)


def test_real_timetables_late_evening_show_tomorrow(cz):
    up = next_departures(load_timetables(), datetime(2026, 10, 6, 23, 52, 30), 3, cz)
    assert all(u.next_day for u in up)
    assert up[0].when == datetime(2026, 10, 7, 4, 16)
  • Step 2: Run to verify failure

Run: .venv/bin/pytest tests/test_schedule.py -v Expected: ImportError cannot import name 'next_departures'.

  • Step 3: Implement

Replace the import block at the top of schedule.py with:

from dataclasses import dataclass
from datetime import date, datetime, timedelta
from typing import Container, Sequence

from timetable import KIND_REST_DAY, KIND_SPECIAL, KIND_WORKDAY, Column, Departure, Timetable

LOOKAHEAD_DAYS = 3  # days after today we search before giving up

and append to the end of the file:

@dataclass(frozen=True)
class Upcoming:
    departure: Departure
    when: datetime
    minutes: int  # whole minutes from now; 0 means "leaving now"
    next_day: bool  # departs on a later calendar day than now


def next_departures(
    timetables: Sequence[Timetable], now: datetime, count: int, state_holidays: Container[date]
) -> list[Upcoming]:
    """The next `count` departures at or after `now` (minute precision), earliest first."""
    start = now.replace(second=0, microsecond=0)
    found: list[Upcoming] = []
    for offset in range(LOOKAHEAD_DAYS + 1):
        day = start.date() + timedelta(days=offset)
        rest = is_rest_day(day, state_holidays)
        for timetable in timetables:
            column = select_column(timetable.columns, day, rest)
            if column is None:
                continue
            for dep in column.departures:
                when = datetime.combine(day, dep.time)
                if when >= start:
                    minutes = int((when - start).total_seconds() // 60)
                    found.append(Upcoming(dep, when, minutes, day != now.date()))
        if len(found) >= count:
            break
    found.sort(key=lambda u: (u.when, u.departure.line))
    return found[:count]
  • Step 4: Run to verify pass

Run: .venv/bin/pytest -v Expected: all pass.

  • Step 5: Commit
git add schedule.py tests/test_schedule.py
git commit -m "feat: list next departures across stops with day rollover"

Task 5: Downloading and caching timetables

Files:

  • Create: store.py, tests/test_store.py

Interfaces:

  • Consumes: timetable.parse_page, ParseError, Timetable; lines.yaml.

  • Produces (in store.py):

    • @dataclass(frozen=True) LineConfig(line: str, stop: str, url: str) with property label -> f"{line} {stop}"
    • @dataclass RefreshReport(updated: list[str], failed: dict[str, str]) (keys/values are label / error text)
    • load_lines(path) -> list[LineConfig]
    • fetch_page(url: str, timeout: float = 20.0) -> str
    • cache_path(data_dir, cfg: LineConfig) -> Path
    • refresh(lines, data_dir, fetch=fetch_page, now: datetime | None = None) -> RefreshReport
    • load_timetables(lines, data_dir) -> list[Timetable] (skips lines with no usable cache)
    • is_stale(lines, data_dir, now: datetime, max_age: timedelta = MAX_AGE) -> bool
  • Step 1: Write the failing tests

tests/test_store.py:

from datetime import datetime, timedelta

import pytest

import store
from tests.helpers import ROOT, fixture_html

LINE4 = store.LineConfig("4", "Štípa,u potoka", "https://example.test/4")
NOW = datetime(2026, 10, 6, 12, 0)
EMPTY_TABLE = (
    '<table><thead><tr><th>Hod.</th><th>Pracovní dny<br/>platnost od 1.10.2026</th></tr></thead>'
    '<tbody><tr><td class="hour-cell">00</td><td class="minutes-cell"></td></tr></tbody></table>'
)


def good_page(url):
    return fixture_html("line4_u_potoka.html")


def test_refresh_stores_page_and_load_parses_it(tmp_path):
    report = store.refresh([LINE4], tmp_path, fetch=good_page, now=NOW)
    assert report.updated == [LINE4.label] and report.failed == {}
    [timetable] = store.load_timetables([LINE4], tmp_path)
    assert timetable.line == "4" and len(timetable.columns[0].departures) == 36


def test_failed_download_keeps_previous_cache(tmp_path):
    store.refresh([LINE4], tmp_path, fetch=good_page, now=NOW)

    def network_down(url):
        raise OSError("network down")

    report = store.refresh([LINE4], tmp_path, fetch=network_down, now=NOW + timedelta(days=1))
    assert "network down" in report.failed[LINE4.label]
    assert len(store.load_timetables([LINE4], tmp_path)[0].columns[0].departures) == 36
    # the failed attempt must not make the old cache look fresh
    assert store.is_stale([LINE4], tmp_path, NOW + timedelta(days=3, hours=1)) is True


@pytest.mark.parametrize("html", ["<html>redesigned page</html>", EMPTY_TABLE, ""])
def test_unparseable_page_does_not_replace_cache(tmp_path, html):
    store.refresh([LINE4], tmp_path, fetch=good_page, now=NOW)
    report = store.refresh([LINE4], tmp_path, fetch=lambda url: html, now=NOW + timedelta(days=1))
    assert LINE4.label in report.failed and report.updated == []
    assert len(store.load_timetables([LINE4], tmp_path)[0].columns[0].departures) == 36


def test_refresh_continues_after_one_line_fails(tmp_path):
    other = store.LineConfig("5", "Štípa,u potoka", "https://example.test/5")

    def fetch(url):
        if url.endswith("/4"):
            raise OSError("boom")
        return fixture_html("line5_u_potoka.html")

    report = store.refresh([LINE4, other], tmp_path, fetch=fetch, now=NOW)
    assert report.updated == [other.label] and list(report.failed) == [LINE4.label]


def test_load_timetables_skips_missing_and_corrupt_cache(tmp_path):
    assert store.load_timetables([LINE4], tmp_path) == []  # nothing cached yet
    store.cache_path(tmp_path, LINE4).write_text("<html>junk</html>", encoding="utf-8")
    assert store.load_timetables([LINE4], tmp_path) == []


def test_is_stale(tmp_path):
    assert store.is_stale([LINE4], tmp_path, NOW) is True  # never fetched
    store.refresh([LINE4], tmp_path, fetch=good_page, now=NOW)
    assert store.is_stale([LINE4], tmp_path, NOW + timedelta(days=2, hours=23)) is False
    assert store.is_stale([LINE4], tmp_path, NOW + timedelta(days=3, hours=1)) is True


def test_load_lines_reads_yaml(tmp_path):
    path = tmp_path / "lines.yaml"
    path.write_text('lines:\n  - line: "4"\n    stop: "Štípa,u potoka"\n    url: "https://x.test/4"\n', encoding="utf-8")
    assert store.load_lines(path) == [store.LineConfig("4", "Štípa,u potoka", "https://x.test/4")]


def test_repo_lines_yaml_lists_the_four_lines():
    labels = [c.label for c in store.load_lines(ROOT / "lines.yaml")]
    assert labels == ["4 Štípa,u potoka", "5 Štípa,u potoka", "35 Štípa,družstvo", "36 Štípa,družstvo"]
  • Step 2: Run to verify failure

Run: .venv/bin/pytest tests/test_store.py -v Expected: ModuleNotFoundError: No module named 'store'.

  • Step 3: Implement store.py
"""Download DSZO timetable pages, cache them on disk and load them back."""
import hashlib
import json
import logging
import os
import urllib.request
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path

import yaml

from timetable import ParseError, Timetable, parse_page

log = logging.getLogger(__name__)

USER_AGENT = "bus-department-schedule/1.0 (personal home display; 4 requests/day)"
MAX_AGE = timedelta(days=3)
FETCHED_FILE = "fetched.json"


@dataclass(frozen=True)
class LineConfig:
    line: str
    stop: str
    url: str

    @property
    def label(self) -> str:
        return f"{self.line} {self.stop}"


@dataclass
class RefreshReport:
    updated: list[str] = field(default_factory=list)
    failed: dict[str, str] = field(default_factory=dict)


def load_lines(path) -> list[LineConfig]:
    data = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
    return [LineConfig(str(e["line"]), e["stop"], e["url"]) for e in data["lines"]]


def fetch_page(url: str, timeout: float = 20.0) -> str:
    request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
    with urllib.request.urlopen(request, timeout=timeout) as response:
        return response.read().decode("utf-8")


def cache_path(data_dir, cfg: LineConfig) -> Path:
    digest = hashlib.sha1(cfg.url.encode("utf-8")).hexdigest()[:10]
    return Path(data_dir) / f"line{cfg.line}-{digest}.html"


def _read_fetched(data_dir: Path) -> dict[str, str]:
    try:
        return json.loads((data_dir / FETCHED_FILE).read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return {}


def _write_atomic(path: Path, text: str) -> None:
    tmp = path.with_name(path.name + ".tmp")
    tmp.write_text(text, encoding="utf-8")
    os.replace(tmp, path)


def refresh(lines, data_dir, fetch=fetch_page, now: datetime | None = None) -> RefreshReport:
    """Download every line; only a page that parses replaces the cached copy."""
    data_dir = Path(data_dir)
    data_dir.mkdir(parents=True, exist_ok=True)
    now = now or datetime.now()
    fetched = _read_fetched(data_dir)
    report = RefreshReport()
    for cfg in lines:
        try:
            html = fetch(cfg.url)
            parse_page(html, cfg.line, cfg.stop)  # validate before touching the cache
        except Exception as exc:  # network, HTTP, decoding and ParseError all mean "keep old cache"
            log.warning("refresh failed for %s: %s", cfg.label, exc)
            report.failed[cfg.label] = str(exc)
            continue
        _write_atomic(cache_path(data_dir, cfg), html)
        fetched[cfg.label] = now.isoformat(timespec="seconds")
        report.updated.append(cfg.label)
    _write_atomic(data_dir / FETCHED_FILE, json.dumps(fetched, ensure_ascii=False, indent=2))
    return report


def load_timetables(lines, data_dir) -> list[Timetable]:
    """Parse every cached page; lines without a usable cache are skipped."""
    timetables = []
    for cfg in lines:
        try:
            html = cache_path(data_dir, cfg).read_text(encoding="utf-8")
            timetables.append(parse_page(html, cfg.line, cfg.stop))
        except (OSError, ValueError, ParseError) as exc:
            log.warning("no usable cache for %s: %s", cfg.label, exc)
    return timetables


def is_stale(lines, data_dir, now: datetime, max_age: timedelta = MAX_AGE) -> bool:
    """True if any line was never fetched or its last good fetch is older than max_age."""
    fetched = _read_fetched(Path(data_dir))
    for cfg in lines:
        try:
            when = datetime.fromisoformat(fetched[cfg.label])
        except (KeyError, ValueError):
            return True
        if now - when > max_age:
            return True
    return False
  • Step 4: Run to verify pass

Run: .venv/bin/pytest -v Expected: all pass.

  • Step 5: Check the real site once (read-only, 4 requests)
.venv/bin/python - <<'EOF'
import tempfile
import store
lines = store.load_lines("lines.yaml")
with tempfile.TemporaryDirectory() as d:
    report = store.refresh(lines, d)
    print("updated:", report.updated)
    print("failed:", report.failed)
    print([len(t.columns[0].departures) for t in store.load_timetables(lines, d)])
EOF

Expected: all four lines in updated, failed: {}, and four non-zero counts. If a page changed since the fixtures were taken, report it instead of "fixing" tests.

  • Step 6: Commit
git add store.py tests/test_store.py
git commit -m "feat: download, validate and cache timetable pages"

Task 6: Board image, vendored fonts, design preview

Files:

  • Create: board.py, tests/test_board.py, tests/test_render.py, preview_board.py, assets/fonts/Roboto-Light.ttf, assets/fonts/Roboto-Regular.ttf, assets/fonts/Roboto-Medium.ttf, assets/fonts/LICENSE.txt, docs/previews/board.png (generated)
  • Modify: render.py (load_fonts takes a font directory)

Interfaces:

  • Consumes: schedule.Upcoming.

  • Produces:

    • board.load_fonts(font_dir: str) -> dict, render.load_fonts(font_dir: str) -> dict (same directory argument)
    • board.render_board(upcoming: list[Upcoming], now: datetime, fonts: dict, stale: bool = False) -> PIL.Image.Image (480x320 RGB; the first item is the big "next bus" block, the following board.ROWS (=4) are rows)
    • board.countdown_text(u: Upcoming) -> str, board.hero_text(u: Upcoming) -> str
    • constants board.W, board.H, board.BG, board.ACCENT, board.ROWS
  • Step 1: Vendor the fonts

mkdir -p assets/fonts
B=https://raw.githubusercontent.com/mathoudebine/turing-smart-screen-python/2b33ab4f00a096916dd6a1174441a53a7ec33b03/res/fonts/roboto
for f in Roboto-Light.ttf Roboto-Regular.ttf Roboto-Medium.ttf LICENSE.txt; do curl -fsS -o assets/fonts/$f $B/$f; done
ls -l assets/fonts

Expected: three .ttf files and LICENSE.txt.

  • Step 2: Write the failing tests

tests/test_render.py:

from datetime import datetime

import render
from tests.helpers import FONT_DIR


def test_clock_images_have_expected_sizes():
    fonts = render.load_fonts(FONT_DIR)
    now = datetime(2026, 10, 6, 22, 47, 12)
    assert render.render_dial(now).size == (render.DIAL_W, render.H)
    assert render.render_info(now, fonts).size == (render.INFO_W, render.H)
    assert render.render_frame(now, fonts).size == (480, 320)

tests/test_board.py:

from datetime import datetime, time

import pytest
from PIL import Image

import board
from schedule import Upcoming
from tests.helpers import FONT_DIR
from timetable import Departure

NOW = datetime(2026, 10, 6, 13, 28, 20)


def up(line, stop, h, m, minutes, next_day=False):
    return Upcoming(Departure(line, stop, time(h, m)), datetime(2026, 10, 6, h, m), minutes, next_day)


FIVE = [
    up("4", "Štípa,u potoka", 13, 33, 5),
    up("4", "Štípa,u potoka", 13, 53, 25),
    up("4", "Štípa,u potoka", 14, 8, 40),
    up("5", "Štípa,u potoka", 14, 25, 57),
    up("36", "Štípa,družstvo", 14, 27, 59),
]


@pytest.fixture(scope="module")
def fonts():
    return board.load_fonts(FONT_DIR)


@pytest.mark.parametrize(
    "minutes, next_day, countdown, hero",
    [
        (0, False, "teď", "teď"),
        (7, False, "za 7 min", "7 min"),
        (59, False, "za 59 min", "59 min"),
        (60, False, "za 1 h 00 min", "1 h 00"),
        (76, False, "za 1 h 16 min", "1 h 16"),
        (264, True, "zítra", "zítra"),
    ],
)
def test_countdown_text(minutes, next_day, countdown, hero):
    u = up("4", "Štípa,u potoka", 13, 33, minutes, next_day)
    assert board.countdown_text(u) == countdown
    assert board.hero_text(u) == hero


def test_board_has_screen_size(fonts):
    assert board.render_board(FIVE, NOW, fonts).size == (480, 320)


def test_board_marks_the_next_bus_with_accent_badge(fonts):
    img = board.render_board(FIVE, NOW, fonts)
    assert img.getpixel((30, 30)) == board.ACCENT


def test_empty_board_shows_message_not_badge(fonts):
    img = board.render_board([], NOW, fonts)
    assert img.size == (480, 320)
    assert img.getpixel((30, 30)) == board.BG
    blank = Image.new("RGB", (board.W, board.H), board.BG)
    assert img.tobytes() != blank.tobytes()  # the "Žádné odjezdy" text was drawn


def test_single_departure_and_overflow_do_not_crash(fonts):
    assert board.render_board(FIVE[:1], NOW, fonts).size == (480, 320)
    many = FIVE * 3  # more than the board can show
    assert board.render_board(many, NOW, fonts).size == (480, 320)


def test_stale_marker_changes_the_image(fonts):
    fresh = board.render_board(FIVE, NOW, fonts, stale=False).tobytes()
    stale = board.render_board(FIVE, NOW, fonts, stale=True).tobytes()
    assert fresh != stale


def test_long_stop_name_does_not_crash(fonts):
    long = [up("4", "Zlín,Lešná,ZOO – velmi dlouhý název zastávky", 13, 33, 5)] * 2
    assert board.render_board(long, NOW, fonts).size == (480, 320)
  • Step 3: Run to verify failure

Run: .venv/bin/pytest tests/test_board.py tests/test_render.py -v Expected: ModuleNotFoundError: No module named 'board', and for tests/test_render.py an OSError (cannot open resource) because the old render.load_fonts looks in the screen library's res/fonts tree.

  • Step 4: Update render.load_fonts to take a font directory

In render.py, replace the whole load_fonts function with:

def load_fonts(font_dir: str) -> dict:
    def f(name: str, size: int) -> ImageFont.FreeTypeFont:
        return ImageFont.truetype(f"{font_dir}/{name}", size)

    return {
        "time": f("Roboto-Light.ttf", 56),
        "weekday": f("Roboto-Medium.ttf", 24),
        "date": f("Roboto-Regular.ttf", 28),
        "year": f("Roboto-Light.ttf", 22),
    }
  • Step 5: Implement board.py
"""Draw the departure board (480x320 landscape)."""
from datetime import datetime

from PIL import Image, ImageDraw, ImageFont

from schedule import Upcoming

W, H = 480, 320
BG = (9, 11, 16)
RING = (44, 52, 70)
ACCENT = (255, 112, 67)
TEXT = (245, 247, 252)
TEXT_DIM = (140, 148, 165)

ROWS = 4  # departures listed under the big "next bus" block
ROW_TOP, ROW_H = 144, 38
HERO_DIVIDER_Y = 134


def load_fonts(font_dir: str) -> dict:
    def f(name: str, size: int) -> ImageFont.FreeTypeFont:
        return ImageFont.truetype(f"{font_dir}/{name}", size)

    return {
        "hero": f("Roboto-Light.ttf", 58),
        "hero_stop": f("Roboto-Medium.ttf", 24),
        "hero_small": f("Roboto-Regular.ttf", 20),
        "clock": f("Roboto-Regular.ttf", 22),
        "badge_big": f("Roboto-Medium.ttf", 38),
        "badge": f("Roboto-Medium.ttf", 20),
        "row": f("Roboto-Regular.ttf", 22),
        "row_time": f("Roboto-Medium.ttf", 24),
        "row_cd": f("Roboto-Regular.ttf", 20),
    }


def countdown_text(u: Upcoming) -> str:
    """Czech countdown for a list row: 'teď', 'za 7 min', 'za 1 h 16 min' or 'zítra'."""
    if u.next_day:
        return "zítra"
    if u.minutes == 0:
        return "teď"
    if u.minutes < 60:
        return f"za {u.minutes} min"
    return f"za {u.minutes // 60} h {u.minutes % 60:02d} min"


def hero_text(u: Upcoming) -> str:
    """The big countdown for the next bus."""
    if u.next_day:
        return "zítra"
    if u.minutes == 0:
        return "teď"
    if u.minutes < 60:
        return f"{u.minutes} min"
    return f"{u.minutes // 60} h {u.minutes % 60:02d}"


def _badge(d: ImageDraw.ImageDraw, box, line: str, font, fill, text_fill) -> None:
    d.rounded_rectangle(box, radius=8, fill=fill)
    d.text(((box[0] + box[2]) / 2, (box[1] + box[3]) / 2), line, font=font, fill=text_fill, anchor="mm")


def render_board(upcoming: list[Upcoming], now: datetime, fonts: dict, stale: bool = False) -> Image.Image:
    img = Image.new("RGB", (W, H), BG)
    d = ImageDraw.Draw(img)
    d.text((W - 16, 24), now.strftime("%H:%M"), font=fonts["clock"], fill=TEXT_DIM, anchor="rm")

    if not upcoming:
        d.text((W // 2, H // 2), "Žádné odjezdy", font=fonts["hero_stop"], fill=TEXT_DIM, anchor="mm")
        return img

    first = upcoming[0]
    _badge(d, (16, 20, 96, 100), first.departure.line, fonts["badge_big"], ACCENT, BG)
    d.text((112, 34), first.departure.stop, font=fonts["hero_stop"], fill=TEXT, anchor="lm")
    d.text((112, 82), hero_text(first), font=fonts["hero"], fill=TEXT, anchor="lm")
    d.text((W - 16, 100), f"odj. {first.departure.time:%H:%M}", font=fonts["hero_small"], fill=ACCENT, anchor="rm")

    d.line([(16, HERO_DIVIDER_Y), (W - 16, HERO_DIVIDER_Y)], fill=RING, width=2)

    for i, u in enumerate(upcoming[1 : ROWS + 1]):
        y = ROW_TOP + i * ROW_H
        mid = y + ROW_H // 2
        _badge(d, (16, y + 3, 62, y + ROW_H - 3), u.departure.line, fonts["badge"], RING, TEXT)
        d.text((76, mid), u.departure.stop, font=fonts["row"], fill=TEXT, anchor="lm")
        d.text((338, mid), f"{u.departure.time:%H:%M}", font=fonts["row_time"], fill=TEXT, anchor="rm")
        d.text((W - 16, mid), countdown_text(u), font=fonts["row_cd"], fill=TEXT_DIM, anchor="rm")

    if stale:
        d.text((16, H - 12), "jízdní řád zastaralý", font=fonts["hero_small"], fill=ACCENT, anchor="lm")
    return img
  • Step 6: Run to verify pass

Run: .venv/bin/pytest -v Expected: all pass.

  • Step 7: Generate the preview and get the user's approval

preview_board.py:

"""Render sample boards from the frozen fixtures to docs/previews/board.png (no screen needed)."""
from datetime import datetime

import holidays
from PIL import Image

import board
from schedule import next_departures
from tests.helpers import FONT_DIR, ROOT, load_timetables

SAMPLES = [
    (datetime(2026, 10, 6, 13, 28, 20), False),  # afternoon
    (datetime(2026, 10, 6, 23, 52, 30), True),  # after the last bus, stale marker
    (datetime(2026, 10, 6, 14, 47, 50), False),  # next bus in 1 minute
]


def main() -> None:
    fonts = board.load_fonts(FONT_DIR)
    timetables = load_timetables()
    state_holidays = holidays.CZ()
    sheet = Image.new("RGB", (board.W * len(SAMPLES) + 20 * (len(SAMPLES) - 1), board.H), (40, 40, 40))
    for i, (now, stale) in enumerate(SAMPLES):
        upcoming = next_departures(timetables, now, board.ROWS + 1, state_holidays)
        sheet.paste(board.render_board(upcoming, now, fonts, stale), (i * (board.W + 20), 0))
    out = ROOT / "docs" / "previews" / "board.png"
    sheet.save(out)
    print(out)


if __name__ == "__main__":
    main()
.venv/bin/python preview_board.py && open docs/previews/board.png

Ask the user whether the layout is approved. Tweaks (colours, sizes, wording) are changes to constants in board.py; re-run the command and the tests. Do not continue to Task 7 until the user approves the preview.

  • Step 8: Commit
git add board.py render.py preview_board.py assets tests/test_board.py tests/test_render.py docs/previews/board.png
git commit -m "feat: departure board image and vendored Roboto fonts"

Task 7: Wire it together, deploy, verify on the screen

Files:

  • Create: app.py, main.py, tests/test_app.py
  • Delete: clock.py
  • Modify: Dockerfile, docker-compose.yml, README.md

Interfaces:

  • Consumes: store, schedule.next_departures, board, render.

  • Produces (in app.py):

    • DEFAULT_TZ = "Europe/Prague", REFRESH_HOUR = 3, RETRY = timedelta(minutes=15)
    • local_now(tz_name: str = DEFAULT_TZ) -> datetime (naive local time in that zone)
    • refresh_due(last_attempt: datetime | None, now: datetime, last_ok: bool) -> bool
    • board_image(timetables, now, fonts, stale, state_holidays) -> PIL.Image.Image | None (None means "nothing to show, use the clock")
  • Step 1: Write the failing tests

tests/test_app.py:

import os
import time as time_module
from datetime import datetime, timezone

import app
import board
from tests.helpers import FONT_DIR, load_timetables


def test_refresh_due_on_first_run():
    assert app.refresh_due(None, datetime(2026, 10, 6, 12, 0), last_ok=True) is True


def test_refresh_due_once_after_three_am():
    last = datetime(2026, 10, 6, 10, 0)
    assert app.refresh_due(last, datetime(2026, 10, 6, 23, 59), last_ok=True) is False
    assert app.refresh_due(last, datetime(2026, 10, 7, 2, 59), last_ok=True) is False
    assert app.refresh_due(last, datetime(2026, 10, 7, 3, 0), last_ok=True) is True
    after = datetime(2026, 10, 7, 3, 0, 5)  # refreshed right at 03:00
    assert app.refresh_due(after, datetime(2026, 10, 7, 3, 30), last_ok=True) is False


def test_refresh_retries_every_fifteen_minutes_after_a_failure():
    last = datetime(2026, 10, 6, 12, 0)
    assert app.refresh_due(last, datetime(2026, 10, 6, 12, 14), last_ok=False) is False
    assert app.refresh_due(last, datetime(2026, 10, 6, 12, 15), last_ok=False) is True


def test_local_now_is_naive_prague_time(monkeypatch):
    monkeypatch.setenv("TZ", "UTC")  # a container without a proper TZ
    time_module.tzset()
    try:
        now = app.local_now("Europe/Prague")
        utc = datetime.now(timezone.utc).replace(tzinfo=None)
        assert now.tzinfo is None
        assert 3500 < (now - utc).total_seconds() < 7300  # Prague is UTC+1 or UTC+2
    finally:
        monkeypatch.undo()
        time_module.tzset()


def test_board_image_is_none_without_timetables(cz):
    fonts = board.load_fonts(FONT_DIR)
    assert app.board_image([], datetime(2026, 10, 6, 13, 0), fonts, False, cz) is None


def test_board_image_renders_real_timetables(cz):
    fonts = board.load_fonts(FONT_DIR)
    img = app.board_image(load_timetables(), datetime(2026, 10, 6, 13, 28, 20), fonts, False, cz)
    assert img is not None and img.size == (480, 320)
  • Step 2: Run to verify failure

Run: .venv/bin/pytest tests/test_app.py -v Expected: ModuleNotFoundError: No module named 'app'.

  • Step 3: Implement app.py
"""Testable glue between timetables, schedule and the board (no screen, no network)."""
from datetime import date, datetime, timedelta
from typing import Container, Sequence
from zoneinfo import ZoneInfo

from PIL import Image

import board
from schedule import next_departures
from timetable import Timetable

DEFAULT_TZ = "Europe/Prague"
REFRESH_HOUR = 3
RETRY = timedelta(minutes=15)


def local_now(tz_name: str = DEFAULT_TZ) -> datetime:
    """Naive wall-clock time in `tz_name`, independent of the container's own TZ."""
    return datetime.now(ZoneInfo(tz_name)).replace(tzinfo=None)


def refresh_due(last_attempt: datetime | None, now: datetime, last_ok: bool) -> bool:
    """True on the first call, 15 min after a failed refresh, and once after each 03:00."""
    if last_attempt is None:
        return True
    if not last_ok:
        return now - last_attempt >= RETRY
    today_refresh = now.replace(hour=REFRESH_HOUR, minute=0, second=0, microsecond=0)
    return last_attempt < today_refresh <= now


def board_image(
    timetables: Sequence[Timetable],
    now: datetime,
    fonts: dict,
    stale: bool,
    state_holidays: Container[date],
) -> Image.Image | None:
    """The board for `now`, or None when there is nothing to show (caller shows the clock)."""
    upcoming = next_departures(timetables, now, board.ROWS + 1, state_holidays)
    if not upcoming:
        return None
    return board.render_board(upcoming, now, fonts, stale)
  • Step 4: Run to verify pass

Run: .venv/bin/pytest -v Expected: all pass.

  • Step 5: Write main.py (replaces clock.py) — hardware entry point, verified on the device in Step 8
"""Container entry point: keep timetables fresh and show the departure board.

Falls back to the analog clock when there is nothing to show.
"""
import logging
import os
import signal
import sys
import time
from pathlib import Path

LIB = os.environ.get("LCD_LIB_PATH", "/opt/lcd")
sys.path.insert(0, LIB)

import holidays  # noqa: E402
from PIL import Image  # noqa: E402

import app  # noqa: E402
import board  # noqa: E402
import render  # noqa: E402
import store  # noqa: E402
from library.lcd.lcd_comm import Orientation  # noqa: E402
from library.lcd.lcd_comm_rev_a import LcdCommRevA  # noqa: E402

# force=True: the screen library configures logging at import, which would swallow ours.
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", force=True)
log = logging.getLogger("main")

DEVICE = os.environ.get("SCREEN_DEVICE", "AUTO")
ORIENTATION = Orientation[os.environ.get("SCREEN_ORIENTATION", "REVERSE_LANDSCAPE")]
BRIGHTNESS = int(os.environ.get("SCREEN_BRIGHTNESS", "50"))
TZ = os.environ.get("TZ", app.DEFAULT_TZ)
DATA_DIR = Path(os.environ.get("DATA_DIR", "/data"))
LINES_FILE = Path(os.environ.get("LINES_FILE", "/app/lines.yaml"))
FONT_DIR = str(Path(__file__).parent / "assets" / "fonts")


def main() -> None:
    lines = store.load_lines(LINES_FILE)
    state_holidays = holidays.CZ()
    board_fonts = board.load_fonts(FONT_DIR)
    clock_fonts = render.load_fonts(FONT_DIR)

    log.info("Opening display on %s (%s), time zone %s", DEVICE, ORIENTATION.name, TZ)
    lcd = LcdCommRevA(com_port=DEVICE) if DEVICE != "AUTO" else LcdCommRevA()
    lcd.InitializeComm()
    lcd.SetOrientation(ORIENTATION)
    lcd.SetBrightness(BRIGHTNESS)

    running = True

    def stop(*_):
        nonlocal running
        running = False

    signal.signal(signal.SIGTERM, stop)
    signal.signal(signal.SIGINT, stop)

    last_attempt = None
    last_ok = True
    timetables = []
    stale = False
    mode = None  # "board" or "clock"
    last_minute = last_second = None

    while running:
        now = app.local_now(TZ)

        if app.refresh_due(last_attempt, now, last_ok):
            report = store.refresh(lines, DATA_DIR, now=now)
            last_attempt, last_ok = now, not report.failed
            timetables = store.load_timetables(lines, DATA_DIR)
            stale = store.is_stale(lines, DATA_DIR, now)
            log.info("refresh: %d updated, failed=%s, stale=%s", len(report.updated), report.failed, stale)
            last_minute = None  # redraw straight away

        if now.second != last_second:
            last_second = now.second
            if now.minute != last_minute:
                last_minute = now.minute
                image = app.board_image(timetables, now, board_fonts, stale, state_holidays)
                new_mode = "board" if image is not None else "clock"
                if new_mode != mode:
                    log.info("showing %s", new_mode)
                    lcd.DisplayPILImage(Image.new("RGB", (board.W, board.H), board.BG), 0, 0)
                    mode = new_mode
                if mode == "board":
                    lcd.DisplayPILImage(image, 0, 0)
                else:
                    lcd.DisplayPILImage(render.render_info(now, clock_fonts), render.DIAL_W, 0)
            if mode == "clock":
                lcd.DisplayPILImage(render.render_dial(now), 0, 0)
        time.sleep(0.05)

    lcd.closeSerial()
    log.info("Stopped")


if __name__ == "__main__":
    main()
git rm clock.py
python3 -m py_compile main.py && echo syntax-ok

Expected: syntax-ok (full import needs the screen library, which only exists in the container).

  • Step 6: Update Dockerfile and docker-compose.yml

Dockerfile:

FROM python:3.12-slim

# Pinned commit of the Turing Smart Screen library (we only need library/).
ARG LCD_COMMIT=2b33ab4f00a096916dd6a1174441a53a7ec33b03

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

ADD https://github.com/mathoudebine/turing-smart-screen-python/archive/${LCD_COMMIT}.tar.gz /tmp/lcd.tar.gz
RUN mkdir -p /opt/lcd \
 && tar -xzf /tmp/lcd.tar.gz -C /opt/lcd --strip-components=1 --wildcards '*/library' \
 && rm /tmp/lcd.tar.gz

ENV LCD_LIB_PATH=/opt/lcd \
    PYTHONUNBUFFERED=1 \
    TZ=Europe/Prague \
    DATA_DIR=/data

COPY assets ./assets
COPY lines.yaml ./
COPY app.py board.py render.py schedule.py store.py timetable.py main.py ./

VOLUME /data
CMD ["python", "main.py"]

docker-compose.yml:

services:
  screen:
    build: .
    restart: unless-stopped
    environment:
      # Prefer the stable by-id path (see README); /dev/ttyACM0 can change after replug/reboot.
      SCREEN_DEVICE: ${SCREEN_DEVICE:-/dev/ttyACM0}
      SCREEN_ORIENTATION: REVERSE_LANDSCAPE
      SCREEN_BRIGHTNESS: "50"
      TZ: Europe/Prague
      DATA_DIR: /data
    volumes:
      - bus-board-data:/data
    devices:
      - "${SCREEN_DEVICE:-/dev/ttyACM0}:${SCREEN_DEVICE:-/dev/ttyACM0}"

volumes:
  bus-board-data:
  • Step 7: Update README.md
# bus-department-schedule

Shows the next bus/trolleybus departures from Štípa,u potoka and Štípa,družstvo
(lines 4, 5, 35, 36) on a 3.5" Turing Smart Screen driven from a Docker container
on the Coolify home server. Scheduled times only (DSZO timetable pages); falls back
to an analog clock when there is nothing to show.

## Develop (no screen needed)

    python3 -m venv .venv && .venv/bin/pip install -r requirements-dev.txt
    .venv/bin/pytest
    .venv/bin/python preview_board.py   # writes docs/previews/board.png

Design: `docs/superpowers/specs/2026-10-06-bus-board-design.md`.
Plan: `docs/superpowers/plans/2026-10-07-bus-board.md`.

## Run on the server

Find the stable device path (survives replug/reboot, unlike `ttyACM0`):

    ls -l /dev/serial/by-id/

    SCREEN_DEVICE=/dev/serial/by-id/<your-device> docker compose up --build -d
    docker compose logs -f screen

Timetables are cached in the `bus-board-data` volume (`/data`); they refresh on
start and daily at 03:00 (retry every 15 min after a failure).

## If something is wrong

- Blank screen: `docker compose logs screen`; check ModemManager
  (`systemctl status ModemManager`, disable it or add a udev ignore rule).
- Upside-down: set `SCREEN_ORIENTATION` to `LANDSCAPE`.
- `jízdní řád zastaralý` on the board: a download failed for more than 3 days;
  check `docker compose logs screen | grep refresh` (DSZO may have changed a page).
- Add or change lines: edit `lines.yaml` (one entry per line per stop).

## Config (env vars)

| Variable | Default | |
|---|---|---|
| `SCREEN_DEVICE` | `/dev/ttyACM0` | serial device, also passed into the container |
| `SCREEN_ORIENTATION` | `REVERSE_LANDSCAPE` | flip to `LANDSCAPE` if upside-down |
| `SCREEN_BRIGHTNESS` | `50` | 0–100 |
| `TZ` | `Europe/Prague` | time zone for departures |
| `DATA_DIR` | `/data` | cache directory |
| `LINES_FILE` | `/app/lines.yaml` | line/stop/URL list |

The screen library is pinned to one upstream commit in the `Dockerfile` (`LCD_COMMIT`).
  • Step 8: Deploy to the test container and verify live
tar czf - --exclude=.venv --exclude=.git --exclude=tests --exclude=docs --exclude=__pycache__ --exclude=.pytest_cache . 2>/dev/null \
 | ssh coolify 'cd ~/bus-board-test && rm -f clock.py && tar xzf - 2>/dev/null && SCREEN_DEVICE=/dev/serial/by-id/usb-2017-2-25_UsbMonitor_USB35INCHIPSV2-if00 docker compose up --build -d --force-recreate 2>&1 | tail -5'
sleep 15
ssh coolify 'cd ~/bus-board-test && docker compose ps --format "{{.Name}} {{.Status}}" && docker compose logs --tail 20 screen && docker compose exec screen ls -l /data'

Expected: container Up; log lines refresh: 4 updated, failed={}, stale=False and showing board; /data contains four line*-*.html files and fetched.json.

Then ask the user to check the screen against the approved preview (next bus big with countdown; four rows below; times match the real timetable). If the logs show refresh: 0 updated or showing clock, diagnose with superpowers:systematic-debugging rather than guessing.

  • Step 9: Commit
git add -A
git commit -m "feat: run the departure board in the container, clock as fallback"

Not in this plan

  • Moving the container into Coolify from a Gitea repo (needs your Gitea/Coolify UI; separate follow-up once this works).
  • Live delays, other directions or stops, displaying footnote marks (spec "Out of scope").