Files
retroLabs/bridge/weather.py

131 lines
5.4 KiB
Python

import asyncio
import logging
import os
from datetime import UTC, datetime
from time import monotonic
from zoneinfo import ZoneInfo
from astral import Observer
from astral.sun import sun
import httpx
LOG = logging.getLogger(__name__)
class NWSWeather:
def __init__(self):
self.point = os.getenv("RETROTV_WEATHER_POINT", "").strip()
self.location = os.getenv("RETROTV_WEATHER_LOCATION", "Local Weather")
self.cache = {}
self.retry_at = {}
self.lock = asyncio.Lock()
async def _cached(self, client, key, url, ttl, transform):
now = monotonic()
if now >= self.retry_at.get(key, 0):
try:
response = await client.get(url)
response.raise_for_status()
self.cache[key] = (transform(response.json()), now + ttl)
self.retry_at[key] = now + ttl
except (httpx.HTTPError, ValueError, KeyError, IndexError, TypeError) as exc:
LOG.warning("NWS %s unavailable: %s", key, exc)
self.retry_at[key] = now + 60
return self.cache.get(key, (None, 0))
async def read(self):
if not self.point:
return {"status": "unconfigured", "location": self.location}
async with self.lock, httpx.AsyncClient(
base_url="https://api.weather.gov", timeout=3,
headers={"User-Agent": "retroLabs/0.1", "Accept": "application/geo+json"},
) as client:
grid, _ = await self._cached(
client, "grid", f"/points/{self.point}", 86400,
lambda body: body["properties"],
)
if not grid:
return {"status": "unavailable", "location": self.location}
async def current():
stations, _ = await self._cached(
client, "stations", grid["observationStations"], 86400,
lambda body: [station["properties"]["stationIdentifier"]
for station in body["features"][:5]],
)
candidates = await asyncio.gather(*(
self._cached(client, f"observation:{station}",
f"/stations/{station}/observations/latest", 300, observation)
for station in stations or []
))
recent = [(value, deadline) for value, deadline in candidates if value]
return next(((value, deadline) for value, deadline in recent
if deadline > monotonic()), recent[0] if recent else (None, 0))
parts = await asyncio.gather(
current(),
self._cached(client, "hourly", grid["forecastHourly"], 600,
lambda body: periods(body, 18)),
self._cached(client, "forecast", grid["forecast"], 600,
lambda body: periods(body, 14)),
self._cached(client, "alerts", f"/alerts/active?point={self.point}", 120,
lambda body: [alert["properties"] for alert in body["features"]]),
)
clock = datetime.now(UTC)
now = clock.isoformat()
local_zone = ZoneInfo(grid["timeZone"])
latitude, longitude = map(float, self.point.split(","))
daylight = sun(Observer(latitude, longitude),
date=clock.astimezone(local_zone).date(), tzinfo=local_zone)
observation_data, hourly, forecast, alerts = (value for value, _ in parts)
return {
"status": "ok", "location": self.location, "source": "National Weather Service",
"current": observation_data,
"almanac": {key: local_time(daylight[key]) for key in ("sunrise", "sunset")},
"hourly": future_periods(hourly, now)[:6],
"forecast": future_periods(forecast, now)[:7],
"alerts": [
{"event": alert["event"], "headline": alert.get("headline")}
for alert in alerts or [] if after(alert.get("ends") or alert.get("expires"), now)
],
"alertsAvailable": parts[3][1] > monotonic(),
"stale": any(deadline <= monotonic() for _, deadline in parts[:3]),
}
def local_time(value):
return value.strftime("%I:%M %p").lstrip("0")
def observation(body):
data = body["properties"]
celsius = data["temperature"]["value"]
if celsius is None:
raise ValueError("Observation has no temperature")
humidity = data.get("relativeHumidity", {}).get("value")
wind = data.get("windSpeed", {}).get("value")
return {
"temperature": round(celsius * 9 / 5 + 32), "conditions": data["textDescription"],
"humidity": None if humidity is None else round(humidity),
"windMph": None if wind is None else round(wind * 0.621371),
"observedAt": data["timestamp"],
}
def periods(body, limit):
return [
{"name": item["name"] or local_time(datetime.fromisoformat(item["startTime"])), "start": item["startTime"], "end": item["endTime"],
"temperature": item["temperature"], "conditions": item["shortForecast"],
"daytime": item["isDaytime"]}
for item in body["properties"]["periods"][:limit]
]
def after(value, now):
return value is not None and datetime.fromisoformat(value) > datetime.fromisoformat(now)
def future_periods(items, now):
return [item for item in items or [] if after(item["end"], now)]