diff --git a/main.py b/main.py new file mode 100644 index 0000000..6727ebc --- /dev/null +++ b/main.py @@ -0,0 +1,68 @@ +"""Container entry point: show the view named by VIEW on the second Turing screen.""" +import logging +import os +import signal +import sys +import threading + +import registry +import runner +from timeutil import local_now + +DEFAULT_DEVICE = "/dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00" + +# 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") + + +def _open_lcd(device: str, orientation_name: str, brightness: int): + from library.lcd.lcd_comm import Orientation # the screen library lives outside the project + from library.lcd.lcd_comm_rev_a import LcdCommRevA + + lcd = LcdCommRevA(com_port=device) if device != "AUTO" else LcdCommRevA() + lcd.InitializeComm() + lcd.SetOrientation(Orientation[orientation_name]) + lcd.SetBrightness(brightness) + return lcd + + +def main(stop: threading.Event | None = None) -> None: + stop = stop or threading.Event() + view_name = os.environ.get("VIEW", "") + device = os.environ.get("SCREEN_DEVICE", DEFAULT_DEVICE) + orientation = os.environ.get("SCREEN_ORIENTATION", "LANDSCAPE") + brightness = int(os.environ.get("SCREEN_BRIGHTNESS", "50")) + sys.path.insert(0, os.environ.get("LCD_LIB_PATH", "/opt/lcd")) + + def running() -> bool: + return not stop.is_set() + + log.info("Opening display on %s (%s), view %r", device, orientation, view_name) + lcd = runner.open_screen(lambda: _open_lcd(device, orientation, brightness), running=running, sleep=stop.wait) + if lcd is None: + return + try: + try: + view = registry.make_view(view_name) + except registry.UnknownView as exc: + log.error("%s", exc) + runner.idle_with_message( + lcd, [f"UNKNOWN VIEW: {view_name or '(VIEW not set)'}", "VALID: " + ", ".join(exc.valid)], + running=running, sleep=stop.wait) + return + view.start() + try: + runner.run(view, lcd, now_fn=local_now, running=running, sleep=stop.wait) + finally: + view.stop() + finally: + lcd.closeSerial() + log.info("Stopped") + + +if __name__ == "__main__": + event = threading.Event() + signal.signal(signal.SIGTERM, lambda *_: event.set()) + signal.signal(signal.SIGINT, lambda *_: event.set()) + main(event) diff --git a/registry.py b/registry.py new file mode 100644 index 0000000..02a0bb2 --- /dev/null +++ b/registry.py @@ -0,0 +1,43 @@ +"""The views the container can show, selected by the VIEW env var.""" +from typing import Callable + +from poller import Poller +from server_view import ServerView +from stats_data import StatsReader +from timeutil import local_now +from view import View +from weather_data import fetch_weather +from weather_view import WeatherView + +WEATHER_REFRESH_S = 15 * 60 +SERVER_REFRESH_S = 5 + + +class UnknownView(Exception): + def __init__(self, name: str, valid: list[str]) -> None: + super().__init__(f"unknown view {name!r}; valid views: {', '.join(valid)}") + self.name = name + self.valid = valid + + +def _weather() -> View: + return WeatherView(Poller(lambda: fetch_weather(local_now()), WEATHER_REFRESH_S)) + + +def _server() -> View: + return ServerView(Poller(StatsReader().read, SERVER_REFRESH_S)) + + +# To add a view: write the module, add one entry here, add a README line. +REGISTRY: dict[str, Callable[[], View]] = { + "weather": _weather, + "server": _server, +} + + +def make_view(name: str) -> View: + try: + factory = REGISTRY[name] + except KeyError: + raise UnknownView(name, sorted(REGISTRY)) from None + return factory() diff --git a/runner.py b/runner.py new file mode 100644 index 0000000..48c6e0c --- /dev/null +++ b/runner.py @@ -0,0 +1,82 @@ +"""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) diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000..bc07c8f --- /dev/null +++ b/tests/test_main.py @@ -0,0 +1,118 @@ +import sys +import threading +import types +from enum import Enum + +import pytest +from PIL import Image + +import main +import registry +from lcdkit import BG +from view import Patch + + +class FakeLcd: + instances = [] + + def __init__(self, com_port="AUTO"): + self.com_port = com_port + self.calls, self.closed, self.orientation, self.brightness = [], False, None, None + FakeLcd.instances.append(self) + + def InitializeComm(self): ... + + def SetOrientation(self, o): + self.orientation = o + + def SetBrightness(self, b): + self.brightness = b + + def DisplayPILImage(self, image, x=0, y=0, image_width=None, image_height=None): + self.calls.append((image.size, x, y)) + + def closeSerial(self): + self.closed = True + + +class FakeOrientation(Enum): + PORTRAIT = 0 + REVERSE_PORTRAIT = 1 + LANDSCAPE = 2 + REVERSE_LANDSCAPE = 3 + + +@pytest.fixture(autouse=True) +def fake_library(monkeypatch): + FakeLcd.instances = [] + lib = types.ModuleType("library") + lcd = types.ModuleType("library.lcd") + comm = types.ModuleType("library.lcd.lcd_comm") + comm.Orientation = FakeOrientation + rev_a = types.ModuleType("library.lcd.lcd_comm_rev_a") + rev_a.LcdCommRevA = FakeLcd + for name, mod in (("library", lib), ("library.lcd", lcd), ("library.lcd.lcd_comm", comm), + ("library.lcd.lcd_comm_rev_a", rev_a)): + monkeypatch.setitem(sys.modules, name, mod) + monkeypatch.setenv("SCREEN_DEVICE", "/dev/fake") + + +class StubView: + name = "stub" + + def __init__(self): + self.started = self.stopped = False + + def start(self): + self.started = True + + def stop(self): + self.stopped = True + + def frame_key(self, now): + return "k" + + def render(self, now): + return Image.new("RGB", (480, 320), BG) + + def patch(self, now): + return None + + +def stop_soon(seconds=0.4): + stop = threading.Event() + threading.Timer(seconds, stop.set).start() + return stop + + +def test_unknown_view_shows_error_and_stays_up_until_stopped(monkeypatch): + monkeypatch.setenv("VIEW", "bogus") + main.main(stop_soon()) + lcd = FakeLcd.instances[0] + assert lcd.calls == [((480, 320), 0, 0)] # the error screen, drawn once + assert lcd.closed + + +def test_missing_view_variable_is_an_error_screen_too(monkeypatch): + monkeypatch.delenv("VIEW", raising=False) + main.main(stop_soon()) + assert FakeLcd.instances[0].calls == [((480, 320), 0, 0)] + + +def test_known_view_runs_and_is_stopped_cleanly(monkeypatch): + view = StubView() + monkeypatch.setitem(registry.REGISTRY, "stub", lambda: view) + monkeypatch.setenv("VIEW", "stub") + main.main(stop_soon()) + lcd = FakeLcd.instances[0] + assert view.started and view.stopped and lcd.closed + assert lcd.calls[0] == ((480, 320), 0, 0) + + +def test_settings_reach_the_screen(monkeypatch): + monkeypatch.setitem(registry.REGISTRY, "stub", StubView) + monkeypatch.setenv("VIEW", "stub") + monkeypatch.setenv("SCREEN_BRIGHTNESS", "70") + main.main(stop_soon(0.2)) + lcd = FakeLcd.instances[0] + assert (lcd.com_port, lcd.orientation, lcd.brightness) == ("/dev/fake", FakeOrientation.LANDSCAPE, 70) diff --git a/tests/test_registry.py b/tests/test_registry.py new file mode 100644 index 0000000..37dbcae --- /dev/null +++ b/tests/test_registry.py @@ -0,0 +1,24 @@ +import pytest + +from registry import REGISTRY, UnknownView, make_view + + +def test_registry_has_both_views(): + assert sorted(REGISTRY) == ["server", "weather"] + + +def test_make_view_builds_named_views(): + assert make_view("weather").name == "weather" + assert make_view("server").name == "server" + + +def test_make_view_unknown_lists_valid_names(): + with pytest.raises(UnknownView) as err: + make_view("bogus") + assert err.value.name == "bogus" + assert err.value.valid == ["server", "weather"] + + +def test_make_view_empty_name_is_unknown(): + with pytest.raises(UnknownView): + make_view("") diff --git a/tests/test_runner.py b/tests/test_runner.py new file mode 100644 index 0000000..6d799b5 --- /dev/null +++ b/tests/test_runner.py @@ -0,0 +1,140 @@ +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): + self._keys = keys # callable(now) -> key + self._with_patch = with_patch + 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 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 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_full_frame_when_key_changes(): + lcd, view = FakeLcd(), StubView(lambda now: now.minute) + 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)] * 3 + + +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) diff --git a/timeutil.py b/timeutil.py new file mode 100644 index 0000000..9688aeb --- /dev/null +++ b/timeutil.py @@ -0,0 +1,12 @@ +"""Wall-clock time independent of the container's own TZ.""" +import os +from datetime import datetime +from zoneinfo import ZoneInfo + +DEFAULT_TZ = "Europe/Prague" + + +def local_now(tz_name: str | None = None) -> datetime: + """Naive wall-clock time in `tz_name` (default: env BOARD_TZ, else Europe/Prague).""" + name = tz_name or os.environ.get("BOARD_TZ", DEFAULT_TZ) + return datetime.now(ZoneInfo(name)).replace(tzinfo=None)