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]>
This commit is contained in:
1 parent
c3a42cf35b
commit
edba341f30
5 files changed
+205
-11
No files matched your search
@@ -14,7 +14,8 @@ Plan: `docs/superpowers/plans/2026-10-22-second-screen.md`. Previews: `docs/prev
|
||||
|
||||
## Switching views
|
||||
|
||||
Edit `VIEW:` in `docker-compose.yml`, commit, `git push`, press **Deploy** in Coolify. An unknown or missing
|
||||
Edit `VIEW:` in `docker-compose.yml`, commit, `git push`, then in Coolify press **Reload Compose** on the app page
|
||||
(it keeps its own copy of the compose file) and **Deploy**. An unknown or missing
|
||||
`VIEW` shows an error screen naming the valid views and keeps the container idle (no restart loop).
|
||||
|
||||
## Add a view
|
||||
@@ -36,7 +37,7 @@ Edit `VIEW:` in `docker-compose.yml`, commit, `git push`, press **Deploy** in Co
|
||||
so Coolify cannot use a deploy key.
|
||||
- Build pack **Docker Compose**, base directory `/`, **Docker Compose Location `/docker-compose.yml`**.
|
||||
- No domain and no environment variables: the defaults in `docker-compose.yml` fit this server.
|
||||
- **Update:** commit, `git push`, press **Deploy** (no webhook).
|
||||
- **Update:** commit, `git push`, press **Reload Compose** if `docker-compose.yml` changed, then **Deploy** (no webhook).
|
||||
- **Logs:** Coolify → the application → Logs, or `ssh coolify 'docker logs --tail 30 <container>'`.
|
||||
- Only one container can hold a screen's serial port. Stop manual copies before deploying.
|
||||
|
||||
@@ -84,4 +85,7 @@ The screen library is pinned to one upstream commit in the `Dockerfile` (`LCD_CO
|
||||
- The weather graph is the next 12 hours from now, so late in the day it runs into tomorrow.
|
||||
- Server stats: process CPU is a share of the whole machine and grouped by command name; temperature is the CPU
|
||||
package sensor if the host has one, else the hottest thermal zone.
|
||||
- Seconds are redrawn once per second with a small partial update.
|
||||
- The screen's link moves about 150 KB/s (measured 2026-10-22: a full 480x320 frame takes 1.96 s, a 96x52 box 65 ms),
|
||||
and time grows with the bytes sent. So after the first frame the runner sends only the rectangles that changed
|
||||
(`regions.py`), a full frame when more than 60 % of the screen changed or after any failed push, and a full refresh
|
||||
every 15 minutes. The weather seconds are a small patch once per second.
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
"""Find what changed between two frames, so only that is sent over the slow serial link."""
|
||||
from PIL import Image, ImageChops
|
||||
|
||||
TILE = 32
|
||||
|
||||
Box = tuple[int, int, int, int] # x0, y0, x1, y1 (x1, y1 exclusive)
|
||||
|
||||
|
||||
def changed_regions(old: Image.Image, new: Image.Image, tile: int = TILE) -> list[Box]:
|
||||
"""Tight boxes around the pixels that differ.
|
||||
|
||||
The frame is cut into tiles; consecutive changed tiles in one tile row become a single box, trimmed to the
|
||||
pixels that actually changed. The screen's link costs time per byte only, so many small boxes are fine.
|
||||
"""
|
||||
if old.size != new.size:
|
||||
raise ValueError(f"size mismatch: {old.size} vs {new.size}")
|
||||
diff = ImageChops.difference(old.convert("RGB"), new.convert("RGB"))
|
||||
if diff.getbbox() is None:
|
||||
return []
|
||||
width, height = diff.size
|
||||
boxes: list[Box] = []
|
||||
for ty in range(0, height, tile):
|
||||
run: Box | None = None
|
||||
for tx in range(0, width, tile):
|
||||
inner = diff.crop((tx, ty, min(tx + tile, width), min(ty + tile, height))).getbbox()
|
||||
if inner is not None:
|
||||
box = (tx + inner[0], ty + inner[1], tx + inner[2], ty + inner[3])
|
||||
run = box if run is None else (min(run[0], box[0]), min(run[1], box[1]),
|
||||
max(run[2], box[2]), max(run[3], box[3]))
|
||||
elif run is not None:
|
||||
boxes.append(run)
|
||||
run = None
|
||||
if run is not None:
|
||||
boxes.append(run)
|
||||
return boxes
|
||||
@@ -8,12 +8,15 @@ 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:
|
||||
@@ -55,28 +58,51 @@ def idle_with_message(lcd, lines: Sequence[str], *, running: Callable[[], bool],
|
||||
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) -> None:
|
||||
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:
|
||||
lcd.DisplayPILImage(view.render(now), 0, 0)
|
||||
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 everything on the next tick
|
||||
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)
|
||||
@@ -0,0 +1,52 @@
|
||||
import numpy as np
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from lcdkit import BG
|
||||
from regions import changed_regions
|
||||
|
||||
|
||||
def blank(w=480, h=320):
|
||||
return Image.new("RGB", (w, h), BG)
|
||||
|
||||
|
||||
def with_pixels(points, colour=(0, 0, 0)):
|
||||
img = blank()
|
||||
for p in points:
|
||||
img.putpixel(p, colour)
|
||||
return img
|
||||
|
||||
|
||||
def test_identical_images_have_no_changed_regions():
|
||||
assert changed_regions(blank(), blank()) == []
|
||||
|
||||
|
||||
def test_single_pixel_gives_a_tight_box():
|
||||
assert changed_regions(blank(), with_pixels([(100, 50)])) == [(100, 50, 101, 51)]
|
||||
|
||||
|
||||
def test_far_apart_changes_are_separate_boxes():
|
||||
boxes = changed_regions(blank(), with_pixels([(10, 10), (400, 250)]))
|
||||
assert boxes == [(10, 10, 11, 11), (400, 250, 401, 251)]
|
||||
|
||||
|
||||
def test_neighbouring_tiles_in_a_row_merge_into_one_box():
|
||||
# x=10 is in tile 0 and x=40 in tile 1 (32 px tiles): one run, tight bounding box
|
||||
assert changed_regions(blank(), with_pixels([(10, 10), (40, 12)])) == [(10, 10, 41, 13)]
|
||||
|
||||
|
||||
def test_boxes_always_cover_every_changed_pixel():
|
||||
rng = np.random.default_rng(7)
|
||||
for _ in range(20):
|
||||
points = [(int(rng.integers(0, 480)), int(rng.integers(0, 320))) for _ in range(int(rng.integers(1, 12)))]
|
||||
new = with_pixels(points)
|
||||
boxes = changed_regions(blank(), new)
|
||||
for x, y in points:
|
||||
assert any(x0 <= x < x1 and y0 <= y < y1 for x0, y0, x1, y1 in boxes), (x, y, boxes)
|
||||
for x0, y0, x1, y1 in boxes: # and stay inside the image
|
||||
assert 0 <= x0 < x1 <= 480 and 0 <= y0 < y1 <= 320
|
||||
|
||||
|
||||
def test_size_mismatch_is_an_error():
|
||||
with pytest.raises(ValueError):
|
||||
changed_regions(blank(480, 320), blank(320, 480))
|
||||
+82
-5
@@ -25,9 +25,10 @@ class FakeLcd:
|
||||
class StubView:
|
||||
name = "stub"
|
||||
|
||||
def __init__(self, keys, with_patch=True):
|
||||
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): ...
|
||||
@@ -38,12 +39,19 @@ class StubView:
|
||||
|
||||
def render(self, now):
|
||||
self.renders += 1
|
||||
return Image.new("RGB", (480, 320), BG)
|
||||
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}
|
||||
@@ -83,10 +91,12 @@ def test_run_pushes_patch_each_new_second_only():
|
||||
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)
|
||||
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 [c[0] for c in lcd.calls] == [(480, 320)] * 3
|
||||
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():
|
||||
@@ -163,3 +173,70 @@ def test_run_counts_library_sys_exit_as_a_failed_draw():
|
||||
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)]
|
||||
Reference in new issue
Block a user