198 lines
7.8 KiB
Python
198 lines
7.8 KiB
Python
"""Open-Meteo integration and weather suitability policy.
|
|
|
|
The rest of the planner only consumes DailyForecast instances, never Open-Meteo JSON.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from datetime import date
|
|
from decimal import Decimal
|
|
import json
|
|
from typing import Iterable
|
|
from urllib.parse import urlencode
|
|
from urllib.request import urlopen
|
|
|
|
from django.core.cache import cache
|
|
|
|
from planner.models import Task, UserSettings
|
|
|
|
OPEN_METEO_URL = 'https://api.open-meteo.com/v1/forecast'
|
|
FORECAST_SEARCH_HORIZON_DAYS = 16
|
|
FORECAST_CACHE_SECONDS = 12 * 60 * 60
|
|
MEANINGFUL_PRECIPITATION_PROBABILITY = 40
|
|
MEANINGFUL_PRECIPITATION_MM = 0.5
|
|
SUNNY_MINIMUM_SECONDS = 4 * 60 * 60
|
|
WARM_MINIMUM_TEMPERATURE_C = 15.0
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class DailyForecast:
|
|
forecast_date: date
|
|
condition: str
|
|
precipitation_probability: float | None
|
|
precipitation_mm: float | None
|
|
temperature_min_c: float | None
|
|
temperature_max_c: float | None
|
|
wind_speed_max_kmh: float | None
|
|
sunshine_seconds: float | None
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class WeatherSuitability:
|
|
status: str # suitable, unsuitable, unknown
|
|
reason: str
|
|
|
|
@property
|
|
def is_suitable(self) -> bool:
|
|
return self.status == 'suitable'
|
|
|
|
|
|
class WeatherServiceError(Exception):
|
|
"""Open-Meteo could not provide a usable forecast."""
|
|
|
|
|
|
def wmo_condition(code: int | None) -> str:
|
|
"""Map Open-Meteo WMO codes into stable application-level conditions."""
|
|
if code == 0:
|
|
return 'clear'
|
|
if code in (1, 2):
|
|
return 'partly_cloudy'
|
|
if code == 3:
|
|
return 'cloudy'
|
|
if code in (45, 48):
|
|
return 'fog'
|
|
if code in (51, 53, 55, 56, 57, 80, 81):
|
|
return 'rain'
|
|
if code in (61, 63, 66, 80):
|
|
return 'rain'
|
|
if code in (65, 67, 82):
|
|
return 'heavy_rain'
|
|
if code in (71, 73, 75, 77, 85, 86):
|
|
return 'snow'
|
|
if code in (95, 96, 99):
|
|
return 'thunderstorm'
|
|
return 'unknown'
|
|
|
|
|
|
WEATHER_ICON_NAMES = {
|
|
'clear': '☀', 'partly_cloudy': '⛅', 'cloudy': '☁', 'fog': '🌫',
|
|
'rain': '🌦', 'heavy_rain': '🌧', 'thunderstorm': '⛈', 'snow': '❄', 'unknown': '◌',
|
|
}
|
|
WEATHER_LABELS = {
|
|
'clear': 'Clear', 'partly_cloudy': 'Partly cloudy', 'cloudy': 'Cloudy', 'fog': 'Foggy',
|
|
'rain': 'Rain', 'heavy_rain': 'Heavy rain', 'thunderstorm': 'Thunderstorms',
|
|
'snow': 'Snow', 'unknown': 'Unknown conditions',
|
|
}
|
|
|
|
|
|
def _as_number(values: list, index: int) -> float | None:
|
|
try:
|
|
value = values[index]
|
|
except (IndexError, TypeError):
|
|
return None
|
|
return float(value) if value is not None else None
|
|
|
|
|
|
def normalize_open_meteo_response(payload: dict) -> list[DailyForecast]:
|
|
"""Convert Open-Meteo's daily arrays into application forecast records."""
|
|
daily = payload.get('daily') or {}
|
|
dates = daily.get('time') or []
|
|
forecasts = []
|
|
for index, value in enumerate(dates):
|
|
try:
|
|
forecast_date = date.fromisoformat(value)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
code = _as_number(daily.get('weather_code', []), index)
|
|
forecasts.append(DailyForecast(
|
|
forecast_date=forecast_date,
|
|
condition=wmo_condition(int(code) if code is not None else None),
|
|
precipitation_probability=_as_number(daily.get('precipitation_probability_max', []), index),
|
|
precipitation_mm=_as_number(daily.get('precipitation_sum', []), index),
|
|
temperature_min_c=_as_number(daily.get('temperature_2m_min', []), index),
|
|
temperature_max_c=_as_number(daily.get('temperature_2m_max', []), index),
|
|
wind_speed_max_kmh=_as_number(daily.get('wind_speed_10m_max', []), index),
|
|
sunshine_seconds=_as_number(daily.get('sunshine_duration', []), index),
|
|
))
|
|
return forecasts
|
|
|
|
|
|
def fetch_open_meteo_forecasts(latitude: Decimal | float, longitude: Decimal | float) -> list[DailyForecast]:
|
|
"""Fetch one normalized finite daily forecast from Open-Meteo."""
|
|
params = urlencode({
|
|
'latitude': str(latitude), 'longitude': str(longitude),
|
|
'daily': 'weather_code,precipitation_probability_max,precipitation_sum,temperature_2m_min,temperature_2m_max,wind_speed_10m_max,sunshine_duration',
|
|
'forecast_days': FORECAST_SEARCH_HORIZON_DAYS, 'timezone': 'auto',
|
|
})
|
|
try:
|
|
with urlopen(f'{OPEN_METEO_URL}?{params}', timeout=5) as response: # nosec B310 - fixed HTTPS endpoint
|
|
payload = json.loads(response.read().decode('utf-8'))
|
|
except (OSError, ValueError, json.JSONDecodeError) as error:
|
|
raise WeatherServiceError('Weather forecast is unavailable.') from error
|
|
return normalize_open_meteo_response(payload)
|
|
|
|
|
|
def _forecast_cache_key(user_id: int, latitude: Decimal, longitude: Decimal) -> str:
|
|
return f'planner:weather:{user_id}:{latitude}:{longitude}'
|
|
|
|
|
|
def forecasts_for_user(user) -> list[DailyForecast] | None:
|
|
"""Return cached normalized forecasts, or None when location/API is unavailable."""
|
|
settings = UserSettings.objects.filter(user=user).first()
|
|
if settings is None or settings.latitude is None or settings.longitude is None:
|
|
return None
|
|
key = _forecast_cache_key(user.pk, settings.latitude, settings.longitude)
|
|
cached = cache.get(key)
|
|
if cached is not None:
|
|
return cached
|
|
try:
|
|
forecasts = fetch_open_meteo_forecasts(settings.latitude, settings.longitude)
|
|
except WeatherServiceError:
|
|
return None
|
|
cache.set(key, forecasts, FORECAST_CACHE_SECONDS)
|
|
return forecasts
|
|
|
|
|
|
def forecast_for_user_on_date(user, selected_date: date) -> DailyForecast | None:
|
|
forecasts = forecasts_for_user(user)
|
|
if forecasts is None:
|
|
return None
|
|
return next((forecast for forecast in forecasts if forecast.forecast_date == selected_date), None)
|
|
|
|
|
|
def evaluate_weather_suitability(task: Task, forecast: DailyForecast | None) -> WeatherSuitability:
|
|
"""Evaluate a task profile with centralized, explainable weather thresholds."""
|
|
profile = task.weather_profile
|
|
if profile == Task.WeatherProfile.ANY:
|
|
return WeatherSuitability('suitable', 'Any weather is suitable.')
|
|
if forecast is None:
|
|
return WeatherSuitability('unknown', 'Weather forecast unavailable.')
|
|
|
|
rainy = (
|
|
(forecast.precipitation_probability is not None and forecast.precipitation_probability >= MEANINGFUL_PRECIPITATION_PROBABILITY)
|
|
or (forecast.precipitation_mm is not None and forecast.precipitation_mm >= MEANINGFUL_PRECIPITATION_MM)
|
|
)
|
|
dry = not rainy
|
|
sunny = dry and forecast.condition in {'clear', 'partly_cloudy'} and (
|
|
forecast.sunshine_seconds is not None and forecast.sunshine_seconds >= SUNNY_MINIMUM_SECONDS
|
|
)
|
|
warm = forecast.temperature_max_c is not None and forecast.temperature_max_c >= WARM_MINIMUM_TEMPERATURE_C
|
|
|
|
if profile == Task.WeatherProfile.DRY:
|
|
return WeatherSuitability('suitable', f'Dry forecast.') if dry else WeatherSuitability('unsuitable', 'Rain expected.')
|
|
if profile == Task.WeatherProfile.SUNNY:
|
|
return WeatherSuitability('suitable', 'Sunny and dry forecast.') if sunny else WeatherSuitability('unsuitable', 'Not sunny and dry enough.')
|
|
if profile == Task.WeatherProfile.WARM:
|
|
return WeatherSuitability('suitable', f'Warm, up to {forecast.temperature_max_c:g} °C.') if warm else WeatherSuitability('unsuitable', f'Below {WARM_MINIMUM_TEMPERATURE_C:g} °C.')
|
|
if profile == Task.WeatherProfile.DRY_AND_WARM:
|
|
if not dry:
|
|
return WeatherSuitability('unsuitable', 'Rain expected.')
|
|
if not warm:
|
|
return WeatherSuitability('unsuitable', f'Below {WARM_MINIMUM_TEMPERATURE_C:g} °C.')
|
|
return WeatherSuitability('suitable', f'Dry and warm, up to {forecast.temperature_max_c:g} °C.')
|
|
return WeatherSuitability('unknown', 'Unknown weather preference.')
|
|
|
|
|
|
def weather_profile_label(task: Task) -> str:
|
|
return task.get_weather_profile_display()
|