65 lines
2.2 KiB
Python
65 lines
2.2 KiB
Python
"""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
|
|
|
|
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)
|
|
NIGHT_END_HOUR = 6 # the screen is dimmed from midnight until this hour
|
|
|
|
|
|
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 brightness(now: datetime, base: int) -> int:
|
|
"""Backlight level for `now`: half of `base` from 00:00 to 06:00, `base` otherwise."""
|
|
return base // 2 if now.hour < NIGHT_END_HOUR else base
|
|
|
|
|
|
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,
|
|
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)
|