Harden main loop and store; by-id device default, BOARD_TZ

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
rickzkmandClaude Sonnet 5.5 committed 2026-10-07 00:55:46 +02:00
1 parent 8649d3abd0
commit 44a1b3cf8c
7 files changed
+100 -30

No files matched your search

+5 -4
View File
@@ -20,11 +20,11 @@ Find the stable device path (survives replug/reboot, unlike `ttyACM0`):
ls -l /dev/serial/by-id/ ls -l /dev/serial/by-id/
SCREEN_DEVICE=/dev/serial/by-id/<your-device> docker compose up --build -d docker compose up --build -d
docker compose logs -f screen docker compose logs -f screen
Timetables are cached in the `bus-board-data` volume (`/data`); they refresh on 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). start (only if the cache is older than 20 h) and daily at 03:00 (retry every 15 min after a failure).
## If something is wrong ## If something is wrong
@@ -39,10 +39,11 @@ start and daily at 03:00 (retry every 15 min after a failure).
| Variable | Default | | | Variable | Default | |
|---|---|---| |---|---|---|
| `SCREEN_DEVICE` | `/dev/ttyACM0` | serial device, also passed into the container | | `SCREEN_DEVICE` | `/dev/serial/by-id/usb-2017-2-25_UsbMonitor_USB35INCHIPSV2-if00` | serial device, also passed into the container |
| `SCREEN_ORIENTATION` | `REVERSE_LANDSCAPE` | flip to `LANDSCAPE` if upside-down | | `SCREEN_ORIENTATION` | `REVERSE_LANDSCAPE` | flip to `LANDSCAPE` if upside-down |
| `SCREEN_BRIGHTNESS` | `50` | 0–100 | | `SCREEN_BRIGHTNESS` | `50` | 0–100 |
| `TZ` | `Europe/Prague` | time zone for departures | | `BOARD_TZ` | `Europe/Prague` | time zone for departures (the container's own `TZ` is ignored) |
| `TZ` | `Europe/Prague` | container time zone (logs only) |
| `DATA_DIR` | `/data` | cache directory | | `DATA_DIR` | `/data` | cache directory |
| `LINES_FILE` | `/app/lines.yaml` | line/stop/URL list | | `LINES_FILE` | `/app/lines.yaml` | line/stop/URL list |
+15
View File
@@ -1,4 +1,5 @@
"""Testable glue between timetables, schedule and the board (no screen, no network).""" """Testable glue between timetables, schedule and the board (no screen, no network)."""
import logging
from datetime import date, datetime, timedelta from datetime import date, datetime, timedelta
from typing import Container, Sequence from typing import Container, Sequence
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
@@ -6,9 +7,12 @@ from zoneinfo import ZoneInfo
from PIL import Image from PIL import Image
import board import board
import store
from schedule import next_departures from schedule import next_departures
from timetable import Timetable from timetable import Timetable
log = logging.getLogger(__name__)
DEFAULT_TZ = "Europe/Prague" DEFAULT_TZ = "Europe/Prague"
REFRESH_HOUR = 3 REFRESH_HOUR = 3
RETRY = timedelta(minutes=15) RETRY = timedelta(minutes=15)
@@ -29,6 +33,17 @@ def refresh_due(last_attempt: datetime | None, now: datetime, last_ok: bool) ->
return last_attempt < today_refresh <= now return last_attempt < today_refresh <= now
def load_cache(
lines, data_dir, now: datetime, previous_timetables: list[Timetable], previous_stale: bool
) -> tuple[list[Timetable], bool]:
"""Load the cached timetables and staleness; on any error keep the previous values."""
try:
return store.load_timetables(lines, data_dir), store.is_stale(lines, data_dir, now)
except Exception:
log.exception("loading the cache failed")
return previous_timetables, previous_stale
def board_image( def board_image(
timetables: Sequence[Timetable], timetables: Sequence[Timetable],
now: datetime, now: datetime,
+3 -2
View File
@@ -4,15 +4,16 @@ services:
restart: unless-stopped restart: unless-stopped
environment: environment:
# Prefer the stable by-id path (see README); /dev/ttyACM0 can change after replug/reboot. # Prefer the stable by-id path (see README); /dev/ttyACM0 can change after replug/reboot.
SCREEN_DEVICE: ${SCREEN_DEVICE:-/dev/ttyACM0} SCREEN_DEVICE: ${SCREEN_DEVICE:-/dev/serial/by-id/usb-2017-2-25_UsbMonitor_USB35INCHIPSV2-if00}
SCREEN_ORIENTATION: REVERSE_LANDSCAPE SCREEN_ORIENTATION: REVERSE_LANDSCAPE
SCREEN_BRIGHTNESS: "50" SCREEN_BRIGHTNESS: "50"
TZ: Europe/Prague TZ: Europe/Prague
BOARD_TZ: Europe/Prague
DATA_DIR: /data DATA_DIR: /data
volumes: volumes:
- bus-board-data:/data - bus-board-data:/data
devices: devices:
- "${SCREEN_DEVICE:-/dev/ttyACM0}:${SCREEN_DEVICE:-/dev/ttyACM0}" - "${SCREEN_DEVICE:-/dev/serial/by-id/usb-2017-2-25_UsbMonitor_USB35INCHIPSV2-if00}:${SCREEN_DEVICE:-/dev/serial/by-id/usb-2017-2-25_UsbMonitor_USB35INCHIPSV2-if00}"
volumes: volumes:
bus-board-data: bus-board-data:
+43 -20
View File
@@ -7,6 +7,7 @@ import os
import signal import signal
import sys import sys
import time import time
from datetime import timedelta
from pathlib import Path from pathlib import Path
LIB = os.environ.get("LCD_LIB_PATH", "/opt/lcd") LIB = os.environ.get("LCD_LIB_PATH", "/opt/lcd")
@@ -29,7 +30,9 @@ log = logging.getLogger("main")
DEVICE = os.environ.get("SCREEN_DEVICE", "AUTO") DEVICE = os.environ.get("SCREEN_DEVICE", "AUTO")
ORIENTATION = Orientation[os.environ.get("SCREEN_ORIENTATION", "REVERSE_LANDSCAPE")] ORIENTATION = Orientation[os.environ.get("SCREEN_ORIENTATION", "REVERSE_LANDSCAPE")]
BRIGHTNESS = int(os.environ.get("SCREEN_BRIGHTNESS", "50")) BRIGHTNESS = int(os.environ.get("SCREEN_BRIGHTNESS", "50"))
TZ = os.environ.get("TZ", app.DEFAULT_TZ) TZ = os.environ.get("BOARD_TZ", app.DEFAULT_TZ)
MAX_DRAW_FAILURES = 10
STARTUP_MAX_AGE = timedelta(hours=20)
DATA_DIR = Path(os.environ.get("DATA_DIR", "/data")) DATA_DIR = Path(os.environ.get("DATA_DIR", "/data"))
LINES_FILE = Path(os.environ.get("LINES_FILE", "/app/lines.yaml")) LINES_FILE = Path(os.environ.get("LINES_FILE", "/app/lines.yaml"))
FONT_DIR = str(Path(__file__).parent / "assets" / "fonts") FONT_DIR = str(Path(__file__).parent / "assets" / "fonts")
@@ -58,44 +61,64 @@ def main() -> None:
last_attempt = None last_attempt = None
last_ok = True last_ok = True
timetables = []
stale = False
mode = None # "board" or "clock" mode = None # "board" or "clock"
last_minute = last_second = None last_minute = last_second = None
draw_failures = 0
# Draw from the existing cache straight away; only refresh at startup if it is old.
now = app.local_now(TZ)
timetables, stale = app.load_cache(lines, DATA_DIR, now, [], False)
try:
cache_fresh = not store.is_stale(lines, DATA_DIR, now, max_age=STARTUP_MAX_AGE)
except Exception:
log.exception("cache age check failed")
cache_fresh = False
if cache_fresh:
log.info("cache fresh, skipping startup refresh")
last_attempt, last_ok = now, True
while running: while running:
now = app.local_now(TZ) now = app.local_now(TZ)
if app.refresh_due(last_attempt, now, last_ok): if app.refresh_due(last_attempt, now, last_ok):
report = None
try: try:
report = store.refresh(lines, DATA_DIR, now=now) 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 last_ok = not report.failed
log.info("refresh: %d updated, failed=%s, stale=%s", len(report.updated), report.failed, stale)
except Exception: except Exception:
# Never crash or go blank: keep showing the previous timetables, retry in 15 min. # Never crash or go blank: keep showing the previous timetables, retry in 15 min.
log.exception("refresh failed") log.exception("refresh failed")
last_ok = False last_ok = False
timetables, stale = app.load_cache(lines, DATA_DIR, now, timetables, stale)
if report is not None:
log.info("refresh: %d updated, failed=%s, stale=%s", len(report.updated), report.failed, stale)
last_attempt = now last_attempt = now
last_minute = None # redraw straight away last_minute = None # redraw straight away
if now.second != last_second: if now.second != last_second:
last_second = now.second last_second = now.second
if now.minute != last_minute: try:
last_minute = now.minute if now.minute != last_minute:
image = app.board_image(timetables, now, board_fonts, stale, state_holidays) last_minute = now.minute
new_mode = "board" if image is not None else "clock" image = app.board_image(timetables, now, board_fonts, stale, state_holidays)
if new_mode != mode: new_mode = "board" if image is not None else "clock"
log.info("showing %s", new_mode) if new_mode != mode:
lcd.DisplayPILImage(Image.new("RGB", (board.W, board.H), board.BG), 0, 0) log.info("showing %s", new_mode)
mode = new_mode lcd.DisplayPILImage(Image.new("RGB", (board.W, board.H), board.BG), 0, 0)
if mode == "board": mode = new_mode # only recorded once the clearing draw succeeded
lcd.DisplayPILImage(image, 0, 0) if mode == "board":
else: lcd.DisplayPILImage(image, 0, 0)
lcd.DisplayPILImage(render.render_info(now, clock_fonts), render.DIAL_W, 0) else:
if mode == "clock": lcd.DisplayPILImage(render.render_info(now, clock_fonts), render.DIAL_W, 0)
lcd.DisplayPILImage(render.render_dial(now), 0, 0) if mode == "clock":
lcd.DisplayPILImage(render.render_dial(now), 0, 0)
draw_failures = 0
except Exception:
log.exception("draw failed")
draw_failures += 1
last_minute = None # retry on the next second
if draw_failures >= MAX_DRAW_FAILURES:
raise # let Docker restart the process and reopen the port
time.sleep(0.05) time.sleep(0.05)
lcd.closeSerial() lcd.closeSerial()
+3 -2
View File
@@ -54,9 +54,10 @@ def cache_path(data_dir, cfg: LineConfig) -> Path:
def _read_fetched(data_dir: Path) -> dict[str, str]: def _read_fetched(data_dir: Path) -> dict[str, str]:
try: try:
return json.loads((data_dir / FETCHED_FILE).read_text(encoding="utf-8")) data = json.loads((data_dir / FETCHED_FILE).read_text(encoding="utf-8"))
except (OSError, ValueError): except (OSError, ValueError):
return {} return {}
return data if isinstance(data, dict) else {}
def _write_atomic(path: Path, text: str) -> None: def _write_atomic(path: Path, text: str) -> None:
@@ -105,7 +106,7 @@ def is_stale(lines, data_dir, now: datetime, max_age: timedelta = MAX_AGE) -> bo
for cfg in lines: for cfg in lines:
try: try:
when = datetime.fromisoformat(fetched[cfg.label]) when = datetime.fromisoformat(fetched[cfg.label])
except (KeyError, ValueError): except (KeyError, ValueError, TypeError):
return True return True
if now - when > max_age: if now - when > max_age:
return True return True
+16 -2
View File
@@ -1,10 +1,10 @@
import os
import time as time_module import time as time_module
from datetime import datetime, timezone from datetime import datetime, timezone
import app import app
import board import board
from tests.helpers import FONT_DIR, load_timetables import store
from tests.helpers import FONT_DIR, fixture_html, load_timetables
def test_refresh_due_on_first_run(): def test_refresh_due_on_first_run():
@@ -48,3 +48,17 @@ def test_board_image_renders_real_timetables(cz):
fonts = board.load_fonts(FONT_DIR) fonts = board.load_fonts(FONT_DIR)
img = app.board_image(load_timetables(), datetime(2026, 10, 6, 13, 28, 20), fonts, False, cz) 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) assert img is not None and img.size == (480, 320)
def test_load_cache_returns_parsed_timetables_and_fresh_flag(tmp_path):
line4 = store.LineConfig("4", "Štípa,u potoka", "https://example.test/4")
now = datetime(2026, 10, 6, 12, 0)
store.refresh([line4], tmp_path, fetch=lambda url: fixture_html("line4_u_potoka.html"), now=now)
timetables, stale = app.load_cache([line4], tmp_path, now, [], True)
assert [t.line for t in timetables] == ["4"] and stale is False
def test_load_cache_keeps_previous_values_on_error(tmp_path):
previous = load_timetables()
timetables, stale = app.load_cache(None, tmp_path, datetime(2026, 10, 6, 12, 0), previous, True)
assert timetables is previous and stale is True
+15
View File
@@ -1,3 +1,4 @@
import json
from datetime import datetime, timedelta from datetime import datetime, timedelta
import pytest import pytest
@@ -79,3 +80,17 @@ def test_load_lines_reads_yaml(tmp_path):
def test_repo_lines_yaml_lists_the_four_lines(): def test_repo_lines_yaml_lists_the_four_lines():
labels = [c.label for c in store.load_lines(ROOT / "lines.yaml")] 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"] assert labels == ["4 Štípa,u potoka", "5 Štípa,u potoka", "35 Štípa,družstvo", "36 Štípa,družstvo"]
@pytest.mark.parametrize("content", ["[]", "null", "42", '"x"'])
def test_fetched_json_that_is_not_an_object_is_ignored(tmp_path, content):
(tmp_path / store.FETCHED_FILE).write_text(content, encoding="utf-8")
assert store.is_stale([LINE4], tmp_path, NOW) is True
report = store.refresh([LINE4], tmp_path, fetch=good_page, now=NOW)
assert report.updated == [LINE4.label]
assert store.is_stale([LINE4], tmp_path, NOW) is False
def test_fetched_json_with_non_string_value_is_stale_not_an_error(tmp_path):
(tmp_path / store.FETCHED_FILE).write_text(json.dumps({LINE4.label: 5}), encoding="utf-8")
assert store.is_stale([LINE4], tmp_path, NOW) is True