Files
bonaminandClaude Opus 5.5 84c2d5b2d8 feat(signage): the weather all the way: a week, the next hours, feels like, humidity, wind, rain chance, sunrise / sunset, UV, in words; row, column, card, list of days or hourly layouts
services/weather.py asks Open-Meteo for 7 days, the next 24 hours and the details
(mph for Fahrenheit); older answers without them still read. The widget's layout,
the details it adds and the place's name; up to 7 days. Plan 6R.18, F-116.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:07:03 +02:00

172 lines
8.2 KiB
Python

"""The weather for signage screens (plan step 5.4c, owner 2026-11-17: "weather only works with
internet; if the internet is down, just hide the widget").
The venue's place is a setting (`signage.weather.place`, `.latitude`, `.longitude`, picked in the
editor from a town search). `weather_worker` (a signage module worker) asks Open-Meteo (free, no
key) every 30 minutes while it has internet and keeps the last answer in memory. A forecast older
than 3 hours counts as none: the screens get `weather: null` and hide the widget.
current() → {"place", "temperature", "code", "is_day", "feels_like", "humidity", "wind", "wind_dir",
"precipitation", "days": [{date, max, min, code, rain, wind, uv, sunrise, sunset}] (7),
"hours": [{time, temp, code, rain, is_day}] (the next 24), "units", "wind_unit", "at"} | None
(6R.18: everything the detailed weather widget can show; older answers lack some keys)
search(name) → places for the editor's search (name, country, region, latitude, longitude)
"""
from __future__ import annotations
import asyncio
import logging
import time
import httpx
logger = logging.getLogger("xenia.weather")
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"
SEARCH_URL = "https://geocoding-api.open-meteo.com/v1/search"
EVERY_S = 30 * 60
STALE_S = 3 * 3600
TIMEOUT_S = 10
_last: dict = {"data": None, "at": 0.0, "key": None, "error": None, "tried": 0.0}
def _setting(db, key: str, default: str = "") -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row and row.value not in (None, "") else default
def place(db) -> dict | None:
"""The venue's place for the weather, or None when it isn't set."""
try:
lat, lon = float(_setting(db, "signage.weather.latitude")), float(_setting(db, "signage.weather.longitude"))
except ValueError:
return None
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
return None
units = _setting(db, "signage.weather.units", "celsius")
return {"name": _setting(db, "signage.weather.place") or f"{lat:.2f}, {lon:.2f}", "latitude": lat, "longitude": lon,
"units": units if units in ("celsius", "fahrenheit") else "celsius"}
def current(db, now: float | None = None) -> dict | None:
"""The last forecast for the venue's place while it is fresh; None hides the widget."""
where = place(db)
if where is None or _last["data"] is None or _last["key"] != _key(where):
return None
if (now or time.time()) - _last["at"] > STALE_S:
return None
return _last["data"]
def status(db) -> dict:
where = place(db)
return {"place": where, "weather": current(db), "fetched_at": _last["at"] or None,
"error": _last["error"] if where else None}
def _key(where: dict) -> tuple:
return (round(where["latitude"], 3), round(where["longitude"], 3), where["units"])
async def fetch(where: dict, client: httpx.AsyncClient | None = None) -> dict:
imperial = where["units"] == "fahrenheit"
params = {"latitude": where["latitude"], "longitude": where["longitude"], "timezone": "auto", "forecast_days": 7,
"current": "temperature_2m,weather_code,is_day,apparent_temperature,relative_humidity_2m,wind_speed_10m,wind_direction_10m,precipitation",
"daily": "temperature_2m_max,temperature_2m_min,weather_code,precipitation_probability_max,wind_speed_10m_max,uv_index_max,sunrise,sunset",
"hourly": "temperature_2m,weather_code,precipitation_probability,is_day",
"temperature_unit": where["units"], "wind_speed_unit": "mph" if imperial else "kmh"}
own = client is None
client = client or httpx.AsyncClient(timeout=TIMEOUT_S)
try:
r = await client.get(FORECAST_URL, params=params)
r.raise_for_status()
j = r.json()
finally:
if own:
await client.aclose()
cur, daily, hourly = j.get("current") or {}, j.get("daily") or {}, j.get("hourly") or {}
col = lambda src, key, n: (src.get(key) or [None] * n)[:n] + [None] * max(0, n - len(src.get(key) or [])) # noqa: E731
n = len(daily.get("time", []))
hm = lambda v: v[11:16] if isinstance(v, str) and len(v) >= 16 else None # noqa: E731 "2026-11-17T07:12" → "07:12"
days = [{"date": d, "max": mx, "min": mn, "code": c, "rain": rp, "wind": wm, "uv": uv, "sunrise": hm(sr), "sunset": hm(ss)}
for d, mx, mn, c, rp, wm, uv, sr, ss in zip(daily.get("time", []), col(daily, "temperature_2m_max", n), col(daily, "temperature_2m_min", n),
col(daily, "weather_code", n), col(daily, "precipitation_probability_max", n),
col(daily, "wind_speed_10m_max", n), col(daily, "uv_index_max", n),
col(daily, "sunrise", n), col(daily, "sunset", n))]
# the next 24 hours from now (the place's own time: Open-Meteo answers in it)
times = hourly.get("time", [])
start = next((i for i, x in enumerate(times) if x >= (cur.get("time") or "")[:13] + ":00"), 0)
m = len(times)
hours = [{"time": hm(t), "temp": tp, "code": c, "rain": rp, "is_day": bool(dy if dy is not None else 1)}
for t, tp, c, rp, dy in list(zip(times, col(hourly, "temperature_2m", m), col(hourly, "weather_code", m),
col(hourly, "precipitation_probability", m), col(hourly, "is_day", m)))[start:start + 24]]
return {"place": where["name"], "temperature": cur.get("temperature_2m"), "code": cur.get("weather_code"),
"is_day": bool(cur.get("is_day", 1)), "feels_like": cur.get("apparent_temperature"), "humidity": cur.get("relative_humidity_2m"),
"wind": cur.get("wind_speed_10m"), "wind_dir": cur.get("wind_direction_10m"), "precipitation": cur.get("precipitation"),
"days": days, "hours": hours, "units": where["units"], "wind_unit": "mph" if imperial else "km/h", "at": cur.get("time")}
async def refresh(db, client: httpx.AsyncClient | None = None) -> bool:
"""Fetch now for the venue's place. True when a forecast came; the screens are told either way
when it changes whether they can show one."""
where = place(db)
before = current(db) is not None
_last["tried"] = time.time()
if where is None:
_last.update(data=None, key=None, error=None)
ok = False
else:
try:
data = await fetch(where, client)
_last.update(data=data, at=time.time(), key=_key(where), error=None)
ok = True
except Exception as e: # no internet, DNS, the service down: the widget hides
_last["error"] = type(e).__name__
logger.info("weather: no forecast (%s)", _last["error"])
ok = False
if ok or before != (current(db) is not None):
_tell_screens(db)
return ok
def _tell_screens(db) -> None:
try:
from routers.signage import tell_all_screens
tell_all_screens(db)
except Exception as e:
logger.warning("weather: screens not told: %s", e)
async def search(name: str, language: str = "en", client: httpx.AsyncClient | None = None) -> list[dict]:
own = client is None
client = client or httpx.AsyncClient(timeout=TIMEOUT_S)
try:
r = await client.get(SEARCH_URL, params={"name": name, "count": 8, "language": language, "format": "json"})
r.raise_for_status()
results = r.json().get("results") or []
finally:
if own:
await client.aclose()
return [{"name": x.get("name"), "country": x.get("country"), "region": x.get("admin1"),
"latitude": x.get("latitude"), "longitude": x.get("longitude")} for x in results]
async def weather_worker():
"""Every 30 minutes (a signage module worker; stops when signage is turned off)."""
from database import SessionLocal
while True:
db = SessionLocal()
try:
await refresh(db)
except Exception as e:
logger.warning("weather worker: %s", e)
finally:
db.close()
await asyncio.sleep(EVERY_S)
def reset() -> None:
_last.update(data=None, at=0.0, key=None, error=None, tried=0.0)