File size: 15,905 Bytes
a007ec7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df277ee
a007ec7
 
d7b8cd6
a007ec7
 
 
 
 
 
 
 
 
 
 
df277ee
 
 
a007ec7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df277ee
 
 
 
a007ec7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df277ee
 
a007ec7
df277ee
 
a007ec7
df277ee
f1ba0e4
df277ee
a007ec7
f1ba0e4
 
 
 
 
 
 
 
 
 
a007ec7
f1ba0e4
 
 
a007ec7
f1ba0e4
 
a007ec7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df277ee
 
 
 
 
 
 
a007ec7
 
 
 
 
 
 
 
 
 
 
 
 
 
df277ee
a007ec7
 
df277ee
 
 
 
a007ec7
df277ee
 
a007ec7
 
df277ee
 
 
a007ec7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b6c1bd
0c3f677
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b6c1bd
df277ee
0c3f677
df277ee
6b6c1bd
 
0c3f677
6b6c1bd
2797a9e
8aadffd
d7b8cd6
 
 
 
 
 
8aadffd
 
d7b8cd6
 
 
 
 
 
 
8aadffd
d7b8cd6
 
 
 
a007ec7
 
 
 
 
 
 
 
 
 
df277ee
 
 
 
 
 
d7b8cd6
 
 
 
 
a007ec7
 
 
 
 
 
 
d7b8cd6
a007ec7
 
 
df277ee
a007ec7
 
df277ee
a007ec7
df277ee
a007ec7
 
 
 
d7b8cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
a007ec7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
"""
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"&current=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