"""Draw a view on the screen: full frames when it changes, partial patches in between.""" import logging import time from datetime import datetime from typing import Any, Callable, Sequence from PIL import Image, ImageDraw import lcdkit from lcdkit import BG, H, INK, W from view import View log = logging.getLogger(__name__) TICK_S = 0.05 OPEN_RETRY_S = 30.0 def render_error(lines: Sequence[str]) -> Image.Image: img = Image.new("RGB", (W, H), BG) d = ImageDraw.Draw(img) d.rectangle((6, 6, W - 7, H - 7), outline=INK, width=2) lcdkit.tag(d, (14, 14), "ERROR", lcdkit.load_font(18)) font = lcdkit.load_font(18) for i, line in enumerate(lines): while line and d.textlength(line, font=font) > W - 40: line = line[:-1] d.text((20, 60 + i * 30), line, font=font, fill=INK) return img def open_screen(factory: Callable[[], Any], *, running: Callable[[], bool], sleep: Callable[[float], None] = time.sleep, retry_s: float = OPEN_RETRY_S) -> Any | None: """Call `factory` until it returns a screen; None if `running()` turns false first. Logs the first failure only.""" logged = False while running(): try: return factory() except Exception as exc: if not logged: log.warning("screen not available (%s); retrying every %.0f s", exc, retry_s) logged = True sleep(retry_s) return None def idle_with_message(lcd, lines: Sequence[str], *, running: Callable[[], bool], sleep: Callable[[float], None] = time.sleep) -> None: """Show an error message and stay alive (holding the port) until stopped.""" try: lcd.DisplayPILImage(render_error(lines), 0, 0) except Exception: log.exception("could not draw the error message") while running(): sleep(0.5) def run(view: View, lcd, *, now_fn: Callable[[], datetime], running: Callable[[], bool], sleep: Callable[[float], None] = time.sleep, max_failures: int = 10) -> None: last_key = None last_second = None failures = 0 while running(): now = now_fn() try: key = view.frame_key(now) if key != last_key: lcd.DisplayPILImage(view.render(now), 0, 0) last_key, last_second = key, now.second elif now.second != last_second: patch = view.patch(now) if patch is not None: lcd.DisplayPILImage(patch.image, patch.x, patch.y) last_second = now.second failures = 0 except Exception: log.exception("draw failed") failures += 1 last_key = None # redraw everything on the next tick if failures >= max_failures: raise # let Docker restart the process and reopen the port sleep(TICK_S)