Files
bus-department-schedule/main.py
T
2026-10-28 22:55:08 +01:00

135 lines
5.0 KiB
Python

"""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 datetime import timedelta
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("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")
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)
running = True
def stop(*_):
nonlocal running
running = False
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
last_attempt = None
last_ok = True
mode = None # "board" or "clock"
last_minute = last_second = None
level = None # backlight level last sent to the screen
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)
last_ok = not report.failed
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
try:
if now.minute != last_minute:
last_minute = now.minute
new_level = app.brightness(now, BRIGHTNESS)
if new_level != level:
log.info("brightness %d", new_level)
lcd.SetBrightness(new_level)
level = new_level # only recorded once the screen accepted it
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()
log.info("Stopped")
if __name__ == "__main__":
main()