diff --git a/docs/previews/weather.png b/docs/previews/weather.png new file mode 100644 index 0000000..d709c9c Binary files /dev/null and b/docs/previews/weather.png differ diff --git a/preview.py b/preview.py new file mode 100644 index 0000000..dc1fe85 --- /dev/null +++ b/preview.py @@ -0,0 +1,60 @@ +"""Render every view with fake data to docs/previews/*.png (no screen, no network needed).""" +from datetime import datetime +from pathlib import Path + +from PIL import Image + +from lcdkit import H, W +from weather_data import Hour, Weather +from weather_view import WeatherView + +OUT = Path(__file__).parent / "docs" / "previews" +NOW = datetime(2026, 10, 22, 14, 32, 8) # a Thursday afternoon + + +class FakePoller: + def __init__(self, value, age: float | None = 60.0): + self.value, self.version, self.failures, self._age = value, 1 if value is not None else 0, 0, age + + def age(self): + return self._age + + def start(self): + pass + + def stop(self): + pass + + +def fake_weather(temp=14.2, rain=(0, 0, 10, 20, 40, 70, 60, 50, 30, 20, 10, 0), code=2) -> Weather: + hours = tuple(Hour(datetime(2026, 10, 22, 14 + i, 0) if 14 + i < 24 else datetime(2026, 10, 23, 14 + i - 24, 0), + p, 0.3) for i, p in enumerate(rain)) + return Weather(temp=temp, code=code, today_max=16.0, today_min=7.0, hours=hours) + + +def sheet(images: list[Image.Image], columns: int = 2) -> Image.Image: + rows = -(-len(images) // columns) + out = Image.new("RGB", (columns * W + (columns - 1) * 20, rows * H + (rows - 1) * 20), (40, 40, 40)) + for i, img in enumerate(images): + out.paste(img, ((i % columns) * (W + 20), (i // columns) * (H + 20))) + return out + + +def weather_previews() -> Image.Image: + cases = [ + FakePoller(fake_weather()), + FakePoller(fake_weather(temp=-3.4, rain=(100,) * 12, code=71)), + FakePoller(None, age=None), + FakePoller(fake_weather(code=95), age=7200.0), + ] + return sheet([WeatherView(p).render(NOW) for p in cases]) + + +def main() -> None: + OUT.mkdir(parents=True, exist_ok=True) + weather_previews().save(OUT / "weather.png") + print(OUT / "weather.png") + + +if __name__ == "__main__": + main() diff --git a/tests/test_weather_view.py b/tests/test_weather_view.py new file mode 100644 index 0000000..76b586e --- /dev/null +++ b/tests/test_weather_view.py @@ -0,0 +1,139 @@ +from datetime import datetime + +import numpy as np +from PIL import ImageChops + +from lcdkit import INK +from tests.helpers import count_colour +from view import Patch +from weather_data import Hour, Weather +from weather_view import WeatherView + +NOW = datetime(2026, 10, 22, 12, 45, 8) # a Thursday + + +class StubPoller: + def __init__(self, value=None, version=1, age=60.0): + self.value, self.version, self._age = value, version, age + self.failures = 0 + + def age(self): + return self._age + + def start(self): + pass + + def stop(self): + pass + + +def weather(temp=14.2, rain=(0, 0, 10, 20, 40, 70, 60, 50, 30, 20, 10, 0), code=2): + hours = tuple(Hour(datetime(2026, 10, 22, 12 + i, 0), p, 0.2) for i, p in enumerate(rain)) + return Weather(temp=temp, code=code, today_max=16.0, today_min=7.0, hours=hours) + + +def view(**kw): + return WeatherView(StubPoller(**kw)) + + +def ink_bbox(img, box): + """Bounding box of INK pixels inside `box`, in image coordinates, or None.""" + region = np.asarray(img.crop(box).convert("RGB")) + ys, xs = np.where((region == np.array(INK)).all(axis=2)) + if len(xs) == 0: + return None + return (box[0] + xs.min(), box[1] + ys.min(), box[0] + xs.max(), box[1] + ys.max()) + + +def test_render_size_is_480x320(): + assert view(value=weather()).render(NOW).size == (480, 320) + + +def test_frame_key_changes_each_minute_not_each_second(): + v = view(value=weather()) + assert v.frame_key(datetime(2026, 10, 22, 12, 45, 0)) == v.frame_key(datetime(2026, 10, 22, 12, 45, 59)) + assert v.frame_key(datetime(2026, 10, 22, 12, 45, 59)) != v.frame_key(datetime(2026, 10, 22, 12, 46, 0)) + + +def test_frame_key_changes_when_weather_updates(): + p = StubPoller(value=weather(), version=1) + v = WeatherView(p) + before = v.frame_key(NOW) + p.version = 2 + assert v.frame_key(NOW) != before + + +def test_frame_key_changes_when_stale_flips(): + p = StubPoller(value=weather(), age=60.0) + v = WeatherView(p) + before = v.frame_key(NOW) + p._age = WeatherView.STALE_AFTER + 1 + assert v.frame_key(NOW) != before + + +def test_patch_matches_full_render_region(): + v = view(value=weather()) + patch = v.patch(NOW) + assert isinstance(patch, Patch) + full = v.render(NOW) + region = full.crop((patch.x, patch.y, patch.x + patch.image.width, patch.y + patch.image.height)) + assert ImageChops.difference(region.convert("RGB"), patch.image.convert("RGB")).getbbox() is None + + +def test_patch_changes_with_the_second(): + v = view(value=weather()) + a = v.patch(datetime(2026, 10, 22, 12, 45, 8)).image + b = v.patch(datetime(2026, 10, 22, 12, 45, 9)).image + assert ImageChops.difference(a, b).getbbox() is not None + + +def test_no_weather_renders_without_error(): + img = view(value=None, version=0, age=None).render(NOW) + assert img.size == (480, 320) + # weekday strip, clock and dashes are still drawn + assert count_colour(img, INK) > 1000 + + +def test_stale_tag_only_when_old(): + fresh = view(value=weather(), age=60.0).render(NOW) + old = view(value=weather(), age=7200.0).render(NOW) + bbox = ImageChops.difference(fresh.convert("RGB"), old.convert("RGB")).getbbox() + assert bbox is not None + assert bbox[0] >= 20 and bbox[1] >= 160 and bbox[2] <= 204 and bbox[3] <= 186 + + +def test_hundred_percent_fits(): + rain = (100,) * 12 + img = view(value=weather(rain=rain)).render(NOW) + box = ink_bbox(img, (14, 262, 204, 312)) + assert box is not None and box[2] < 200 + + +def test_negative_temp_fits_and_draws_minus(): + cold = view(value=weather(temp=-3.4)).render(NOW) + warm = view(value=weather(temp=3.4)).render(NOW) + cold_box = ink_bbox(cold, (84, 180, 204, 236)) + assert cold_box is not None and cold_box[2] < 200 + assert ImageChops.difference(cold.convert("RGB"), warm.convert("RGB")).getbbox() is not None + + +def test_sunday_inverts_last_weekday_cell(): + sunday = datetime(2026, 10, 25, 9, 0, 0) + img = view(value=weather()).render(sunday) + assert img.getpixel((402 + 1, 15)) == INK # NE cell + assert img.getpixel((12 + 1, 15)) != INK # PO cell + + +def test_thursday_inverts_fourth_cell(): + img = view(value=weather()).render(NOW) + assert img.getpixel((12 + 3 * 65 + 1, 15)) == INK # ČT + assert img.getpixel((12 + 1, 15)) != INK + + +def test_fewer_than_twelve_hours_still_renders(): + img = view(value=weather(rain=(10, 20))).render(NOW) + assert img.size == (480, 320) + + +def test_unknown_weather_code_renders(): + assert view(value=weather(code=999)).render(NOW).size == (480, 320) diff --git a/view.py b/view.py new file mode 100644 index 0000000..f5147cf --- /dev/null +++ b/view.py @@ -0,0 +1,31 @@ +"""What a screen view looks like to the runner.""" +from dataclasses import dataclass +from datetime import datetime +from typing import Hashable, Protocol + +from PIL import Image + + +@dataclass +class Patch: + """A partial update: draw `image` with its top-left corner at (x, y).""" + image: Image.Image + x: int + y: int + + +class View(Protocol): + name: str + + def start(self) -> None: ... + + def stop(self) -> None: ... + + def frame_key(self, now: datetime) -> Hashable: + """Changes whenever a full redraw is needed.""" + + def render(self, now: datetime) -> Image.Image: + """The full 480x320 frame.""" + + def patch(self, now: datetime) -> Patch | None: + """Cheap partial update valid while frame_key is unchanged (e.g. the seconds).""" diff --git a/weather_view.py b/weather_view.py new file mode 100644 index 0000000..01fb14b --- /dev/null +++ b/weather_view.py @@ -0,0 +1,162 @@ +"""Casio-style weather clock: time, date, current weather and a 12 hour rain forecast.""" +from datetime import datetime + +from PIL import Image, ImageDraw + +import lcdkit +from lcdkit import BG, H, INK, W +from poller import Poller +from view import Patch +from weather_data import Icon, Weather, icon_for + +WEEKDAYS = ["PO", "ÚT", "ST", "ČT", "PÁ", "SO", "NE"] +SECONDS_BOX = (370, 52, 466, 104) # region redrawn once per second +SECONDS_GEOMETRY = dict(x=378, y=58, w=24, h=42, t=6, gap=6) +GRAPH_X, GRAPH_PITCH, GRAPH_BOTTOM = 222, 21, 282 + + +def _cloud(d: ImageDraw.ImageDraw, x: float, base: float, s: float, outline: bool = False) -> None: + """A cloud of width ~0.8*s sitting on the line y=base; `outline` first paints a background halo.""" + for pad, colour in ((3, BG), (0, INK)) if outline else ((0, INK),): + d.ellipse((x + s * 0.30 - pad, base - s * 0.34 - pad, x + s * 0.68 + pad, base + pad), fill=colour) + d.ellipse((x + s * 0.52 - pad, base - s * 0.26 - pad, x + s * 0.95 + pad, base + pad), fill=colour) + d.rounded_rectangle((x + s * 0.18 - pad, base - s * 0.20 - pad, x + s * 0.95 + pad, base + pad), + radius=int(s * 0.1), fill=colour) + + +def _sun(d: ImageDraw.ImageDraw, cx: float, cy: float, r: float, s: float) -> None: + d.ellipse((cx - r, cy - r, cx + r, cy + r), fill=INK) + for dx, dy in ((0, -1), (0, 1), (-1, 0), (1, 0), (-.7, -.7), (.7, -.7), (-.7, .7), (.7, .7)): + d.line((cx + dx * r * 1.35, cy + dy * r * 1.35, cx + dx * r * 1.8, cy + dy * r * 1.8), + fill=INK, width=max(2, int(s / 16))) + + +def draw_icon(d: ImageDraw.ImageDraw, icon: Icon | None, x: float, y: float, s: float) -> None: + w = max(2, int(s / 16)) + if icon is Icon.SUN: + _sun(d, x + s / 2, y + s / 2, s * 0.22, s) + elif icon is Icon.PARTLY: + _sun(d, x + s * 0.36, y + s * 0.36, s * 0.2, s) + _cloud(d, x, y + s * 0.82, s, outline=True) + elif icon is Icon.CLOUDY: + _cloud(d, x, y + s * 0.75, s) + elif icon is Icon.RAIN: + _cloud(d, x, y + s * 0.6, s) + for i in range(3): + dx = x + s * (0.3 + 0.2 * i) + d.line((dx + 4, y + s * 0.68, dx - 2, y + s * 0.92), fill=INK, width=w) + elif icon is Icon.SNOW: + _cloud(d, x, y + s * 0.6, s) + for i in range(3): + dx, dy = x + s * (0.3 + 0.2 * i), y + s * (0.8 if i % 2 == 0 else 0.9) + d.rectangle((dx - 2, dy - 2, dx + 2, dy + 2), fill=INK) + elif icon is Icon.STORM: + _cloud(d, x, y + s * 0.6, s) + bolt = [(x + s * 0.52, y + s * 0.62), (x + s * 0.40, y + s * 0.80), (x + s * 0.50, y + s * 0.80), + (x + s * 0.44, y + s * 0.98), (x + s * 0.62, y + s * 0.74), (x + s * 0.52, y + s * 0.74)] + d.polygon(bolt, fill=INK) + elif icon is Icon.FOG: + for i in range(4): + off = s * 0.08 if i % 2 else 0 + yy = y + s * (0.25 + 0.17 * i) + d.line((x + s * 0.12 + off, yy, x + s * 0.88 + off, yy), fill=INK, width=w + 1) + + +class WeatherView: + name = "weather" + STALE_AFTER = 3600.0 # seconds without a successful fetch before the data is marked old + + def __init__(self, poller: Poller[Weather]) -> None: + self._poller = poller + + def start(self) -> None: + self._poller.start() + + def stop(self) -> None: + self._poller.stop() + + def _is_stale(self) -> bool: + age = self._poller.age() + return age is not None and age > self.STALE_AFTER + + def frame_key(self, now: datetime): + return (now.strftime("%Y%m%d%H%M"), self._poller.version, self._is_stale()) + + def patch(self, now: datetime) -> Patch: + x0, y0, x1, y1 = SECONDS_BOX + img = Image.new("RGB", (x1 - x0, y1 - y0), BG) + g = SECONDS_GEOMETRY + lcdkit.number(ImageDraw.Draw(img), f"{now.second:02d}", g["x"] - x0, g["y"] - y0, g["w"], g["h"], + g["t"], g["gap"]) + return Patch(img, x0, y0) + + def render(self, now: datetime) -> Image.Image: + weather: Weather | None = self._poller.value + img = Image.new("RGB", (W, H), BG) + d = ImageDraw.Draw(img) + f_small, f_tiny = lcdkit.load_font(15), lcdkit.load_font(12) + + d.rectangle((6, 6, W - 7, H - 7), outline=INK, width=2) + self._weekday_strip(d, now, f_small) + d.line((12, 46, W - 13, 46), fill=INK, width=2) + + # time row: HH:MM, seconds and date on the right + lcdkit.number(d, now.strftime("%H:%M"), 24, 54, 54, 96, 12, 9) + x0, y0, _, _ = SECONDS_BOX + img.paste(self.patch(now).image, (x0, y0)) + lcdkit.number(d, now.strftime("%-d.%-m."), 372, 112, 14, 34, 4, 4, ghost=False) + d.line((12, 160, W - 13, 160), fill=INK, width=2) + + self._current_block(d, weather, f_small, f_tiny) + d.line((206, 168, 206, H - 14), fill=INK, width=2) + self._rain_graph(d, weather, f_small, f_tiny) + if self._is_stale(): + label_w = d.textlength("ZLÍN NYNÍ", font=f_tiny) + lcdkit.tag(d, (int(22 + label_w + 8), 163), "STARÉ", f_tiny) + return img + + @staticmethod + def _weekday_strip(d: ImageDraw.ImageDraw, now: datetime, font) -> None: + cell = (W - 24) // 7 + for i, name in enumerate(WEEKDAYS): + x0 = 12 + i * cell + colour = INK + if i == now.weekday(): + d.rectangle((x0, 14, x0 + cell - 6, 38), fill=INK) + colour = BG + text_w = d.textlength(name, font=font) + d.text((x0 + (cell - 6 - text_w) / 2, 17), name, font=font, fill=colour) + + @staticmethod + def _current_block(d: ImageDraw.ImageDraw, weather: Weather | None, f_small, f_tiny) -> None: + d.text((22, 166), "ZLÍN NYNÍ", font=f_tiny, fill=INK) + temp = weather.temp if weather else None + if weather: + draw_icon(d, icon_for(weather.code), 20, 182, 56) + end = lcdkit.number(d, lcdkit.fmt_temp(temp), 90, 184, 26, 46, 6, 7, ghost=False) + if temp is not None: + d.ellipse((end + 4, 184, end + 14, 194), outline=INK, width=3) + hi = lcdkit.fmt_temp(weather.today_max) if weather else "--" + lo = lcdkit.fmt_temp(weather.today_min) if weather else "--" + d.text((22, 244), f"MAX {hi}° MIN {lo}°", font=f_small, fill=INK) + + d.text((22, 264), "DEŠŤ", font=f_tiny, fill=INK) + chances = [h.rain_pct for h in (weather.hours if weather else ()) if h.rain_pct is not None] + text = str(max(chances)) if chances else "--" + x = lcdkit.number(d, text, 22, 279, 18, 28, 4, 6, ghost=False) + if chances: + d.text((x + 4, 288), "%", font=f_small, fill=INK) + + @staticmethod + def _rain_graph(d: ImageDraw.ImageDraw, weather: Weather | None, f_small, f_tiny) -> None: + d.text((220, 166), "DEŠŤ % / HOD", font=f_tiny, fill=INK) + hours = weather.hours if weather else () + mm = f"{sum(h.mm or 0 for h in hours):.1f} mm" if hours else "-- mm" + d.text((W - 18 - d.textlength(mm, font=f_small), 164), mm, font=f_small, fill=INK) + for i in range(12): + bx = GRAPH_X + i * GRAPH_PITCH + hour = hours[i] if i < len(hours) else None + lcdkit.v_bar(d, bx, GRAPH_BOTTOM, hour.rain_pct if hour else None, 14, 16, 5, 1) + if hour is not None and i % 3 == 0: + label = f"{hour.time.hour:02d}" + d.text((bx + 7 - d.textlength(label, font=f_tiny) / 2, 290), label, font=f_tiny, fill=INK)