Files
xenia-pos-local/local_backend/services/weather.py
T
bonaminandClaude Opus 5.5 b5951ba373 feat(backend): signage widgets, the message of the day, the weather (platform-v2 step 5.4c)
- Widget on text and menu slides: logo (a picture), name, date (short/long),
  clock (seconds), message (the venue's or its own text), QR code (ordering /
  QR menu / a link; the screen gets the link), weather (1-3 days); position
  (corners, top / bottom bar) and size. Logos count as media usage.
- The screen gets `venue`: name, message of the day, weather.
- PUT /api/signage/message (one place, every screen told at once).
- services/weather.py: the venue's place (town search through
  /api/signage/weather/places, PUT/DELETE /weather/place, °C/°F), Open-Meteo
  every 30 min (signage worker), kept in memory; no place, no internet or older
  than 3 h → weather null and the widget hides. signage.weather_offline when
  the town search can't reach the service. Checked against the real service.
- tests: test_signage_widgets.py (5, a fake Open-Meteo); 520 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:42:52 +02:00

152 lines
6.0 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", "days": [{date, max, min, code}], "units", "at"} | None
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:
params = {"latitude": where["latitude"], "longitude": where["longitude"], "timezone": "auto", "forecast_days": 3,
"current": "temperature_2m,weather_code,is_day", "daily": "temperature_2m_max,temperature_2m_min,weather_code",
"temperature_unit": where["units"]}
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 = j.get("current") or {}, j.get("daily") or {}
days = [{"date": d, "max": mx, "min": mn, "code": c}
for d, mx, mn, c in zip(daily.get("time", []), daily.get("temperature_2m_max", []),
daily.get("temperature_2m_min", []), daily.get("weather_code", []))]
return {"place": where["name"], "temperature": cur.get("temperature_2m"), "code": cur.get("weather_code"),
"is_day": bool(cur.get("is_day", 1)), "days": days, "units": where["units"], "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)