diff --git a/Dockerfile b/Dockerfile index adec56c..443db55 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ FROM python:3.12-slim -# Pinned commit of the Turing Smart Screen library (we only need library/ and the fonts). +# Pinned commit of the Turing Smart Screen library (we only need library/). ARG LCD_COMMIT=2b33ab4f00a096916dd6a1174441a53a7ec33b03 WORKDIR /app @@ -10,13 +10,17 @@ 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' '*/res/fonts' \ + && 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 + TZ=Europe/Prague \ + DATA_DIR=/data -COPY render.py clock.py ./ -CMD ["python", "clock.py"] +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"] diff --git a/README.md b/README.md index 492212d..323e8cd 100644 --- a/README.md +++ b/README.md @@ -1,42 +1,49 @@ # bus-department-schedule -Drives a 3.5" Turing Smart Screen (Rev A, 320x480, USB serial) from a Docker -container on the Coolify server. Goal: show local bus departures. +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. -**Current stage: hardware smoke test.** `clock.py` draws a clock. Once it runs -on the server, it gets replaced by the departure board. +## 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 a stable device path (survives replug/reboot, unlike `ttyACM0`): +Find the stable device path (survives replug/reboot, unlike `ttyACM0`): ls -l /dev/serial/by-id/ -Then, from this folder on the server: + SCREEN_DEVICE=/dev/serial/by-id/ docker compose up --build -d + docker compose logs -f screen - SCREEN_DEVICE=/dev/serial/by-id/ docker compose up --build +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). -In Coolify: new resource -> Docker Compose from the Gitea repo, and set -`SCREEN_DEVICE` in the environment variables. +## If something is wrong -## If the screen stays blank - -1. `docker compose logs screen` - permission denied or "could not open port"? -2. ModemManager grabbing the port: `systemctl status ModemManager`. Fix with - `sudo systemctl disable --now ModemManager` (or a udev rule marking the - device `ID_MM_DEVICE_IGNORE=1`). -3. Wrong orientation: change `SCREEN_ORIENTATION` (PORTRAIT, REVERSE_PORTRAIT, - LANDSCAPE, REVERSE_LANDSCAPE). -4. Only one process can hold the port - make sure nothing else uses it. +- 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 the picture is upside-down | -| `SCREEN_BRIGHTNESS` | `50` | 0-100 | -| `TZ` | `Europe/Prague` | clock timezone | +| `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`). +The screen library is pinned to one upstream commit in the `Dockerfile` (`LCD_COMMIT`). diff --git a/app.py b/app.py new file mode 100644 index 0000000..94daf9d --- /dev/null +++ b/app.py @@ -0,0 +1,43 @@ +"""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) diff --git a/clock.py b/clock.py deleted file mode 100644 index fa5b4af..0000000 --- a/clock.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Clock face for the Turing Smart Screen, run as a container on the Coolify server. - -Placeholder until the bus departure board replaces it. Drawing lives in render.py; -this file only owns the display and the update loop. -""" -import logging -import os -import signal -import sys -import time -from datetime import datetime - -LIB = os.environ.get("LCD_LIB_PATH", "/opt/lcd") -sys.path.insert(0, LIB) - -from PIL import Image # noqa: E402 - -import render # 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("clock") - -DEVICE = os.environ.get("SCREEN_DEVICE", "AUTO") -ORIENTATION = Orientation[os.environ.get("SCREEN_ORIENTATION", "REVERSE_LANDSCAPE")] -BRIGHTNESS = int(os.environ.get("SCREEN_BRIGHTNESS", "50")) - - -def main() -> None: - log.info("Opening display on %s (%s)", DEVICE, ORIENTATION.name) - lcd = LcdCommRevA(com_port=DEVICE) if DEVICE != "AUTO" else LcdCommRevA() - lcd.InitializeComm() - lcd.SetOrientation(ORIENTATION) - lcd.SetBrightness(BRIGHTNESS) - fonts = render.load_fonts(LIB) - - running = True - - def stop(*_): - nonlocal running - running = False - - signal.signal(signal.SIGTERM, stop) - signal.signal(signal.SIGINT, stop) - - lcd.DisplayPILImage(Image.new("RGB", (render.W, render.H), render.BG), 0, 0) # clear once - log.info("Display ready") - - last_second = last_minute = None - while running: - now = datetime.now() - if now.second != last_second: - if now.minute != last_minute: # the digital panel only changes once a minute - lcd.DisplayPILImage(render.render_info(now, fonts), render.DIAL_W, 0) - last_minute = now.minute - lcd.DisplayPILImage(render.render_dial(now), 0, 0) - last_second = now.second - time.sleep(0.05) - - lcd.closeSerial() - log.info("Stopped") - - -if __name__ == "__main__": - main() diff --git a/docker-compose.yml b/docker-compose.yml index 214bc27..cf75f08 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,5 +8,11 @@ services: 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: diff --git a/main.py b/main.py new file mode 100644 index 0000000..3cf16dd --- /dev/null +++ b/main.py @@ -0,0 +1,106 @@ +"""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): + try: + report = store.refresh(lines, DATA_DIR, now=now) + timetables = store.load_timetables(lines, DATA_DIR) + stale = store.is_stale(lines, DATA_DIR, now) + last_ok = not report.failed + log.info("refresh: %d updated, failed=%s, stale=%s", len(report.updated), report.failed, stale) + except Exception: + # Never crash or go blank: keep showing the previous timetables, retry in 15 min. + log.exception("refresh failed") + last_ok = False + last_attempt = now + 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() diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..4f54727 --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,50 @@ +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)