"""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)