Week ahead in the weather strip, reverse LCD at night

The weekday strip now shows today and the next six days (icon, max, min),
the current temperature and feels-like sit next to the clock, and the rain
graph spans the full width with the hour under every bar. From sunset to
sunrise the whole frame, seconds patch included, is drawn as a reverse LCD.
The rain label is now spelled DÉŠŤ.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
rickzkmandClaude Opus 5.5 committed 2026-10-28 22:40:34 +01:00
1 parent 45508b1b68
commit 6c9a1420d2
10 files changed
+341 -122

No files matched your search

+4 -1
View File
@@ -7,7 +7,7 @@ shapes, glitch numbers) for the server stats:
| `VIEW` | Shows |
|---|---|
| `weather` | Czech weekday strip, big `HH:MM` with seconds, date, current weather for Zlín, today's max/min, highest rain chance and a 12-hour rain probability bar graph with the total mm |
| `weather` | The week ahead in the Czech weekday strip (today first and inverted: icon, max and min for each day), big `HH:MM` with seconds, date, current temperature and feels-like (`POCIT`) for Zlín, and a 12-hour rain probability bar graph with the hour under every bar and the total mm. From sunset to sunrise the whole screen turns into a reverse LCD (light segments on black) |
| `server` | Cyberpunk style: CPU / RAM / disk gauges (red from 80 %), load, CPU temperature, uptime, Docker containers (readable names and status chips) and the busiest processes. Refreshed every second; the container list every 5 s and the process ranking over 3 s windows |
Design: `docs/superpowers/specs/2026-10-22-second-screen-design.md`.
@@ -83,6 +83,9 @@ The screen library is pinned to one upstream commit in the `Dockerfile` (`LCD_CO
## Known limitations
- Weather comes from Open-Meteo for Zlín only (coordinates in `weather_data.py`), refreshed every 15 minutes.
- Night mode uses the forecast's sunrise and sunset for today. If the forecast has no today (fetches failing for
days), the closest day's times are used; with no forecast at all (right after a start) the screen stays in day
mode. Switching day/night redraws the whole screen once (about 2 s).
- 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.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 51 KiB

+12 -1
View File
@@ -3,13 +3,16 @@ from functools import lru_cache
from pathlib import Path
from typing import Sequence
from PIL import ImageDraw, ImageFont
import numpy as np
from PIL import Image, ImageDraw, ImageFont
W, H = 480, 320
BG = (170, 184, 154)
INK = (28, 36, 24)
GHOST = (158, 172, 143) # unlit segments, barely darker than the background
SLANT = 0.14
NIGHT_BG = (12, 15, 12) # reverse LCD: light segments on black
NIGHT_INK = (196, 214, 184)
FONT_PATH = Path(__file__).parent / "assets" / "fonts" / "Roboto-Bold.ttf"
SEGMENT_GAP = 1.5
@@ -20,6 +23,14 @@ DIGIT_SEGMENTS = {
}
def night(img: Image.Image) -> Image.Image:
"""The same frame as a reverse LCD: background becomes NIGHT_BG, ink NIGHT_INK, everything between in step."""
a = np.asarray(img.convert("RGB")).astype(np.float32)
t = np.clip((a[..., 0] - INK[0]) / (BG[0] - INK[0]), 0, 1)[..., None] # 0 at ink, 1 at background
ink, bg = np.array(NIGHT_INK, np.float32), np.array(NIGHT_BG, np.float32)
return Image.fromarray(np.round(ink + (bg - ink) * t).astype(np.uint8))
def _slant(points: Sequence[tuple[float, float]], base_y: float) -> list[tuple[float, float]]:
return [(x + SLANT * (base_y - y), y) for x, y in points]
+17 -8
View File
@@ -1,11 +1,11 @@
"""Render every view with fake data to docs/previews/*.png (no screen, no network needed)."""
from datetime import datetime
from datetime import date, datetime, time, timedelta
from pathlib import Path
from PIL import Image
from lcdkit import H, W
from weather_data import Hour, Weather
from weather_data import Day, Hour, Weather
from server_view import ServerView
from stats_data import Container, Proc, Stats
from weather_view import WeatherView
@@ -28,10 +28,18 @@ class FakePoller:
pass
WEEK = ((2, 16.0, 7.0), (3, 13.0, 8.0), (61, 11.0, 6.0), (80, 9.0, 4.0), (0, 12.0, 2.0), (1, 14.0, 5.0),
(71, 4.0, -1.0))
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)
days = tuple(Day(date(2026, 10, 22) + timedelta(days=i), c, hi, lo,
datetime.combine(date(2026, 10, 22) + timedelta(days=i), time(7, 20)),
datetime.combine(date(2026, 10, 22) + timedelta(days=i), time(17, 45)))
for i, (c, hi, lo) in enumerate(WEEK))
return Weather(temp=temp, feels=temp - 2.1, code=code, days=days, hours=hours)
def sheet(images: list[Image.Image], columns: int = 2) -> Image.Image:
@@ -44,12 +52,13 @@ def sheet(images: list[Image.Image], columns: int = 2) -> Image.Image:
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),
(FakePoller(fake_weather()), NOW),
(FakePoller(fake_weather(temp=-3.4, rain=(100,) * 12, code=71)), NOW),
(FakePoller(None, age=None), NOW),
(FakePoller(fake_weather(code=95), age=7200.0), NOW),
(FakePoller(fake_weather()), NOW.replace(hour=21, minute=7)), # after sunset: reverse LCD
]
return sheet([WeatherView(p).render(NOW) for p in cases])
return sheet([WeatherView(p).render(now) for p, now in cases])
REAL_NAMES = ["coolify", "coolify-db", "coolify-redis", "coolify-sentinel", "gitea", "jn5mdu87", "task-runners",
+1 -1
View File
@@ -1 +1 @@
{"latitude":49.23005,"longitude":17.657297,"generationtime_ms":0.3495216369628906,"utc_offset_seconds":7200,"timezone":"Europe/Prague","timezone_abbreviation":"GMT+2","elevation":221.0,"current_units":{"time":"iso8601","interval":"seconds","temperature_2m":"°C","weather_code":"wmo code"},"current":{"time":"2026-10-22T12:45","interval":900,"temperature_2m":10.2,"weather_code":61},"hourly_units":{"time":"iso8601","precipitation_probability":"%","precipitation":"mm"},"hourly":{"time":["2026-10-22T00:00","2026-10-22T01:00","2026-10-22T02:00","2026-10-22T03:00","2026-10-22T04:00","2026-10-22T05:00","2026-10-22T06:00","2026-10-22T07:00","2026-10-22T08:00","2026-10-22T09:00","2026-10-22T10:00","2026-10-22T11:00","2026-10-22T12:00","2026-10-22T13:00","2026-10-22T14:00","2026-10-22T15:00","2026-10-22T16:00","2026-10-22T17:00","2026-10-22T18:00","2026-10-22T19:00","2026-10-22T20:00","2026-10-22T21:00","2026-10-22T22:00","2026-10-22T23:00","2026-10-23T00:00","2026-10-23T01:00","2026-10-23T02:00","2026-10-23T03:00","2026-10-23T04:00","2026-10-23T05:00","2026-10-23T06:00","2026-10-23T07:00","2026-10-23T08:00","2026-10-23T09:00","2026-10-23T10:00","2026-10-23T11:00","2026-10-23T12:00","2026-10-23T13:00","2026-10-23T14:00","2026-10-23T15:00","2026-10-23T16:00","2026-10-23T17:00","2026-10-23T18:00","2026-10-23T19:00","2026-10-23T20:00","2026-10-23T21:00","2026-10-23T22:00","2026-10-23T23:00"],"precipitation_probability":[93,98,100,100,100,100,100,100,100,100,100,98,93,98,63,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,5,3,0],"precipitation":[0.40,1.80,2.50,3.80,2.00,2.20,2.30,1.40,2.60,3.50,1.80,1.00,0.40,0.50,0.40,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00]},"daily_units":{"time":"iso8601","temperature_2m_max":"°C","temperature_2m_min":"°C"},"daily":{"time":["2026-10-22","2026-10-23"],"temperature_2m_max":[15.0,14.3],"temperature_2m_min":[6.0,2.2]}}
{"latitude":49.23005,"longitude":17.657297,"generationtime_ms":0.3495216369628906,"utc_offset_seconds":7200,"timezone":"Europe/Prague","timezone_abbreviation":"GMT+2","elevation":221.0,"current_units":{"time":"iso8601","interval":"seconds","temperature_2m":"°C","weather_code":"wmo code","apparent_temperature":"°C"},"current":{"time":"2026-10-22T12:45","interval":900,"temperature_2m":10.2,"weather_code":61,"apparent_temperature":8.1},"hourly_units":{"time":"iso8601","precipitation_probability":"%","precipitation":"mm"},"hourly":{"time":["2026-10-22T00:00","2026-10-22T01:00","2026-10-22T02:00","2026-10-22T03:00","2026-10-22T04:00","2026-10-22T05:00","2026-10-22T06:00","2026-10-22T07:00","2026-10-22T08:00","2026-10-22T09:00","2026-10-22T10:00","2026-10-22T11:00","2026-10-22T12:00","2026-10-22T13:00","2026-10-22T14:00","2026-10-22T15:00","2026-10-22T16:00","2026-10-22T17:00","2026-10-22T18:00","2026-10-22T19:00","2026-10-22T20:00","2026-10-22T21:00","2026-10-22T22:00","2026-10-22T23:00","2026-10-23T00:00","2026-10-23T01:00","2026-10-23T02:00","2026-10-23T03:00","2026-10-23T04:00","2026-10-23T05:00","2026-10-23T06:00","2026-10-23T07:00","2026-10-23T08:00","2026-10-23T09:00","2026-10-23T10:00","2026-10-23T11:00","2026-10-23T12:00","2026-10-23T13:00","2026-10-23T14:00","2026-10-23T15:00","2026-10-23T16:00","2026-10-23T17:00","2026-10-23T18:00","2026-10-23T19:00","2026-10-23T20:00","2026-10-23T21:00","2026-10-23T22:00","2026-10-23T23:00"],"precipitation_probability":[93,98,100,100,100,100,100,100,100,100,100,98,93,98,63,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,5,3,0],"precipitation":[0.4,1.8,2.5,3.8,2.0,2.2,2.3,1.4,2.6,3.5,1.8,1.0,0.4,0.5,0.4,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]},"daily_units":{"time":"iso8601","weather_code":"wmo code","temperature_2m_max":"°C","temperature_2m_min":"°C","sunrise":"iso8601","sunset":"iso8601"},"daily":{"time":["2026-10-22","2026-10-23","2026-10-24","2026-10-25","2026-10-26","2026-10-27","2026-10-28"],"weather_code":[63,45,61,63,80,45,45],"temperature_2m_max":[15.0,14.3,12.1,10.2,11.2,10.0,11.5],"temperature_2m_min":[6.0,2.2,4.3,0.8,1.9,-0.2,-0.5],"sunrise":["2026-10-22T07:20","2026-10-23T07:22","2026-10-24T07:24","2026-10-25T06:25","2026-10-26T06:27","2026-10-27T06:28","2026-10-28T06:30"],"sunset":["2026-10-22T17:45","2026-10-23T17:44","2026-10-24T17:42","2026-10-25T16:40","2026-10-26T16:38","2026-10-27T16:36","2026-10-28T16:35"]}}
+19
View File
@@ -81,3 +81,22 @@ def test_tag_is_ink_box_and_returns_its_box():
x0, y0, x1, y1 = box
assert img.getpixel((x0 + 1, y0 + 1)) == INK
assert x1 > x0 and y1 > y0
def test_night_turns_background_dark_and_ink_light():
img = Image.new("RGB", (3, 1), BG)
img.putpixel((1, 0), INK)
img.putpixel((2, 0), GHOST)
bg, ink, ghost = (sum(lcdkit.night(img).getpixel((x, 0))) for x in range(3))
assert bg < 100 and ink > 450
# unlit segments stay faint: a little lighter than the background, nowhere near the ink
assert bg < ghost < (bg + ink) / 2
def test_night_keeps_antialiased_text_in_between():
mid = tuple((a + b) // 2 for a, b in zip(INK, BG))
img = Image.new("RGB", (3, 1), BG)
img.putpixel((1, 0), INK)
img.putpixel((2, 0), mid)
bg, ink, edge = (sum(lcdkit.night(img).getpixel((x, 0))) for x in range(3))
assert bg < edge < ink
+52 -5
View File
@@ -1,10 +1,10 @@
import copy
import json
from datetime import datetime
from datetime import date, datetime
from pathlib import Path
import weather_data
from weather_data import Icon, icon_for, parse_weather
from weather_data import Day, Icon, icon_for, parse_weather
FIXTURE = json.loads((Path(__file__).parent / "fixtures" / "open-meteo-zlin.json").read_text())
NOW = datetime(2026, 10, 22, 12, 45)
@@ -24,9 +24,34 @@ def test_parse_fixture_window():
assert (w.temp, w.code) == (10.2, 61)
def test_parse_today_max_min():
def test_parse_week_with_sunrise_and_sunset():
w = parse_weather(payload(), NOW)
assert (w.today_max, w.today_min) == (15.0, 6.0)
assert len(w.days) == 7
assert w.days[0] == Day(date(2026, 10, 22), 63, 15.0, 6.0,
datetime(2026, 10, 22, 7, 20), datetime(2026, 10, 22, 17, 45))
assert w.days[6] == Day(date(2026, 10, 28), 45, 11.5, -0.5,
datetime(2026, 10, 28, 6, 30), datetime(2026, 10, 28, 16, 35))
def test_parse_feels_like():
assert parse_weather(payload(), NOW).feels == 8.1
def test_null_day_entries_become_none():
p = payload()
p["daily"]["weather_code"][1] = None
p["daily"]["sunset"][1] = None
day = parse_weather(p, NOW).days[1]
assert (day.code, day.sunset) == (None, None)
assert day.sunrise == datetime(2026, 10, 23, 7, 22)
def test_short_daily_lists_give_none_not_errors():
p = payload()
p["daily"]["temperature_2m_min"] = p["daily"]["temperature_2m_min"][:3]
w = parse_weather(p, NOW)
assert len(w.days) == 7
assert (w.days[2].low, w.days[3].low) == (4.3, None)
def test_window_runs_into_tomorrow_late_in_the_day():
@@ -74,7 +99,7 @@ def test_missing_current_gives_none_temp():
def test_missing_sections_do_not_raise():
w = parse_weather({}, NOW)
assert (w.temp, w.today_max, w.hours) == (None, None, ())
assert (w.temp, w.feels, w.days, w.hours) == (None, None, (), ())
def test_fetch_passes_coordinates():
@@ -99,3 +124,25 @@ def test_fetch_passes_coordinates():
assert params["timezone"] == "Europe/Prague"
assert timeout == 10
assert len(w.hours) == 12
assert len(w.days) == 7
def test_fetch_asks_for_a_week_with_sun_times_and_feels_like():
seen = {}
class Response:
def raise_for_status(self):
pass
def json(self):
return payload()
def fake_get(url, params=None, timeout=None):
seen.update(params)
return Response()
weather_data.fetch_weather(NOW, get=fake_get)
assert seen["forecast_days"] >= 7
assert set(seen["daily"].split(",")) >= {"weather_code", "temperature_2m_max", "temperature_2m_min",
"sunrise", "sunset"}
assert "apparent_temperature" in seen["current"].split(",")
+127 -37
View File
@@ -1,15 +1,18 @@
from datetime import datetime
from datetime import date, datetime, time, timedelta
import numpy as np
from PIL import ImageChops
from lcdkit import INK
from lcdkit import BG, INK
from tests.helpers import count_colour
from view import Patch
from weather_data import Hour, Weather
from weather_view import WeatherView
from weather_data import Day, Hour, Weather
from weather_view import WeatherView, is_night
NOW = datetime(2026, 10, 22, 12, 45, 8) # a Thursday
CODES = (63, 45, 61, 3, 80, 0, 71)
CELL = 65 # width of one day in the forecast strip
BAR_X, BAR_PITCH, BAR_W = 22, 37, 26
class StubPoller:
@@ -27,9 +30,19 @@ class StubPoller:
pass
def weather(temp=14.2, rain=(0, 0, 10, 20, 40, 70, 60, 50, 30, 20, 10, 0), code=2):
def day(d: date, sunrise=time(7, 20), sunset=time(17, 45)) -> Day:
"""A forecast day whose values depend only on its date."""
return Day(d, CODES[d.toordinal() % 7], float(5 + d.day % 10), float(d.day % 5),
datetime.combine(d, sunrise), datetime.combine(d, sunset))
def week(start=date(2026, 10, 22), n=7):
return tuple(day(start + timedelta(days=i)) for i in range(n))
def weather(temp=14.2, rain=(0, 0, 10, 20, 40, 70, 60, 50, 30, 20, 10, 0), code=2, days=None):
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)
return Weather(temp=temp, feels=12.1, code=code, days=week() if days is None else days, hours=hours)
def view(**kw):
@@ -45,6 +58,20 @@ def ink_bbox(img, box):
return (box[0] + xs.min(), box[1] + ys.min(), box[0] + xs.max(), box[1] + ys.max())
def icon_box(i):
cx = 12 + i * CELL + CELL // 2
return (cx - 16, 34, cx + 16, 68)
def hour_label_box(i):
x = BAR_X + i * BAR_PITCH
return (x, 290, x + BAR_W, 304)
def same(a, b):
return ImageChops.difference(a.convert("RGB"), b.convert("RGB")).getbbox() is None
def test_render_size_is_480x320():
assert view(value=weather()).render(NOW).size == (480, 320)
@@ -77,20 +104,20 @@ def test_patch_matches_full_render_region():
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
assert same(region, patch.image)
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
assert not same(a, b)
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
# day names, clock and dashes are still drawn
assert count_colour(img, INK) > 1000
@@ -99,35 +126,54 @@ def test_stale_tag_only_when_old():
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
assert bbox[0] >= 20 and bbox[1] >= 200 and bbox[2] <= 300 and bbox[3] <= 226 # on the rain header line
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_today_is_the_first_day_and_inverted():
img = view(value=weather()).render(NOW)
assert img.getpixel((12 + 5, 14)) == INK
assert img.getpixel((12 + CELL + 5, 14)) != INK
def test_negative_temp_fits_and_draws_minus():
def test_days_before_today_are_skipped():
# just after midnight the last fetch still starts with yesterday
from_yesterday = view(value=weather(days=week(start=date(2026, 10, 21)))).render(NOW)
from_today = view(value=weather(days=week(start=date(2026, 10, 22), n=6))).render(NOW)
assert same(from_yesterday, from_today)
def test_only_days_with_a_forecast_get_an_icon():
img = view(value=weather(days=week(n=3))).render(NOW)
for i in range(3):
assert ink_bbox(img, icon_box(i)) is not None, i
for i in range(3, 7):
assert ink_bbox(img, icon_box(i)) is None, i
def test_every_bar_has_its_hour_label():
img = view(value=weather()).render(NOW)
for i in range(12):
assert ink_bbox(img, hour_label_box(i)) is not None, i
def test_hour_labels_only_for_known_hours():
img = view(value=weather(rain=(10, 20))).render(NOW)
assert ink_bbox(img, hour_label_box(1)) is not None
for i in range(2, 12):
assert ink_bbox(img, hour_label_box(i)) is None, i
def test_negative_temps_stay_inside_the_frame():
for temp in (-3.4, -10.4, -19.6):
img = view(value=weather(temp=temp)).render(NOW)
box = ink_bbox(img, (380, 104, 471, 150))
assert box is not None and box[2] < 466, temp
def test_negative_temp_draws_a_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
assert not same(cold, warm)
def test_fewer_than_twelve_hours_still_renders():
@@ -139,8 +185,52 @@ def test_unknown_weather_code_renders():
assert view(value=weather(code=999)).render(NOW).size == (480, 320)
def test_two_digit_negative_temps_stay_clear_of_the_divider():
for temp in (-10.4, -19.6):
img = view(value=weather(temp=temp)).render(NOW)
box = ink_bbox(img, (84, 180, 204, 236))
assert box is not None and box[2] < 200, temp
# night: from sunset to sunrise the frame is a reverse LCD
def test_is_night_between_sunset_and_sunrise():
w = weather() # sunrise 7:20, sunset 17:45
assert is_night(datetime(2026, 10, 22, 21, 0), w)
assert is_night(datetime(2026, 10, 22, 5, 30), w)
assert not is_night(datetime(2026, 10, 22, 12, 45), w)
def test_is_night_flips_exactly_at_sunrise_and_sunset():
w = weather()
assert not is_night(datetime(2026, 10, 22, 7, 20), w)
assert is_night(datetime(2026, 10, 22, 7, 19), w)
assert not is_night(datetime(2026, 10, 22, 17, 44), w)
assert is_night(datetime(2026, 10, 22, 17, 45), w)
def test_is_night_uses_todays_sun_times():
days = (day(date(2026, 10, 21), sunset=time(16, 0)), day(date(2026, 10, 22), sunset=time(17, 45)))
assert not is_night(datetime(2026, 10, 22, 16, 30), weather(days=days))
def test_is_night_without_today_uses_the_closest_known_day():
# data a week old (fetches failing): sunrise moves only minutes a day, so old times are close enough
days = (day(date(2026, 10, 15), sunrise=time(7, 8), sunset=time(17, 58)),)
assert is_night(datetime(2026, 10, 22, 21, 0), weather(days=days))
assert not is_night(datetime(2026, 10, 22, 12, 0), weather(days=days))
def test_is_night_without_any_forecast_stays_day():
assert not is_night(datetime(2026, 10, 22, 23, 0), None)
assert not is_night(datetime(2026, 10, 22, 23, 0), weather(days=()))
def test_night_frame_is_dark():
night = view(value=weather()).render(datetime(2026, 10, 22, 21, 0, 0))
day_ = view(value=weather()).render(NOW)
assert sum(night.getpixel((2, 2))) < 100
assert day_.getpixel((2, 2)) == BG
def test_night_patch_matches_full_render_region():
v = view(value=weather())
at = datetime(2026, 10, 22, 21, 0, 8)
patch = v.patch(at)
full = v.render(at)
region = full.crop((patch.x, patch.y, patch.x + patch.image.width, patch.y + patch.image.height))
assert same(region, patch.image)
assert sum(patch.image.getpixel((0, 0))) < 100
+33 -13
View File
@@ -1,6 +1,6 @@
"""Open-Meteo forecast for Zlín: fetching and parsing (no drawing)."""
from dataclasses import dataclass
from datetime import datetime
from datetime import date, datetime
from enum import Enum
import requests
@@ -19,12 +19,22 @@ class Hour:
mm: float | None
@dataclass(frozen=True)
class Day:
date: date
code: int | None
high: float | None
low: float | None
sunrise: datetime | None # naive local time
sunset: datetime | None
@dataclass(frozen=True)
class Weather:
temp: float | None
feels: float | None
code: int | None
today_max: float | None
today_min: float | None
days: tuple[Day, ...] # as the forecast gives them, today first when fresh
hours: tuple[Hour, ...] # at most WINDOW_HOURS, starting with the hour containing "now"
@@ -61,16 +71,26 @@ def _at(values, i: int):
return values[i]
def _time(value) -> datetime | None:
return datetime.fromisoformat(value) if value else None
def parse_weather(payload: dict, now: datetime) -> Weather:
current = payload.get("current") or {}
daily = payload.get("daily") or {}
hourly = payload.get("hourly") or {}
day = now.strftime("%Y-%m-%d")
days = daily.get("time") or []
d = days.index(day) if day in days else None
today_max = _at(daily.get("temperature_2m_max"), d) if d is not None else None
today_min = _at(daily.get("temperature_2m_min"), d) if d is not None else None
days = tuple(
Day(
date=date.fromisoformat(day),
code=_at(daily.get("weather_code"), i),
high=_at(daily.get("temperature_2m_max"), i),
low=_at(daily.get("temperature_2m_min"), i),
sunrise=_time(_at(daily.get("sunrise"), i)),
sunset=_time(_at(daily.get("sunset"), i)),
)
for i, day in enumerate(daily.get("time") or [])
)
hours: list[Hour] = []
times = hourly.get("time") or []
@@ -86,9 +106,9 @@ def parse_weather(payload: dict, now: datetime) -> Weather:
return Weather(
temp=current.get("temperature_2m"),
feels=current.get("apparent_temperature"),
code=current.get("weather_code"),
today_max=today_max,
today_min=today_min,
days=days,
hours=tuple(hours),
)
@@ -97,11 +117,11 @@ def fetch_weather(now: datetime, get=requests.get) -> Weather:
params = {
"latitude": LAT,
"longitude": LON,
"current": "temperature_2m,weather_code",
"current": "temperature_2m,weather_code,apparent_temperature",
"hourly": "precipitation_probability,precipitation",
"daily": "temperature_2m_max,temperature_2m_min",
"daily": "weather_code,temperature_2m_max,temperature_2m_min,sunrise,sunset",
"timezone": TIMEZONE,
"forecast_days": 2,
"forecast_days": 7,
}
response = get(URL, params=params, timeout=10)
response.raise_for_status()
+76 -56
View File
@@ -1,18 +1,20 @@
"""Casio-style weather clock: time, date, current weather and a 12 hour rain forecast."""
from datetime import datetime
"""Casio-style weather clock: week ahead, time, date, current weather and a 12 hour rain forecast."""
from datetime import datetime, timedelta
from PIL import Image, ImageDraw
import lcdkit
from lcdkit import BG, H, INK, W
from lcdkit import BG, GHOST, H, INK, W
from poller import Poller
from view import Patch
from weather_data import Icon, Weather, icon_for
from weather_data import Day, 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
CELL = (W - 24) // 7 # one day of the forecast strip
SECONDS_BOX = (288, 104, 352, 148) # region redrawn once per second
SECONDS_GEOMETRY = dict(x=292, y=108, w=20, h=36, t=5, gap=5)
GRAPH_X, GRAPH_PITCH, GRAPH_BOTTOM, BAR_W = 22, 37, 288, 26
RAIN_LABEL = "DÉŠŤ % / HOD"
def _cloud(d: ImageDraw.ImageDraw, x: float, base: float, s: float, outline: bool = False) -> None:
@@ -31,6 +33,19 @@ def _sun(d: ImageDraw.ImageDraw, cx: float, cy: float, r: float, s: float) -> No
fill=INK, width=max(2, int(s / 16)))
def is_night(now: datetime, weather: Weather | None) -> bool:
"""True from sunset until sunrise; the frame is then drawn as a reverse LCD.
Uses today's sun times, or those of the closest day the forecast has (they move only minutes a day).
Without any forecast it stays day.
"""
days = [day for day in (weather.days if weather else ()) if day.sunrise and day.sunset]
if not days:
return False
day = min(days, key=lambda d: abs((d.date - now.date()).days))
return not day.sunrise.time() <= now.time() < day.sunset.time()
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:
@@ -82,83 +97,88 @@ class WeatherView:
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:
@staticmethod
def _seconds(now: datetime) -> Image.Image:
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)
return img
def patch(self, now: datetime) -> Patch:
img = self._seconds(now)
if is_night(now, self._poller.value):
img = lcdkit.night(img)
return Patch(img, SECONDS_BOX[0], SECONDS_BOX[1])
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)
f_small, f_tiny, f_mini = lcdkit.load_font(15), lcdkit.load_font(12), lcdkit.load_font(11)
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)
self._week_strip(d, now, weather, f_small, f_tiny)
d.line((12, 100, W - 13, 100), 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)
# time row: HH:MM, seconds and date, then the weather now
lcdkit.number(d, now.strftime("%H:%M"), 22, 108, 48, 82, 11, 8)
img.paste(self._seconds(now), SECONDS_BOX[:2])
lcdkit.number(d, now.strftime("%-d.%-m."), 292, 156, 13, 30, 4, 3, ghost=False)
d.line((376, 108, 376, 192), fill=INK, width=2)
self._current_block(d, weather, f_small, f_mini)
d.line((12, 200, W - 13, 200), 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
lcdkit.tag(d, (int(20 + d.textlength(RAIN_LABEL, font=f_tiny) + 8), 203), "STARÉ", f_tiny)
return lcdkit.night(img) if is_night(now, weather) else 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)
def _week_strip(d: ImageDraw.ImageDraw, now: datetime, weather: Weather | None, f_small, f_tiny) -> None:
"""Today and the next six days: name, icon, max and min. Today is inverted."""
by_date: dict = {day.date: day for day in (weather.days if weather else ())}
for i in range(7):
x0 = 12 + i * CELL
cx = x0 + CELL / 2
if i:
d.line((x0, 16, x0, 92), fill=GHOST, width=1)
else:
d.rectangle((x0 + 4, 12, x0 + CELL - 4, 32), fill=INK)
d.text((cx, 22), WEEKDAYS[(now.weekday() + i) % 7], font=f_small, fill=BG if i == 0 else INK,
anchor="mm")
day: Day | None = by_date.get(now.date() + timedelta(days=i))
if day is not None:
draw_icon(d, icon_for(day.code), cx - 15, 36, 30)
high = f"{lcdkit.fmt_temp(day.high if day else None)}°"
low = f" {lcdkit.fmt_temp(day.low if day else None)}°"
x = cx - (d.textlength(high, font=f_small) + d.textlength(low, font=f_tiny)) / 2
d.text((x, 90), high, font=f_small, fill=INK, anchor="ls")
d.text((x + d.textlength(high, font=f_small), 90), low, font=f_tiny, fill=INK, anchor="ls")
@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)
def _current_block(d: ImageDraw.ImageDraw, weather: Weather | None, f_small, f_mini) -> None:
temp = weather.temp if weather else None
if weather:
draw_icon(d, icon_for(weather.code), 20, 182, 56)
text = lcdkit.fmt_temp(temp)
w, gap = (26, 7) if len(text) <= 2 else (22, 5) # a third glyph (-10) must stay clear of the divider
end = lcdkit.number(d, text, 90, 184, w, 46, 6, gap, ghost=False)
w, gap = (18, 5) if len(text) <= 2 else (14, 4) # a third glyph (-10) must stay inside the frame
end = lcdkit.number(d, text, 388, 108, w, 38, 5, gap, 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)
d.ellipse((end, 108, end + 10, 118), outline=INK, width=3)
if weather:
draw_icon(d, icon_for(weather.code), 380, 152, 40)
d.text((424, 164), "POCIT", font=f_mini, fill=INK)
d.text((424, 176), f"{lcdkit.fmt_temp(weather.feels if weather else None)}°", 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)
d.text((20, 206), RAIN_LABEL, 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)
d.text((W - 18 - d.textlength(mm, font=f_small), 204), 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)
lcdkit.v_bar(d, bx, GRAPH_BOTTOM, hour.rain_pct if hour else None, BAR_W, 11, 4, 1)
if hour is not None:
d.text((bx + BAR_W / 2, 301), f"{hour.time.hour:02d}", font=f_tiny, fill=INK, anchor="ms")