Fix: Wetter-Alarm standortbezogen statt 5-Städte-Maximum — Abonnenten nach Standort clustern, lokale Tagesprognose, nur lokal warnen
This commit is contained in:
parent
cad34711b7
commit
8c2bc0c445
2 changed files with 82 additions and 87 deletions
|
|
@ -12,7 +12,7 @@ from apscheduler.triggers.cron import CronTrigger
|
||||||
_TZ = ZoneInfo("Europe/Berlin")
|
_TZ = ZoneInfo("Europe/Berlin")
|
||||||
|
|
||||||
from database import db
|
from database import db
|
||||||
from routes.push import send_push_to_user, send_push_to_all
|
from routes.push import send_push_to_user, send_push_to_all, send_push
|
||||||
import weather
|
import weather
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
@ -708,45 +708,70 @@ async def _job_poison_archive():
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
async def _job_weather_alert():
|
async def _job_weather_alert():
|
||||||
"""
|
"""
|
||||||
Holt Tagesprognose für mehrere deutsche Städte.
|
STANDORTBEZOGENER Wetter-Alarm.
|
||||||
Sendet Push-Notification wenn:
|
Gruppiert alle Push-Abonnenten nach ihrem letzten bekannten Standort
|
||||||
- Temperatur >= 28°C (Asphalt-Warnung für Pfoten)
|
(gerundet auf 0.1° ≈ 11 km) und holt pro Cluster die lokale Tagesprognose.
|
||||||
- Gewitter wahrscheinlich
|
Sendet nur an die Abonnenten DES JEWEILIGEN Clusters, wenn dort:
|
||||||
Hitze hat Vorrang: Bei Hitze wird kein Gewitter-Push mehr gesendet.
|
- Temperatur >= 28°C (Asphalt-Warnung für Pfoten), oder
|
||||||
|
- Gewitter wahrscheinlich (Hitze hat Vorrang).
|
||||||
|
Abonnenten ohne gespeicherten Standort erhalten keine Wetter-Warnung
|
||||||
|
(besser keine als eine für eine fremde Region).
|
||||||
"""
|
"""
|
||||||
logger.info("Wetter-Alert Job läuft")
|
from collections import defaultdict
|
||||||
try:
|
logger.info("Wetter-Alert Job läuft (standortbezogen)")
|
||||||
summary = await weather.get_weather_summary()
|
|
||||||
except Exception as e:
|
with db() as conn:
|
||||||
logger.error(f"Wetter-Alert: Fehler beim Abruf: {e}")
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM push_subscriptions "
|
||||||
|
"WHERE last_lat IS NOT NULL AND last_lon IS NOT NULL"
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
if not rows:
|
||||||
|
logger.info("Wetter-Alert: keine Abonnenten mit Standort.")
|
||||||
|
_log_job("weather_alert", "ok", "Keine Standorte")
|
||||||
return
|
return
|
||||||
|
|
||||||
max_temp = summary["max_temp_c"]
|
# Nach gerundetem Standort clustern → ein Wetter-Abruf pro Cluster
|
||||||
thunderstorm = summary["thunderstorm"]
|
clusters = defaultdict(list)
|
||||||
|
for row in rows:
|
||||||
|
key = (round(row["last_lat"], 1), round(row["last_lon"], 1))
|
||||||
|
clusters[key].append(row)
|
||||||
|
|
||||||
if max_temp >= 28:
|
heat_clusters = thunder_clusters = total_sent = 0
|
||||||
_log_job("weather_alert", "ok", f"Hitze-Push: {max_temp:.0f}°C")
|
for (lat, lon), subs in clusters.items():
|
||||||
sent = send_push_to_all({
|
try:
|
||||||
|
alert = await weather.get_day_alert(lat, lon)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Wetter-Alert: Abruf für {lat},{lon} fehlgeschlagen: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
max_temp = alert["max_temp_c"]
|
||||||
|
payload = None
|
||||||
|
if max_temp is not None and max_temp >= 28:
|
||||||
|
payload = {
|
||||||
"type": "weather_heat",
|
"type": "weather_heat",
|
||||||
"title": "☀️ Heißer Asphalt heute",
|
"title": "☀️ Heißer Asphalt heute",
|
||||||
"body": f"Bis {max_temp:.0f}°C heute — Asphalt kann über 50°C heiß werden. Frühmorgens oder abends gassi gehen!",
|
"body": f"Bis {max_temp:.0f}°C heute — Asphalt kann über 50°C heiß werden. Frühmorgens oder abends gassi gehen!",
|
||||||
"data": {"tag": "weather-heat"},
|
"data": {"tag": "weather-heat"},
|
||||||
})
|
}
|
||||||
logger.info(f"Wetter-Alert Hitze: {max_temp:.1f}°C — {sent} Push gesendet.")
|
heat_clusters += 1
|
||||||
return # Kein Gewitter-Push mehr nötig wenn Hitze bereits gemeldet
|
elif alert["thunderstorm"]:
|
||||||
|
payload = {
|
||||||
if thunderstorm:
|
|
||||||
sent = send_push_to_all({
|
|
||||||
"type": "weather_thunder",
|
"type": "weather_thunder",
|
||||||
"title": "⛈️ Gewitter möglich",
|
"title": "⛈️ Gewitter möglich",
|
||||||
"body": "Heute Gewitter wahrscheinlich. Gassi-Tour früh einplanen und Hund beruhigen.",
|
"body": "Heute Gewitter wahrscheinlich. Gassi-Tour früh einplanen und Hund beruhigen.",
|
||||||
"data": {"tag": "weather-thunder"},
|
"data": {"tag": "weather-thunder"},
|
||||||
})
|
}
|
||||||
logger.info(f"Wetter-Alert Gewitter — {sent} Push gesendet.")
|
thunder_clusters += 1
|
||||||
return
|
|
||||||
|
|
||||||
logger.info("Wetter-Alert: Keine Warnung nötig heute.")
|
if payload:
|
||||||
_log_job("weather_alert", "ok", "Keine Warnung")
|
for row in subs:
|
||||||
|
if send_push(row, payload):
|
||||||
|
total_sent += 1
|
||||||
|
|
||||||
|
msg = f"{heat_clusters} Hitze- / {thunder_clusters} Gewitter-Cluster, {total_sent} Push"
|
||||||
|
logger.info(f"Wetter-Alert: {msg}")
|
||||||
|
_log_job("weather_alert", "ok", msg)
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
"""
|
"""
|
||||||
BAN YARO — Wetter via Open-Meteo
|
BAN YARO — Wetter via Open-Meteo
|
||||||
- get_weather_summary(): Push-Job, prüft 5 deutsche Städte
|
- get_day_alert(): standortbezogener Wetter-Alarm-Push (Hitze/Gewitter)
|
||||||
- get_weather_for_location(): API-Endpoint, beliebiger Standort mit TTL-Cache
|
- get_weather_for_location(): API-Endpoint, beliebiger Standort mit TTL-Cache
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
@ -158,67 +158,37 @@ async def get_weather_for_location(lat: float, lon: float) -> dict:
|
||||||
_location_cache[key] = (now, data)
|
_location_cache[key] = (now, data)
|
||||||
return data
|
return data
|
||||||
|
|
||||||
# Wichtige deutsche Städte als Stichprobe
|
|
||||||
CITIES = [
|
|
||||||
{"name": "Berlin", "lat": 52.52, "lon": 13.41},
|
|
||||||
{"name": "München", "lat": 48.14, "lon": 11.58},
|
|
||||||
{"name": "Hamburg", "lat": 53.55, "lon": 10.00},
|
|
||||||
{"name": "Frankfurt", "lat": 50.11, "lon": 8.68},
|
|
||||||
{"name": "Köln", "lat": 50.94, "lon": 6.96},
|
|
||||||
]
|
|
||||||
|
|
||||||
# WMO-Wettercodes 95–99 = Gewitter
|
# WMO-Wettercodes 95–99 = Gewitter
|
||||||
THUNDERSTORM_CODES = {95, 96, 99}
|
THUNDERSTORM_CODES = {95, 96, 99}
|
||||||
|
|
||||||
|
|
||||||
async def get_weather_summary() -> dict:
|
async def get_day_alert(lat: float, lon: float) -> dict:
|
||||||
"""
|
"""
|
||||||
Holt Tagesprognose für mehrere deutsche Städte von Open-Meteo.
|
Tagesprognose (heute) für EINEN Standort — Grundlage für den
|
||||||
Gibt zurück: {"max_temp_c": float, "thunderstorm": bool}
|
standortbezogenen Wetter-Alarm-Push (Hitze / Gewitter).
|
||||||
|
Gibt zurück: {"max_temp_c": float|None, "thunderstorm": bool}
|
||||||
"""
|
"""
|
||||||
max_temp = -999.0
|
|
||||||
thunderstorm = False
|
|
||||||
|
|
||||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
|
||||||
for city in CITIES:
|
|
||||||
url = (
|
url = (
|
||||||
"https://api.open-meteo.com/v1/forecast"
|
"https://api.open-meteo.com/v1/forecast"
|
||||||
f"?latitude={city['lat']}&longitude={city['lon']}"
|
f"?latitude={lat}&longitude={lon}"
|
||||||
"&daily=temperature_2m_max,precipitation_probability_max,weathercode"
|
"&daily=temperature_2m_max,precipitation_probability_max,weathercode"
|
||||||
"&timezone=Europe%2FBerlin&forecast_days=1"
|
"&timezone=Europe%2FBerlin&forecast_days=1"
|
||||||
)
|
)
|
||||||
try:
|
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||||
resp = await client.get(url)
|
resp = await client.get(url)
|
||||||
resp.raise_for_status()
|
resp.raise_for_status()
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
|
|
||||||
daily = data.get("daily", {})
|
daily = data.get("daily", {})
|
||||||
temps = daily.get("temperature_2m_max", [None])
|
temp = (daily.get("temperature_2m_max") or [None])[0]
|
||||||
precip_probs = daily.get("precipitation_probability_max", [None])
|
precip_prob = (daily.get("precipitation_probability_max") or [None])[0]
|
||||||
weathercodes = daily.get("weathercode", [None])
|
weathercode = (daily.get("weathercode") or [None])[0]
|
||||||
|
|
||||||
temp = temps[0] if temps else None
|
thunderstorm = (
|
||||||
precip_prob = precip_probs[0] if precip_probs else None
|
|
||||||
weathercode = weathercodes[0] if weathercodes else None
|
|
||||||
|
|
||||||
if temp is not None and temp > max_temp:
|
|
||||||
max_temp = temp
|
|
||||||
|
|
||||||
if (
|
|
||||||
precip_prob is not None and precip_prob > 50
|
precip_prob is not None and precip_prob > 50
|
||||||
and weathercode is not None and int(weathercode) in THUNDERSTORM_CODES
|
and weathercode is not None and int(weathercode) in THUNDERSTORM_CODES
|
||||||
):
|
)
|
||||||
thunderstorm = True
|
return {"max_temp_c": temp, "thunderstorm": thunderstorm}
|
||||||
logger.info(f"Gewitter erkannt: {city['name']} (Code {weathercode}, {precip_prob}% Niederschlag)")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Wetter-Abruf für {city['name']} fehlgeschlagen: {e}")
|
|
||||||
|
|
||||||
if max_temp == -999.0:
|
|
||||||
max_temp = 0.0
|
|
||||||
|
|
||||||
logger.info(f"Wetter-Zusammenfassung: max_temp={max_temp}°C, thunderstorm={thunderstorm}")
|
|
||||||
return {"max_temp_c": max_temp, "thunderstorm": thunderstorm}
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue