Files
second-screen/weather_view.py
T
rickzkmandClaude Opus 5.5 6c9a1420d2 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]>
2026-10-28 22:40:34 +01:00

185 lines
8.6 KiB
Python

"""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, GHOST, H, INK, W
from poller import Poller
from view import Patch
from weather_data import Day, Icon, Weather, icon_for
WEEKDAYS = ["PO", "ÚT", "ST", "ČT", "PÁ", "SO", "NE"]
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:
"""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 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:
_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())
@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 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, 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._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, 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._rain_graph(d, weather, f_small, f_tiny)
if self._is_stale():
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 _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_mini) -> None:
temp = weather.temp if weather else None
text = lcdkit.fmt_temp(temp)
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, 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((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), 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, 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")