""" api.py — Comunicazione con i server Renault e gestione dei comandi veicolo. """ import asyncio from datetime import datetime, timedelta from typing import Any, Awaitable import aiohttp import streamlit as st from renault_api.renault_client import RenaultClient from config import ( LOCALE, CHARGE_MODE_ALWAYS_CANDIDATES, CHARGE_MODE_SCHEDULE_CANDIDATES, API_TIMEOUT_SECONDS, REFRESH_RATE_LIMIT_SECONDS, Azione, ) from utils import add_debug_event, get_current_credentials, run_async, safe_get, is_refreshing, set_refreshing # ─── Login e selezione veicolo ──────────────────────────────────────────────── async def _login_and_get_vehicle( websession: aiohttp.ClientSession, email: str, password: str, ) -> Any: """ Fa login su MyRenault e ritorna il veicolo selezionato. Supporta multi-veicolo: memorizza la lista in session_state e rispetta il VIN selezionato dall'utente nella sidebar. FIX #20 — la sessione HTTP viene riusata se il token è ancora valido. """ client = RenaultClient(websession=websession, locale=LOCALE) await client.session.login(email, password) if "renault_account_id" in st.session_state: account_id = st.session_state["renault_account_id"] else: person = await client.get_person() account_id = person.accounts[0].accountId st.session_state["renault_account_id"] = account_id account = await client.get_api_account(account_id) if not st.session_state.get("vehicle_list"): vehicles = await account.get_vehicles() vehicle_list: list[dict[str, str]] = [] for vl in vehicles.vehicleLinks: brand = getattr(vl, "brand", "") or "" model = getattr(vl, "model", "") or "" vin = getattr(vl, "vin", "") or "" label = f"{brand} {model} ({vin[-6:]})" if vin else vin vehicle_list.append({"vin": vin, "label": label.strip()}) st.session_state["vehicle_list"] = vehicle_list if not st.session_state.get("renault_vin_selected"): st.session_state["renault_vin_selected"] = vehicle_list[0]["vin"] if vehicle_list else None vin = st.session_state.get("renault_vin_selected") or st.session_state.get("renault_vin") if not vin: raise RuntimeError("Nessun VIN disponibile. Riprova ad accedere.") vehicle = await account.get_api_vehicle(vin) return vehicle # ─── Chiamata sicura (cattura eccezioni per endpoint opzionali) ─────────────── async def _safe_call(name: str, coro: Awaitable[Any]) -> tuple[str, dict[str, Any]]: try: result = await coro return name, {"ok": True, "data": result} except Exception as exc: return name, {"ok": False, "error": str(exc)} # ─── Fetch meteo completo con previsioni 7 giorni (cached 10 min) ──────────── # FIX #1/#2/#7 — unica funzione meteo, unificata, cached, con forecast 7 giorni @st.cache_data(ttl=600, show_spinner=False) def fetch_meteo_full_cached(lat: float, lon: float) -> dict | None: """ Scarica dati meteo correnti + previsioni 7 giorni da Open-Meteo. Usa requests (sync) per evitare conflitti con l'event loop async di aiohttp. TTL 10 minuti per evitare chiamate a ogni re-render. """ import requests as _requests url = ( f"https://api.open-meteo.com/v1/forecast" f"?latitude={lat}&longitude={lon}" f"¤t=temperature_2m,relative_humidity_2m,apparent_temperature," f"weather_code,wind_speed_10m,wind_direction_10m,precipitation" f"&daily=temperature_2m_max,temperature_2m_min,weather_code," f"precipitation_sum,wind_speed_10m_max" f"&wind_speed_unit=kmh&timezone=auto&forecast_days=7" ) try: resp = _requests.get(url, timeout=API_TIMEOUT_SECONDS) if resp.status_code == 200: return resp.json() except Exception: pass return None # ─── Download tutti i dati dal veicolo ─────────────────────────────────────── async def scarica_tutti_i_dati( email: str, password: str, lookback_days: int, ) -> dict[str, Any]: timeout = aiohttp.ClientTimeout(total=API_TIMEOUT_SECONDS) async with aiohttp.ClientSession(timeout=timeout) as websession: vehicle = await _login_and_get_vehicle(websession, email, password) end = datetime.now() start = end - timedelta(days=lookback_days) tasks = [ _safe_call("details", vehicle.get_details()), _safe_call("battery", vehicle.get_battery_status()), _safe_call("charges", vehicle.get_charges(start, end)), _safe_call("cockpit", vehicle.get_cockpit()), _safe_call("hvac", vehicle.get_hvac_status()), _safe_call("location", vehicle.get_location()), _safe_call("charging_settings", vehicle.get_charging_settings()), ] results = await asyncio.gather(*tasks) data: dict[str, Any] = {} errors: dict[str, str] = {} for name, payload in results: if payload["ok"]: data[name] = payload["data"] else: data[name] = None errors[name] = payload["error"] # Meteo: unica chiamata unificata (FIX #1/#2) lat = safe_get(data.get("location"), "gpsLatitude") lon = safe_get(data.get("location"), "gpsLongitude") if lat and lon: data["meteo_full"] = fetch_meteo_full_cached(float(lat), float(lon)) else: data["meteo_full"] = None # Temperatura display: prima sensore auto, poi Open-Meteo ext_temp_car = safe_get(data.get("hvac"), "externalTemperature") if ext_temp_car is not None: data["temp_display"] = {"valore": ext_temp_car, "fonte": "🚗 Sensore Veicolo"} elif data.get("meteo_full"): t_meteo = data["meteo_full"].get("current", {}).get("temperature_2m") data["temp_display"] = {"valore": t_meteo, "fonte": "☁️ Open-Meteo (cache 10 min)"} else: data["temp_display"] = {"valore": None, "fonte": "N/D (Nessuna fonte)"} return { "vin": vehicle.vin, "fetched_at": datetime.now(), "data": data, "errors": errors, } # ─── Imposta modalità di ricarica (fallback su candidati multipli) ──────────── async def _set_charge_mode_robust(vehicle: Any, requested_mode: str) -> Any: candidates = ( CHARGE_MODE_ALWAYS_CANDIDATES if requested_mode == "always" else CHARGE_MODE_SCHEDULE_CANDIDATES ) last_error: Exception | None = None for candidate in candidates: try: return await vehicle.set_charge_mode(candidate) except Exception as exc: last_error = exc if last_error is not None: raise last_error raise RuntimeError("Modalità di ricarica non disponibile") # ─── Invia comando al veicolo ───────────────────────────────────────────────── async def invia_comando( email: str, password: str, azione: Azione, parametro: Any = None, ) -> tuple[bool, Any]: timeout = aiohttp.ClientTimeout(total=API_TIMEOUT_SECONDS) async with aiohttp.ClientSession(timeout=timeout) as websession: vehicle = await _login_and_get_vehicle(websession, email, password) try: if azione == Azione.AVVIA_RICARICA: result = await vehicle.set_charge_start() elif azione == Azione.FERMA_RICARICA: result = await vehicle.set_charge_stop() elif azione == Azione.MODALITA_SEMPRE: result = await _set_charge_mode_robust(vehicle, "always") elif azione == Azione.MODALITA_PROGRAMMATA: result = await _set_charge_mode_robust(vehicle, "schedule") elif azione == Azione.IMPOSTA_SOC: result = await vehicle.set_battery_soc( min=int(parametro["min"]), target=int(parametro["target"]) ) elif azione == Azione.AVVIA_CLIMA: result = await vehicle.set_ac_start(temperature=float(parametro)) elif azione == Azione.FERMA_CLIMA: result = await vehicle.set_ac_stop() elif azione == Azione.IMPOSTA_SCHEDULE_RICARICA: from renault_api.kamereon.models import ChargeSchedule, ChargeDaySchedule giorni_map = { "Lun": "monday", "Mar": "tuesday", "Mer": "wednesday", "Gio": "thursday", "Ven": "friday", "Sab": "saturday", "Dom": "sunday", } schedules_obj = [] for s in parametro: giorni_attivi = s.get("giorni", list(giorni_map.keys())) day_schedule = ChargeDaySchedule( raw_data={}, startTime=s["startTime"], duration=int(s["duration"]), ) kwargs = { "raw_data": {}, "id": int(s["id"]), "activated": bool(s.get("activated", True)), } for abbr, eng in giorni_map.items(): kwargs[eng] = day_schedule if abbr in giorni_attivi else None schedules_obj.append(ChargeSchedule(**kwargs)) result = await vehicle.set_charge_schedules(schedules_obj) elif azione == Azione.IMPOSTA_SCHEDULE_HVAC: from datetime import datetime as _dt, timezone dt_str = parametro["startDateTime"] dt_obj = _dt.strptime(dt_str, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) result = await vehicle.set_ac_start( temperature=float(parametro["temperature"]), when=dt_obj, ) elif azione == Azione.IMPOSTA_PARTENZA_RITARDATA: # Usa set_charge_start(when=) — supportato dalla ZOE anche senza charge-schedule # FIX timezone: l'ora inserita dall'utente è in ora locale (Europe/Rome), # ma il server Renault vuole UTC. Convertiamo correttamente. from datetime import datetime as _dt, timezone from zoneinfo import ZoneInfo # parametro["startTime"] = "HH:MM" (ora calcolata dall'app in ORA LOCALE) ora_str = parametro.get("startTime", "07:00") ora_str = ora_str.lstrip("T").rstrip("Z") h, m = int(ora_str.split(":")[0]), int(ora_str.split(":")[1]) # Ora locale corrente (Europe/Rome) tz_local = ZoneInfo("Europe/Rome") now_local = _dt.now(tz=tz_local) # Costruisci target in ora locale target_local = now_local.replace(hour=h, minute=m, second=0, microsecond=0) # Se l'ora è già passata oggi, programma per domani (locale) if target_local <= now_local: from datetime import timedelta as _td target_local = target_local + _td(days=1) # Converti in UTC per l'API Renault target_utc = target_local.astimezone(timezone.utc) result = await vehicle.set_charge_start(when=target_utc) else: raise ValueError(f"Azione sconosciuta: {azione}") return True, result except Exception as exc: return False, str(exc) # ─── Funzioni Streamlit per aggiornamento dati e comandi ───────────────────── def aggiorna_dati(show_toast: bool = True) -> None: # FIX #18 — rate limiting: evita spam di login su Renault last = st.session_state.get("ultimo_refresh") if last and (datetime.now() - last).total_seconds() < REFRESH_RATE_LIMIT_SECONDS: st.toast(f"⏳ Aspetta almeno {REFRESH_RATE_LIMIT_SECONDS}s tra un refresh e l'altro.", icon="⏳") return # FIX race condition: evita refresh sovrapposti if is_refreshing(): st.toast("🔄 Aggiornamento già in corso...", icon="⏳") return email, password = get_current_credentials() if not email or not password: st.session_state["ultimo_errore"] = "Inserisci email e password My Renault." add_debug_event("Aggiornamento fallito: credenziali mancanti.", "warning") return add_debug_event("Avvio aggiornamento dati dal backend Renault.", "info") set_refreshing(True) with st.spinner("Comunicazione con i server Renault in corso..."): try: lookback_days = int(st.session_state.get("lookback_days", 180)) st.session_state["dati_auto"] = run_async( scarica_tutti_i_dati(email, password, lookback_days) ) st.session_state["autenticato"] = True st.session_state["ultimo_refresh"] = datetime.now() st.session_state["ultimo_errore"] = None add_debug_event("Aggiornamento dati completato con successo.", "success") if show_toast: st.toast("Dati aggiornati correttamente.", icon="✅") except Exception as exc: # Rileva token scaduto da pattern exc_str = str(exc).lower() if any(k in exc_str for k in ("token", "auth", "login", "401", "403", "unauthorized", "invalid")): st.session_state["autenticato"] = False st.session_state["ultimo_errore"] = ( "🔐 Sessione scaduta o credenziali non valide. " "Reinserisci email e password nella barra laterale e premi Accedi." ) add_debug_event("Token scaduto o credenziali non valide, richiesto nuovo login.", "warning") else: st.session_state["ultimo_errore"] = f"Errore di comunicazione: {exc}" add_debug_event(f"Errore backend: {exc}", "error") finally: set_refreshing(False) def esegui_azione( azione: Azione, parametro: Any = None, success_message: str = "Comando inviato.", ) -> None: email, password = get_current_credentials() if not email or not password: st.error("Credenziali mancanti.") add_debug_event(f"Azione {azione} non eseguita: credenziali mancanti.", "warning") return add_debug_event(f"Invio comando: {azione}", "info") with st.spinner("Invio comando in corso..."): ok, msg = run_async(invia_comando(email, password, azione, parametro)) if ok: add_debug_event(f"Comando {azione} eseguito correttamente.", "success") st.success(success_message) st.toast("✅ Premi 🔄 Refresh per vedere lo stato aggiornato.") else: add_debug_event(f"Comando {azione} fallito: {msg}", "error") st.error(f"Comando rifiutato o non supportato: {msg}") def esegui_logout() -> None: add_debug_event("Logout richiesto dall'utente.", "info") for key in ( "autenticato", "dati_auto", "ultimo_refresh", "ultimo_errore", "_hidden_password", "password_input", "renault_account_id", "renault_vin_selected", "vehicle_list", ): st.session_state.pop(key, None) st.session_state["autenticato"] = False