diff --git a/README.md b/README.md index 323e8cd..3acaa74 100644 --- a/README.md +++ b/README.md @@ -20,11 +20,11 @@ Find the stable device path (survives replug/reboot, unlike `ttyACM0`): ls -l /dev/serial/by-id/ - SCREEN_DEVICE=/dev/serial/by-id/ docker compose up --build -d + 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). +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 @@ -39,10 +39,11 @@ start and daily at 03:00 (retry every 15 min after a failure). | 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_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 | | `LINES_FILE` | `/app/lines.yaml` | line/stop/URL list | diff --git a/app.py b/app.py index 94daf9d..e49c0ce 100644 --- a/app.py +++ b/app.py @@ -1,4 +1,5 @@ """Testable glue between timetables, schedule and the board (no screen, no network).""" +import logging from datetime import date, datetime, timedelta from typing import Container, Sequence from zoneinfo import ZoneInfo @@ -6,9 +7,12 @@ from zoneinfo import ZoneInfo from PIL import Image import board +import store from schedule import next_departures from timetable import Timetable +log = logging.getLogger(__name__) + DEFAULT_TZ = "Europe/Prague" REFRESH_HOUR = 3 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 +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( timetables: Sequence[Timetable], now: datetime, diff --git a/docker-compose.yml b/docker-compose.yml index cf75f08..830d782 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -4,15 +4,16 @@ services: 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_DEVICE: ${SCREEN_DEVICE:-/dev/serial/by-id/usb-2017-2-25_UsbMonitor_USB35INCHIPSV2-if00} SCREEN_ORIENTATION: REVERSE_LANDSCAPE SCREEN_BRIGHTNESS: "50" TZ: Europe/Prague + BOARD_TZ: Europe/Prague DATA_DIR: /data volumes: - bus-board-data:/data 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: bus-board-data: diff --git a/main.py b/main.py index 3cf16dd..b9f4277 100644 --- a/main.py +++ b/main.py @@ -7,6 +7,7 @@ import os import signal import sys import time +from datetime import timedelta from pathlib import Path LIB = os.environ.get("LCD_LIB_PATH", "/opt/lcd") @@ -29,7 +30,9 @@ 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) +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")) LINES_FILE = Path(os.environ.get("LINES_FILE", "/app/lines.yaml")) FONT_DIR = str(Path(__file__).parent / "assets" / "fonts") @@ -58,44 +61,64 @@ def main() -> None: last_attempt = None last_ok = True - timetables = [] - stale = False mode = None # "board" or "clock" 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: now = app.local_now(TZ) if app.refresh_due(last_attempt, now, last_ok): + report = None 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 + 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_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) + try: + 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 # only recorded once the clearing draw succeeded + 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) + 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) lcd.closeSerial() diff --git a/store.py b/store.py index 37117c7..f5c507f 100644 --- a/store.py +++ b/store.py @@ -54,9 +54,10 @@ def cache_path(data_dir, cfg: LineConfig) -> Path: def _read_fetched(data_dir: Path) -> dict[str, str]: 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): return {} + return data if isinstance(data, dict) else {} 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: try: when = datetime.fromisoformat(fetched[cfg.label]) - except (KeyError, ValueError): + except (KeyError, ValueError, TypeError): return True if now - when > max_age: return True diff --git a/tests/test_app.py b/tests/test_app.py index 4f54727..b344317 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -1,10 +1,10 @@ -import os import time as time_module from datetime import datetime, timezone import app 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(): @@ -48,3 +48,17 @@ 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) + + +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 diff --git a/tests/test_store.py b/tests/test_store.py index ab6caaa..287fc05 100644 --- a/tests/test_store.py +++ b/tests/test_store.py @@ -1,3 +1,4 @@ +import json from datetime import datetime, timedelta import pytest @@ -79,3 +80,17 @@ def test_load_lines_reads_yaml(tmp_path): 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"] + + +@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