Files
second-screen/runner.py
T
rickzkmandClaude Sonnet 5.5 edba341f30 Send only the changed regions of each frame
The link moves ~150 KB/s, so a full frame takes 2 s. After the first frame the runner
diffs against what the screen shows and sends tight boxes; full frame on big changes,
after a failed push, and every 15 minutes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-22 14:25:09 +02:00

109 lines
4.4 KiB
Python

"""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 regions import changed_regions
from view import View
log = logging.getLogger(__name__)
TICK_S = 0.05
OPEN_RETRY_S = 30.0
FULL_REFRESH_S = 900.0 # resend the whole frame this often, so a glitch on the link cannot stay on the screen
FULL_FRAME_ABOVE = 0.6 # when more than this share of the screen changed, one full frame is simpler
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, SystemExit) as exc: # the screen library calls sys.exit(0) when the port is missing
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 _push_frame(lcd, shown: Image.Image | None, frame: Image.Image, force_full: bool) -> bool:
"""Bring the screen from `shown` (None: unknown) to `frame`. Returns True if a full frame was sent."""
if shown is not None and not force_full:
boxes = changed_regions(shown, frame)
changed = sum((x1 - x0) * (y1 - y0) for x0, y0, x1, y1 in boxes)
if changed <= FULL_FRAME_ABOVE * frame.width * frame.height:
for x0, y0, x1, y1 in boxes:
lcd.DisplayPILImage(frame.crop((x0, y0, x1, y1)), x0, y0)
return False
lcd.DisplayPILImage(frame, 0, 0)
return True
def run(view: View, lcd, *, now_fn: Callable[[], datetime], running: Callable[[], bool],
sleep: Callable[[float], None] = time.sleep, max_failures: int = 10,
full_refresh_s: float = FULL_REFRESH_S, monotonic: Callable[[], float] = time.monotonic) -> None:
last_key = None
last_second = None
shown: Image.Image | None = None # what the screen is believed to show; None when unknown
last_full = 0.0
failures = 0
while running():
now = now_fn()
try:
key = view.frame_key(now)
if key != last_key:
frame = view.render(now)
due = monotonic() - last_full >= full_refresh_s
if _push_frame(lcd, shown, frame, force_full=due):
last_full = monotonic()
shown = frame.copy()
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)
if shown is not None:
shown.paste(patch.image, (patch.x, patch.y))
last_second = now.second
failures = 0
except (Exception, SystemExit): # SystemExit: the library exits when it cannot reopen the port
log.exception("draw failed")
failures += 1
last_key = None # redraw on the next tick
shown = None # a push may have been cut short: the screen's content is unknown
if failures >= max_failures:
raise # let Docker restart the process and reopen the port
sleep(TICK_S)