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]>
243 lines
8.7 KiB
Python
243 lines
8.7 KiB
Python
import logging
|
|
from datetime import datetime, timedelta
|
|
|
|
import pytest
|
|
from PIL import Image
|
|
|
|
import runner
|
|
from lcdkit import BG, INK
|
|
from tests.helpers import count_colour
|
|
from view import Patch
|
|
|
|
|
|
class FakeLcd:
|
|
def __init__(self, fail_first=0, always_fail=False):
|
|
self.calls = [] # (size, x, y)
|
|
self._fail_first, self._always_fail = fail_first, always_fail
|
|
|
|
def DisplayPILImage(self, image, x=0, y=0, image_width=None, image_height=None):
|
|
if self._always_fail or self._fail_first > 0:
|
|
self._fail_first -= 1
|
|
raise OSError("serial hiccup")
|
|
self.calls.append((image.size, x, y))
|
|
|
|
|
|
class StubView:
|
|
name = "stub"
|
|
|
|
def __init__(self, keys, with_patch=True, render_fn=None):
|
|
self._keys = keys # callable(now) -> key
|
|
self._with_patch = with_patch
|
|
self._render_fn = render_fn # callable(now) -> Image, default: a blank frame
|
|
self.renders = 0
|
|
|
|
def start(self): ...
|
|
def stop(self): ...
|
|
|
|
def frame_key(self, now):
|
|
return self._keys(now)
|
|
|
|
def render(self, now):
|
|
self.renders += 1
|
|
return self._render_fn(now) if self._render_fn else Image.new("RGB", (480, 320), BG)
|
|
|
|
def patch(self, now):
|
|
return Patch(Image.new("RGB", (10, 5), BG), 100, 50) if self._with_patch else None
|
|
|
|
|
|
def marker(x, y, size=10):
|
|
"""A blank frame with one dark box; moving it between frames is a small change."""
|
|
img = Image.new("RGB", (480, 320), BG)
|
|
img.paste((0, 0, 0), (x, y, x + size, y + size))
|
|
return img
|
|
|
|
|
|
def ticks(n):
|
|
"""running() that is true for the first n calls."""
|
|
state = {"left": n}
|
|
|
|
def running():
|
|
state["left"] -= 1
|
|
return state["left"] >= 0
|
|
|
|
return running
|
|
|
|
|
|
def clock(start, step_s):
|
|
state = {"now": start - timedelta(seconds=step_s)}
|
|
|
|
def now_fn():
|
|
state["now"] += timedelta(seconds=step_s)
|
|
return state["now"]
|
|
|
|
return now_fn
|
|
|
|
|
|
T0 = datetime(2026, 10, 22, 14, 32, 0)
|
|
|
|
|
|
def test_run_pushes_full_frame_once_per_key():
|
|
lcd, view = FakeLcd(), StubView(lambda now: "same", with_patch=False)
|
|
runner.run(view, lcd, now_fn=clock(T0, 0), running=ticks(3), sleep=lambda s: None)
|
|
assert lcd.calls == [((480, 320), 0, 0)]
|
|
|
|
|
|
def test_run_pushes_patch_each_new_second_only():
|
|
lcd, view = FakeLcd(), StubView(lambda now: "same")
|
|
# ticks at seconds 0, 0, 1, 1, 2 -> full frame, then one patch per *new* second
|
|
seconds = iter([0, 0, 1, 1, 2])
|
|
now_fn = lambda: T0.replace(second=next(seconds))
|
|
runner.run(view, lcd, now_fn=now_fn, running=ticks(5), sleep=lambda s: None)
|
|
assert lcd.calls == [((480, 320), 0, 0), ((10, 5), 100, 50), ((10, 5), 100, 50)]
|
|
|
|
|
|
def test_run_pushes_only_the_changed_region_when_the_key_changes():
|
|
view = StubView(lambda now: now.minute, render_fn=lambda now: marker(now.minute * 10, 40))
|
|
lcd = FakeLcd()
|
|
runner.run(view, lcd, now_fn=clock(T0, 60), running=ticks(3), sleep=lambda s: None)
|
|
assert lcd.calls[0] == ((480, 320), 0, 0) # first frame: everything
|
|
assert lcd.calls[1:] == [((20, 10), 320, 40), ((20, 10), 330, 40)] # then just the box that moved
|
|
|
|
|
|
def test_run_retries_failed_draw_and_continues():
|
|
lcd, view = FakeLcd(fail_first=1), StubView(lambda now: "same", with_patch=False)
|
|
runner.run(view, lcd, now_fn=clock(T0, 0), running=ticks(3), sleep=lambda s: None)
|
|
assert lcd.calls == [((480, 320), 0, 0)] # failed once, redrawn on the next tick, then stable
|
|
|
|
|
|
def test_run_raises_after_max_failures():
|
|
lcd, view = FakeLcd(always_fail=True), StubView(lambda now: "same")
|
|
with pytest.raises(OSError):
|
|
runner.run(view, lcd, now_fn=clock(T0, 0), running=ticks(50), sleep=lambda s: None, max_failures=3)
|
|
|
|
|
|
def test_open_screen_retries_until_available(caplog):
|
|
attempts, sleeps = [], []
|
|
|
|
def factory():
|
|
attempts.append(1)
|
|
if len(attempts) < 3:
|
|
raise OSError("no such device")
|
|
return "lcd"
|
|
|
|
with caplog.at_level(logging.WARNING):
|
|
result = runner.open_screen(factory, running=lambda: True, sleep=sleeps.append)
|
|
assert result == "lcd"
|
|
assert sleeps == [30.0, 30.0]
|
|
assert len([r for r in caplog.records if r.levelno == logging.WARNING]) == 1 # logged once
|
|
|
|
|
|
def test_open_screen_returns_none_when_stopped():
|
|
def factory():
|
|
raise OSError("no such device")
|
|
|
|
assert runner.open_screen(factory, running=ticks(1), sleep=lambda s: None) is None
|
|
|
|
|
|
def test_idle_with_message_draws_once_and_returns_on_stop():
|
|
lcd = FakeLcd()
|
|
runner.idle_with_message(lcd, ["UNKNOWN VIEW: bogus"], running=ticks(4), sleep=lambda s: None)
|
|
assert lcd.calls == [((480, 320), 0, 0)]
|
|
|
|
|
|
def test_render_error_size_and_has_ink():
|
|
img = runner.render_error(["UNKNOWN VIEW: bogus", "VALID: server, weather"])
|
|
assert img.size == (480, 320)
|
|
assert count_colour(img, INK) > 500
|
|
|
|
|
|
def test_render_error_long_line_does_not_raise():
|
|
assert runner.render_error(["X" * 500]).size == (480, 320)
|
|
|
|
|
|
def test_open_screen_retries_when_the_library_calls_sys_exit():
|
|
"""The pinned screen library calls sys.exit(0) when the port is missing; that must not end the process."""
|
|
attempts, sleeps = [], []
|
|
|
|
def factory():
|
|
attempts.append(1)
|
|
if len(attempts) < 3:
|
|
raise SystemExit(0)
|
|
return "lcd"
|
|
|
|
assert runner.open_screen(factory, running=lambda: True, sleep=sleeps.append) == "lcd"
|
|
assert sleeps == [30.0, 30.0]
|
|
|
|
|
|
def test_run_counts_library_sys_exit_as_a_failed_draw():
|
|
class ExitingLcd:
|
|
def DisplayPILImage(self, *a, **k):
|
|
raise SystemExit(0)
|
|
|
|
view = StubView(lambda now: "same")
|
|
with pytest.raises(SystemExit): # after max_failures; Docker then restarts and open_screen retries
|
|
runner.run(view, ExitingLcd(), now_fn=clock(T0, 0), running=ticks(50), sleep=lambda s: None, max_failures=3)
|
|
assert view.renders == 3 # it tried three times first
|
|
|
|
|
|
def test_run_sends_everything_when_most_of_the_screen_changed():
|
|
frames = iter([Image.new("RGB", (480, 320), BG), Image.new("RGB", (480, 320), (0, 0, 0))])
|
|
view = StubView(lambda now: now.minute, render_fn=lambda now: next(frames))
|
|
lcd = FakeLcd()
|
|
runner.run(view, lcd, now_fn=clock(T0, 60), running=ticks(2), sleep=lambda s: None)
|
|
assert lcd.calls == [((480, 320), 0, 0), ((480, 320), 0, 0)]
|
|
|
|
|
|
def test_run_sends_a_full_frame_again_after_the_refresh_interval():
|
|
view = StubView(lambda now: now.minute, render_fn=lambda now: marker(now.minute * 10, 40))
|
|
lcd = FakeLcd()
|
|
elapsed = {32: 0.0, 33: 10.0, 34: 1000.0} # seconds since start, by the minute being shown
|
|
t = {"now": 0.0}
|
|
|
|
def now_fn():
|
|
now = T0 + timedelta(minutes=t["tick"])
|
|
t["tick"] += 1
|
|
t["now"] = elapsed[now.minute]
|
|
return now
|
|
|
|
t["tick"] = 0
|
|
runner.run(view, lcd, now_fn=now_fn, running=ticks(3), sleep=lambda s: None,
|
|
full_refresh_s=900.0, monotonic=lambda: t["now"])
|
|
sizes = [c[0] for c in lcd.calls]
|
|
assert sizes == [(480, 320), (20, 10), (480, 320)] # the third frame is 1000 s after the last full one
|
|
|
|
|
|
def test_run_sends_a_full_frame_after_a_failed_push():
|
|
view = StubView(lambda now: now.minute, render_fn=lambda now: marker(now.minute * 10, 40))
|
|
|
|
class FailsOnSecondCall(FakeLcd):
|
|
def DisplayPILImage(self, image, x=0, y=0, image_width=None, image_height=None):
|
|
if len(self.calls) == 1 and not getattr(self, "failed", False):
|
|
self.failed = True
|
|
raise OSError("serial hiccup")
|
|
super().DisplayPILImage(image, x, y)
|
|
|
|
lcd = FailsOnSecondCall()
|
|
runner.run(view, lcd, now_fn=clock(T0, 60), running=ticks(3), sleep=lambda s: None)
|
|
assert [c[0] for c in lcd.calls] == [(480, 320), (480, 320)] # the screen state was unknown, so everything again
|
|
|
|
|
|
def test_run_does_not_resend_what_a_patch_already_drew():
|
|
state = {"n": 0}
|
|
|
|
def render(now):
|
|
state["n"] += 1
|
|
img = marker(300, 200) # something that never changes
|
|
img.paste((50, 50, 50), (100, 50, 110, 55)) # where the view's patch draws its seconds
|
|
if state["n"] == 2:
|
|
img.paste((0, 0, 0), (10, 10, 20, 20)) # the one real change
|
|
return img
|
|
|
|
class PatchView(StubView):
|
|
def patch(self, now):
|
|
return Patch(Image.new("RGB", (10, 5), (50, 50, 50)), 100, 50)
|
|
|
|
view = PatchView(lambda now: now.minute, render_fn=render)
|
|
lcd = FakeLcd()
|
|
seconds = iter([0, 1, 0]) # tick1 full; tick2 same key new second -> patch; tick3 new key
|
|
minutes = iter([0, 0, 1])
|
|
now_fn = lambda: T0.replace(minute=next(minutes), second=next(seconds))
|
|
runner.run(view, lcd, now_fn=now_fn, running=ticks(3), sleep=lambda s: None)
|
|
# full frame, the patch, then only the changed box: the patch region was already up to date
|
|
assert lcd.calls == [((480, 320), 0, 0), ((10, 5), 100, 50), ((10, 10), 10, 10)]
|