Spaces:
Sleeping
Sleeping
Upload 6 files
Browse files
api.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
api.py β Comunicazione con i server Renault e gestione dei comandi veicolo.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
from typing import Any, Awaitable
|
| 8 |
+
|
| 9 |
+
import aiohttp
|
| 10 |
+
import streamlit as st
|
| 11 |
+
from renault_api.renault_client import RenaultClient
|
| 12 |
+
|
| 13 |
+
from config import (
|
| 14 |
+
LOCALE,
|
| 15 |
+
CHARGE_MODE_ALWAYS_CANDIDATES,
|
| 16 |
+
CHARGE_MODE_SCHEDULE_CANDIDATES,
|
| 17 |
+
API_TIMEOUT_SECONDS,
|
| 18 |
+
Azione,
|
| 19 |
+
)
|
| 20 |
+
from utils import add_debug_event, get_current_credentials, run_async, safe_get
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# βββ Login e selezione veicolo ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 24 |
+
|
| 25 |
+
async def _login_and_get_vehicle(
|
| 26 |
+
websession: aiohttp.ClientSession,
|
| 27 |
+
email: str,
|
| 28 |
+
password: str,
|
| 29 |
+
) -> Any:
|
| 30 |
+
"""
|
| 31 |
+
Fa login su MyRenault e ritorna il veicolo selezionato.
|
| 32 |
+
β
FIX: supporta multi-veicolo: memorizza la lista in session_state
|
| 33 |
+
e rispetta il VIN selezionato dall'utente nella sidebar.
|
| 34 |
+
"""
|
| 35 |
+
client = RenaultClient(websession=websession, locale=LOCALE)
|
| 36 |
+
await client.session.login(email, password)
|
| 37 |
+
|
| 38 |
+
# Recupera account_id dalla cache se disponibile
|
| 39 |
+
if "renault_account_id" in st.session_state:
|
| 40 |
+
account_id = st.session_state["renault_account_id"]
|
| 41 |
+
else:
|
| 42 |
+
person = await client.get_person()
|
| 43 |
+
account_id = person.accounts[0].accountId
|
| 44 |
+
st.session_state["renault_account_id"] = account_id
|
| 45 |
+
|
| 46 |
+
account = await client.get_api_account(account_id)
|
| 47 |
+
|
| 48 |
+
# Recupera lista veicoli (con cache)
|
| 49 |
+
if not st.session_state.get("vehicle_list"):
|
| 50 |
+
vehicles = await account.get_vehicles()
|
| 51 |
+
vehicle_list: list[dict[str, str]] = []
|
| 52 |
+
for vl in vehicles.vehicleLinks:
|
| 53 |
+
brand = getattr(vl, "brand", "") or ""
|
| 54 |
+
model = getattr(vl, "model", "") or ""
|
| 55 |
+
vin = getattr(vl, "vin", "") or ""
|
| 56 |
+
label = f"{brand} {model} ({vin[-6:]})" if vin else vin
|
| 57 |
+
vehicle_list.append({"vin": vin, "label": label.strip()})
|
| 58 |
+
st.session_state["vehicle_list"] = vehicle_list
|
| 59 |
+
# Se non ancora selezionato, usa il primo
|
| 60 |
+
if not st.session_state.get("renault_vin_selected"):
|
| 61 |
+
st.session_state["renault_vin_selected"] = vehicle_list[0]["vin"] if vehicle_list else None
|
| 62 |
+
|
| 63 |
+
vin = st.session_state.get("renault_vin_selected") or st.session_state.get("renault_vin")
|
| 64 |
+
if not vin:
|
| 65 |
+
raise RuntimeError("Nessun VIN disponibile. Riprova ad accedere.")
|
| 66 |
+
|
| 67 |
+
vehicle = await account.get_api_vehicle(vin)
|
| 68 |
+
return vehicle
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# βββ Chiamata sicura (cattura eccezioni per endpoint opzionali) βββββββββββββββ
|
| 72 |
+
|
| 73 |
+
async def _safe_call(name: str, coro: Awaitable[Any]) -> tuple[str, dict[str, Any]]:
|
| 74 |
+
try:
|
| 75 |
+
result = await coro
|
| 76 |
+
return name, {"ok": True, "data": result}
|
| 77 |
+
except Exception as exc:
|
| 78 |
+
return name, {"ok": False, "error": str(exc)}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# βββ Temperatura esterna via Open-Meteo (con cache Streamlit 5 min) ββββββββββ
|
| 82 |
+
|
| 83 |
+
@st.cache_data(ttl=300, show_spinner=False)
|
| 84 |
+
def fetch_weather_cached(lat: float, lon: float) -> float | None:
|
| 85 |
+
"""
|
| 86 |
+
β
FIX: aggiunto cache Streamlit (ttl=5 min) per evitare chiamate
|
| 87 |
+
a ogni re-render della pagina.
|
| 88 |
+
"""
|
| 89 |
+
async def _fetch() -> float | None:
|
| 90 |
+
timeout = aiohttp.ClientTimeout(total=API_TIMEOUT_SECONDS)
|
| 91 |
+
async with aiohttp.ClientSession(timeout=timeout) as session:
|
| 92 |
+
url = (
|
| 93 |
+
f"https://api.open-meteo.com/v1/forecast"
|
| 94 |
+
f"?latitude={lat}&longitude={lon}¤t_weather=true"
|
| 95 |
+
)
|
| 96 |
+
async with session.get(url) as response:
|
| 97 |
+
if response.status == 200:
|
| 98 |
+
data = await response.json()
|
| 99 |
+
return data.get("current_weather", {}).get("temperature")
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
try:
|
| 103 |
+
return run_async(_fetch())
|
| 104 |
+
except Exception:
|
| 105 |
+
return None
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# βββ Download tutti i dati dal veicolo βββββββββββββββββββββββββββββββββββββββ
|
| 109 |
+
|
| 110 |
+
async def scarica_tutti_i_dati(
|
| 111 |
+
email: str,
|
| 112 |
+
password: str,
|
| 113 |
+
lookback_days: int,
|
| 114 |
+
) -> dict[str, Any]:
|
| 115 |
+
timeout = aiohttp.ClientTimeout(total=API_TIMEOUT_SECONDS)
|
| 116 |
+
async with aiohttp.ClientSession(timeout=timeout) as websession:
|
| 117 |
+
vehicle = await _login_and_get_vehicle(websession, email, password)
|
| 118 |
+
|
| 119 |
+
end = datetime.now()
|
| 120 |
+
start = end - timedelta(days=lookback_days)
|
| 121 |
+
|
| 122 |
+
tasks = [
|
| 123 |
+
_safe_call("details", vehicle.get_details()),
|
| 124 |
+
_safe_call("battery", vehicle.get_battery_status()),
|
| 125 |
+
_safe_call("charges", vehicle.get_charges(start, end)),
|
| 126 |
+
_safe_call("cockpit", vehicle.get_cockpit()),
|
| 127 |
+
_safe_call("hvac", vehicle.get_hvac_status()),
|
| 128 |
+
_safe_call("location", vehicle.get_location()),
|
| 129 |
+
_safe_call("charging_settings",vehicle.get_charging_settings()),
|
| 130 |
+
]
|
| 131 |
+
|
| 132 |
+
results = await asyncio.gather(*tasks)
|
| 133 |
+
|
| 134 |
+
data: dict[str, Any] = {}
|
| 135 |
+
errors: dict[str, str] = {}
|
| 136 |
+
|
| 137 |
+
for name, payload in results:
|
| 138 |
+
if payload["ok"]:
|
| 139 |
+
data[name] = payload["data"]
|
| 140 |
+
else:
|
| 141 |
+
data[name] = None
|
| 142 |
+
errors[name] = payload["error"]
|
| 143 |
+
|
| 144 |
+
# Temperatura: prima dal sensore auto, poi da Open-Meteo (cached)
|
| 145 |
+
ext_temp_car = safe_get(data.get("hvac"), "externalTemperature")
|
| 146 |
+
lat = safe_get(data.get("location"), "gpsLatitude")
|
| 147 |
+
lon = safe_get(data.get("location"), "gpsLongitude")
|
| 148 |
+
|
| 149 |
+
if ext_temp_car is not None:
|
| 150 |
+
data["temp_display"] = {"valore": ext_temp_car, "fonte": "π Sensore Veicolo"}
|
| 151 |
+
elif lat and lon:
|
| 152 |
+
weather_val = fetch_weather_cached(float(lat), float(lon))
|
| 153 |
+
data["temp_display"] = {"valore": weather_val, "fonte": "βοΈ Open-Meteo (cache 5 min)"}
|
| 154 |
+
else:
|
| 155 |
+
data["temp_display"] = {"valore": None, "fonte": "N/D (Nessuna fonte)"}
|
| 156 |
+
|
| 157 |
+
return {
|
| 158 |
+
"vin": vehicle.vin,
|
| 159 |
+
"fetched_at": datetime.now(),
|
| 160 |
+
"data": data,
|
| 161 |
+
"errors": errors,
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# βββ Imposta modalitΓ di ricarica (fallback su candidati multipli) ββββββββββββ
|
| 166 |
+
|
| 167 |
+
async def _set_charge_mode_robust(vehicle: Any, requested_mode: str) -> Any:
|
| 168 |
+
candidates = (
|
| 169 |
+
CHARGE_MODE_ALWAYS_CANDIDATES
|
| 170 |
+
if requested_mode == "always"
|
| 171 |
+
else CHARGE_MODE_SCHEDULE_CANDIDATES
|
| 172 |
+
)
|
| 173 |
+
last_error: Exception | None = None
|
| 174 |
+
for candidate in candidates:
|
| 175 |
+
try:
|
| 176 |
+
return await vehicle.set_charge_mode(candidate)
|
| 177 |
+
except Exception as exc:
|
| 178 |
+
last_error = exc
|
| 179 |
+
if last_error is not None:
|
| 180 |
+
raise last_error
|
| 181 |
+
raise RuntimeError("ModalitΓ di ricarica non disponibile")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# βββ Invia comando al veicolo βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 185 |
+
|
| 186 |
+
async def invia_comando(
|
| 187 |
+
email: str,
|
| 188 |
+
password: str,
|
| 189 |
+
azione: Azione,
|
| 190 |
+
parametro: Any = None,
|
| 191 |
+
) -> tuple[bool, Any]:
|
| 192 |
+
timeout = aiohttp.ClientTimeout(total=API_TIMEOUT_SECONDS)
|
| 193 |
+
async with aiohttp.ClientSession(timeout=timeout) as websession:
|
| 194 |
+
vehicle = await _login_and_get_vehicle(websession, email, password)
|
| 195 |
+
try:
|
| 196 |
+
if azione == Azione.AVVIA_RICARICA:
|
| 197 |
+
result = await vehicle.set_charge_start()
|
| 198 |
+
elif azione == Azione.FERMA_RICARICA:
|
| 199 |
+
result = await vehicle.set_charge_stop()
|
| 200 |
+
elif azione == Azione.MODALITA_SEMPRE:
|
| 201 |
+
result = await _set_charge_mode_robust(vehicle, "always")
|
| 202 |
+
elif azione == Azione.MODALITA_PROGRAMMATA:
|
| 203 |
+
result = await _set_charge_mode_robust(vehicle, "schedule")
|
| 204 |
+
elif azione == Azione.IMPOSTA_SOC:
|
| 205 |
+
result = await vehicle.set_battery_soc(
|
| 206 |
+
min=int(parametro["min"]), target=int(parametro["target"])
|
| 207 |
+
)
|
| 208 |
+
elif azione == Azione.AVVIA_CLIMA:
|
| 209 |
+
result = await vehicle.set_ac_start(temperature=float(parametro))
|
| 210 |
+
elif azione == Azione.FERMA_CLIMA:
|
| 211 |
+
result = await vehicle.set_ac_stop()
|
| 212 |
+
else:
|
| 213 |
+
raise ValueError(f"Azione sconosciuta: {azione}")
|
| 214 |
+
return True, result
|
| 215 |
+
except Exception as exc:
|
| 216 |
+
return False, str(exc)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# βββ Funzioni Streamlit per aggiornamento dati e comandi βββββββββββββββββββββ
|
| 220 |
+
|
| 221 |
+
def aggiorna_dati(show_toast: bool = True) -> None:
|
| 222 |
+
email, password = get_current_credentials()
|
| 223 |
+
if not email or not password:
|
| 224 |
+
st.session_state["ultimo_errore"] = "Inserisci email e password My Renault."
|
| 225 |
+
add_debug_event("Aggiornamento fallito: credenziali mancanti.", "warning")
|
| 226 |
+
return
|
| 227 |
+
|
| 228 |
+
add_debug_event("Avvio aggiornamento dati dal backend Renault.", "info")
|
| 229 |
+
with st.spinner("Comunicazione con i server Renault in corso..."):
|
| 230 |
+
try:
|
| 231 |
+
lookback_days = int(st.session_state.get("lookback_days", 180))
|
| 232 |
+
st.session_state["dati_auto"] = run_async(
|
| 233 |
+
scarica_tutti_i_dati(email, password, lookback_days)
|
| 234 |
+
)
|
| 235 |
+
st.session_state["autenticato"] = True
|
| 236 |
+
st.session_state["ultimo_refresh"] = datetime.now()
|
| 237 |
+
st.session_state["ultimo_errore"] = None
|
| 238 |
+
add_debug_event("Aggiornamento dati completato con successo.", "success")
|
| 239 |
+
if show_toast:
|
| 240 |
+
st.toast("Dati aggiornati correttamente.", icon="β
")
|
| 241 |
+
except Exception as exc:
|
| 242 |
+
st.session_state["ultimo_errore"] = f"Errore di comunicazione: {exc}"
|
| 243 |
+
st.session_state["autenticato"] = False
|
| 244 |
+
add_debug_event(f"Errore backend: {exc}", "error")
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def esegui_azione(
|
| 248 |
+
azione: Azione,
|
| 249 |
+
parametro: Any = None,
|
| 250 |
+
success_message: str = "Comando inviato.",
|
| 251 |
+
) -> None:
|
| 252 |
+
"""
|
| 253 |
+
β
FIX: non chiama piΓΉ aggiorna_dati() automaticamente dopo il comando
|
| 254 |
+
(evitava un doppio login inutile). Mostra invece un toast
|
| 255 |
+
e suggerisce il refresh manuale.
|
| 256 |
+
"""
|
| 257 |
+
email, password = get_current_credentials()
|
| 258 |
+
if not email or not password:
|
| 259 |
+
st.error("Credenziali mancanti.")
|
| 260 |
+
add_debug_event(f"Azione {azione} non eseguita: credenziali mancanti.", "warning")
|
| 261 |
+
return
|
| 262 |
+
|
| 263 |
+
add_debug_event(f"Invio comando: {azione}", "info")
|
| 264 |
+
with st.spinner("Invio comando in corso..."):
|
| 265 |
+
ok, msg = run_async(invia_comando(email, password, azione, parametro))
|
| 266 |
+
if ok:
|
| 267 |
+
add_debug_event(f"Comando {azione} eseguito correttamente.", "success")
|
| 268 |
+
st.success(success_message)
|
| 269 |
+
st.toast("β
Premi π Refresh per vedere lo stato aggiornato.")
|
| 270 |
+
else:
|
| 271 |
+
add_debug_event(f"Comando {azione} fallito: {msg}", "error")
|
| 272 |
+
st.error(f"Comando rifiutato o non supportato: {msg}")
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def esegui_logout() -> None:
|
| 276 |
+
add_debug_event("Logout richiesto dall'utente.", "info")
|
| 277 |
+
for key in (
|
| 278 |
+
"autenticato", "dati_auto", "ultimo_refresh", "ultimo_errore",
|
| 279 |
+
"_hidden_password", "password_input",
|
| 280 |
+
"renault_account_id", "renault_vin_selected", "vehicle_list",
|
| 281 |
+
):
|
| 282 |
+
st.session_state.pop(key, None)
|
| 283 |
+
st.session_state["autenticato"] = False
|
app.py
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
charts.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
charts.py β Costruzione di tutti i DataFrame usati nelle tab.
|
| 3 |
+
Nessuna chiamata Streamlit diretta.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
from config import RELIABLE_VCD_CODES
|
| 11 |
+
from utils import safe_get, prettify_generic_status
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# βββ Sessioni di ricarica βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 15 |
+
|
| 16 |
+
def get_charge_sessions_list(charges_obj: Any) -> list[Any]:
|
| 17 |
+
if charges_obj is None:
|
| 18 |
+
return []
|
| 19 |
+
if hasattr(charges_obj, "raw_data") and isinstance(charges_obj.raw_data, dict):
|
| 20 |
+
charges = charges_obj.raw_data.get("charges")
|
| 21 |
+
if isinstance(charges, list):
|
| 22 |
+
return charges
|
| 23 |
+
charges = safe_get(charges_obj, "charges", default=[])
|
| 24 |
+
return charges if isinstance(charges, list) else []
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def build_charge_sessions_df(charges_obj: Any) -> pd.DataFrame:
|
| 28 |
+
rows: list[dict[str, Any]] = []
|
| 29 |
+
|
| 30 |
+
for item in get_charge_sessions_list(charges_obj):
|
| 31 |
+
start = safe_get(item, "chargeStartDate", default=None)
|
| 32 |
+
end = safe_get(item, "chargeEndDate", default=None)
|
| 33 |
+
duration = safe_get(item, "chargeDuration", default=None)
|
| 34 |
+
energy = safe_get(item, "chargeEnergyRecovered", "chargeEnergy", default=None)
|
| 35 |
+
|
| 36 |
+
e_val = pd.to_numeric(energy, errors="coerce")
|
| 37 |
+
d_val = pd.to_numeric(duration, errors="coerce")
|
| 38 |
+
|
| 39 |
+
# β
FIX: era `if (d_val and d_val > 0)` β NaN Γ¨ truthy, causava NaN silenzioso
|
| 40 |
+
avg_power = (
|
| 41 |
+
(e_val / (d_val / 60.0))
|
| 42 |
+
if (pd.notna(d_val) and d_val > 0)
|
| 43 |
+
else 0.0
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
start_soc = safe_get(item, "chargeStartBatteryLevel", default=None)
|
| 47 |
+
end_soc = safe_get(item, "chargeEndBatteryLevel", default=None)
|
| 48 |
+
status = safe_get(item, "chargeEndStatus", default=None)
|
| 49 |
+
|
| 50 |
+
start_dt = pd.to_datetime(start, utc=True, errors="coerce")
|
| 51 |
+
end_dt = pd.to_datetime(end, utc=True, errors="coerce")
|
| 52 |
+
|
| 53 |
+
rows.append({
|
| 54 |
+
"Data e Ora": start_dt.tz_convert("Europe/Rome").tz_localize(None) if pd.notna(start_dt) else pd.NaT,
|
| 55 |
+
"Fine": end_dt.tz_convert("Europe/Rome").tz_localize(None) if pd.notna(end_dt) else pd.NaT,
|
| 56 |
+
"Durata (min)": pd.to_numeric(duration, errors="coerce"),
|
| 57 |
+
"Energia (kWh)": pd.to_numeric(energy, errors="coerce"),
|
| 58 |
+
"Potenza media (kW)": round(avg_power, 1),
|
| 59 |
+
"Batteria iniziale (%)": pd.to_numeric(start_soc, errors="coerce"),
|
| 60 |
+
"Batteria finale (%)": pd.to_numeric(end_soc, errors="coerce"),
|
| 61 |
+
"Stato": status,
|
| 62 |
+
})
|
| 63 |
+
|
| 64 |
+
if not rows:
|
| 65 |
+
return pd.DataFrame()
|
| 66 |
+
|
| 67 |
+
df = pd.DataFrame(rows).sort_values("Data e Ora", ascending=False)
|
| 68 |
+
return df.reset_index(drop=True)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def filter_sessions_df(df: pd.DataFrame, days: int) -> pd.DataFrame:
|
| 72 |
+
if df.empty or "Data e Ora" not in df.columns:
|
| 73 |
+
return df
|
| 74 |
+
# β
FIX: rimosso .normalize() β escludeva ricariche iniziate "oggi"
|
| 75 |
+
cutoff = pd.Timestamp.now() - pd.Timedelta(days=days)
|
| 76 |
+
return df[df["Data e Ora"] >= cutoff].reset_index(drop=True)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def build_charge_daily_df(df_sessions: pd.DataFrame) -> pd.DataFrame:
|
| 80 |
+
if df_sessions.empty or "Data e Ora" not in df_sessions:
|
| 81 |
+
return pd.DataFrame()
|
| 82 |
+
chart_df = df_sessions.dropna(subset=["Data e Ora"]).copy()
|
| 83 |
+
if chart_df.empty:
|
| 84 |
+
return pd.DataFrame()
|
| 85 |
+
chart_df["Giorno"] = chart_df["Data e Ora"].dt.date
|
| 86 |
+
return (
|
| 87 |
+
chart_df.groupby("Giorno", as_index=False)
|
| 88 |
+
.agg({"Energia (kWh)": "sum", "Durata (min)": "sum", "Stato": "count"})
|
| 89 |
+
.rename(columns={"Stato": "Sessioni"})
|
| 90 |
+
.sort_values("Giorno")
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def build_monthly_summary_df(df_sessions: pd.DataFrame) -> pd.DataFrame:
|
| 95 |
+
if df_sessions.empty:
|
| 96 |
+
return pd.DataFrame()
|
| 97 |
+
tmp = df_sessions.dropna(subset=["Data e Ora"]).copy()
|
| 98 |
+
if tmp.empty:
|
| 99 |
+
return pd.DataFrame()
|
| 100 |
+
tmp["Mese"] = tmp["Data e Ora"].dt.to_period("M").astype(str)
|
| 101 |
+
return (
|
| 102 |
+
tmp.groupby("Mese", as_index=False)
|
| 103 |
+
.agg({"Energia (kWh)": "sum", "Durata (min)": "sum", "Stato": "count"})
|
| 104 |
+
.rename(columns={"Stato": "Sessioni"})
|
| 105 |
+
.sort_values("Mese")
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def build_charge_type_df(df_sessions: pd.DataFrame) -> pd.DataFrame:
|
| 110 |
+
"""
|
| 111 |
+
β
NUOVO: distribuzione AC vs DC basata sulla potenza media.
|
| 112 |
+
Usato per il grafico a torta nella tab Cronologia.
|
| 113 |
+
"""
|
| 114 |
+
if df_sessions.empty or "Potenza media (kW)" not in df_sessions.columns:
|
| 115 |
+
return pd.DataFrame()
|
| 116 |
+
df = df_sessions.dropna(subset=["Potenza media (kW)"]).copy()
|
| 117 |
+
df["Tipo"] = df["Potenza media (kW)"].apply(
|
| 118 |
+
lambda p: "DC Rapida (>22 kW)" if p > 22 else "AC Lenta (β€22 kW)"
|
| 119 |
+
)
|
| 120 |
+
return (
|
| 121 |
+
df.groupby("Tipo", as_index=False)
|
| 122 |
+
.agg({"Energia (kWh)": "sum", "Potenza media (kW)": "count"})
|
| 123 |
+
.rename(columns={"Potenza media (kW)": "Sessioni"})
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# βββ Pneumatici βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 128 |
+
|
| 129 |
+
def build_tyre_df(tyre_obj: Any) -> pd.DataFrame:
|
| 130 |
+
if tyre_obj is None:
|
| 131 |
+
return pd.DataFrame()
|
| 132 |
+
rows = [
|
| 133 |
+
{"Ruota": "Anteriore sinistra", "Pressione": safe_get(tyre_obj, "flPressure"), "Stato": safe_get(tyre_obj, "flStatus")},
|
| 134 |
+
{"Ruota": "Anteriore destra", "Pressione": safe_get(tyre_obj, "frPressure"), "Stato": safe_get(tyre_obj, "frStatus")},
|
| 135 |
+
{"Ruota": "Posteriore sinistra","Pressione": safe_get(tyre_obj, "rlPressure"), "Stato": safe_get(tyre_obj, "rlStatus")},
|
| 136 |
+
{"Ruota": "Posteriore destra", "Pressione": safe_get(tyre_obj, "rrPressure"), "Stato": safe_get(tyre_obj, "rrStatus")},
|
| 137 |
+
]
|
| 138 |
+
df = pd.DataFrame(rows)
|
| 139 |
+
if df["Pressione"].isna().all() and df["Stato"].isna().all():
|
| 140 |
+
return pd.DataFrame()
|
| 141 |
+
return df
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# βββ Stato porte / serrature βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 145 |
+
|
| 146 |
+
def build_lock_summary_df(lock_status: Any) -> pd.DataFrame:
|
| 147 |
+
if lock_status is None:
|
| 148 |
+
return pd.DataFrame()
|
| 149 |
+
rows = [
|
| 150 |
+
{"Voce": "Serrature", "Valore": prettify_generic_status(safe_get(lock_status, "lockStatus", default="N/D"))},
|
| 151 |
+
{"Voce": "Porta guidatore", "Valore": prettify_generic_status(safe_get(lock_status, "doorStatusDriver", default="N/D"))},
|
| 152 |
+
{"Voce": "Porta passeggero", "Valore": prettify_generic_status(safe_get(lock_status, "doorStatusPassenger", default="N/D"))},
|
| 153 |
+
{"Voce": "Posteriore sinistra", "Valore": prettify_generic_status(safe_get(lock_status, "doorStatusRearLeft", default="N/D"))},
|
| 154 |
+
{"Voce": "Posteriore destra", "Valore": prettify_generic_status(safe_get(lock_status, "doorStatusRearRight", default="N/D"))},
|
| 155 |
+
{"Voce": "Portellone", "Valore": prettify_generic_status(safe_get(lock_status, "hatchStatus", default="N/D"))},
|
| 156 |
+
]
|
| 157 |
+
return pd.DataFrame(rows)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# βββ VCD Decoder ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 161 |
+
|
| 162 |
+
def decode_vcd_reliable(code: str) -> dict[str, str] | None:
|
| 163 |
+
c = str(code).strip().upper()
|
| 164 |
+
|
| 165 |
+
if c in RELIABLE_VCD_CODES:
|
| 166 |
+
info = RELIABLE_VCD_CODES[c]
|
| 167 |
+
return {
|
| 168 |
+
"Codice": c,
|
| 169 |
+
"Categoria": info["Categoria"],
|
| 170 |
+
"Significato": info["Significato"],
|
| 171 |
+
"AttendibilitΓ ": info["AttendibilitΓ "],
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
# Pattern generici
|
| 175 |
+
if c.startswith("OV") and len(c) >= 4:
|
| 176 |
+
return {"Codice": c, "Categoria": "Colore", "Significato": f"Vernice pastello ({c})", "AttendibilitΓ ": "Media"}
|
| 177 |
+
if c.startswith("TE") and len(c) >= 4:
|
| 178 |
+
return {"Codice": c, "Categoria": "Colore", "Significato": f"Vernice metallizzata ({c})", "AttendibilitΓ ": "Media"}
|
| 179 |
+
if c.startswith("RALU"):
|
| 180 |
+
return {"Codice": c, "Categoria": "Ruote", "Significato": f"Cerchi in lega ({c.replace('RALU', '')}\")", "AttendibilitΓ ": "Media"}
|
| 181 |
+
if c.startswith("PHAS"):
|
| 182 |
+
return {"Codice": c, "Categoria": "Modello", "Significato": f"Fase evolutiva ({c.replace('PHAS', '')})", "AttendibilitΓ ": "Media"}
|
| 183 |
+
if c.endswith("KWH"):
|
| 184 |
+
return {"Codice": c, "Categoria": "Batteria", "Significato": f"CapacitΓ pacco batteria: {c}", "AttendibilitΓ ": "Media"}
|
| 185 |
+
if c.startswith("AEBS"):
|
| 186 |
+
return {"Codice": c, "Categoria": "ADAS", "Significato": f"Frenata automatica (Gen. {c.replace('AEBS', '')})", "AttendibilitΓ ": "Media"}
|
| 187 |
+
if c.startswith("AIRB"):
|
| 188 |
+
return {"Codice": c, "Categoria": "Airbag", "Significato": "Sistema Airbag", "AttendibilitΓ ": "Media"}
|
| 189 |
+
if c.endswith("CAM"):
|
| 190 |
+
return {"Codice": c, "Categoria": "Telecamera","Significato": "Sensore/Telecamera", "AttendibilitΓ ": "Media"}
|
| 191 |
+
if c.startswith("BT") and any(ch.isdigit() for ch in c):
|
| 192 |
+
return {"Codice": c, "Categoria": "Batteria", "Significato": f"Specifica batteria ({c})", "AttendibilitΓ ": "Media"}
|
| 193 |
+
|
| 194 |
+
return None
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def build_reliable_vcd_df(vcd_string: str) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 198 |
+
vcd_list = [c.strip() for c in str(vcd_string).split("/") if c.strip()]
|
| 199 |
+
|
| 200 |
+
reliable_rows: list[dict[str, str]] = []
|
| 201 |
+
discarded_rows: list[dict[str, str]] = []
|
| 202 |
+
|
| 203 |
+
for code in vcd_list:
|
| 204 |
+
decoded = decode_vcd_reliable(code)
|
| 205 |
+
if decoded is None:
|
| 206 |
+
discarded_rows.append({"Codice": code.upper(), "Motivo": "Codice non abbastanza affidabile"})
|
| 207 |
+
else:
|
| 208 |
+
reliable_rows.append(decoded)
|
| 209 |
+
|
| 210 |
+
reliable_df = pd.DataFrame(reliable_rows)
|
| 211 |
+
discarded_df = pd.DataFrame(discarded_rows)
|
| 212 |
+
|
| 213 |
+
if not reliable_df.empty:
|
| 214 |
+
reliable_df = reliable_df.sort_values(
|
| 215 |
+
["AttendibilitΓ ", "Categoria", "Codice"]
|
| 216 |
+
).reset_index(drop=True)
|
| 217 |
+
if not discarded_df.empty:
|
| 218 |
+
discarded_df = discarded_df.sort_values("Codice").reset_index(drop=True)
|
| 219 |
+
|
| 220 |
+
return reliable_df, discarded_df
|
config.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import Enum
|
| 2 |
+
|
| 3 |
+
# βββ Costanti generali ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 4 |
+
APP_TITLE = "My Renault Dashboard"
|
| 5 |
+
APP_ICON = "β‘"
|
| 6 |
+
LOCALE = "it_IT"
|
| 7 |
+
API_TIMEOUT_SECONDS = 15 # β
FIX: era hardcoded in 3 posti diversi
|
| 8 |
+
AUTO_REFRESH_DEFAULT_SECONDS = 60
|
| 9 |
+
DEBUG_LOG_LIMIT = 80
|
| 10 |
+
|
| 11 |
+
CHARGE_MODE_ALWAYS_CANDIDATES = ["always_charging", "always", "always_schedule"]
|
| 12 |
+
CHARGE_MODE_SCHEDULE_CANDIDATES = ["schedule_mode", "scheduled", "schedule"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# βββ Enum azioni veicolo ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
# β
FIX: sostituisce magic strings sparse nel codice
|
| 17 |
+
class Azione(str, Enum):
|
| 18 |
+
AVVIA_RICARICA = "avvia_ricarica"
|
| 19 |
+
FERMA_RICARICA = "ferma_ricarica"
|
| 20 |
+
MODALITA_SEMPRE = "modalita_sempre"
|
| 21 |
+
MODALITA_PROGRAMMATA = "modalita_programmata"
|
| 22 |
+
IMPOSTA_SOC = "imposta_soc"
|
| 23 |
+
AVVIA_CLIMA = "avvia_clima"
|
| 24 |
+
FERMA_CLIMA = "ferma_clima"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# βββ CSS Tema dark βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
+
# β
FIX: tutti i colori ora usano var(--*) invece di hex hardcoded
|
| 29 |
+
CUSTOM_CSS = """
|
| 30 |
+
<style>
|
| 31 |
+
:root {
|
| 32 |
+
--bg-1: #121212;
|
| 33 |
+
--bg-2: #1b1b1b;
|
| 34 |
+
--bg-3: #242424;
|
| 35 |
+
--line: #333333;
|
| 36 |
+
--text-1: #f5f5f5;
|
| 37 |
+
--text-2: #b9b9b9;
|
| 38 |
+
--accent: #ffcc00;
|
| 39 |
+
--success: #1fa971;
|
| 40 |
+
--warning: #ff9f1c;
|
| 41 |
+
--danger: #e5484d;
|
| 42 |
+
--info: #4da3ff;
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
.main .block-container {
|
| 46 |
+
padding-top: 1rem;
|
| 47 |
+
padding-bottom: 1rem;
|
| 48 |
+
max-width: 1450px;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
h1, h2, h3 { color: var(--accent); }
|
| 52 |
+
|
| 53 |
+
.stTabs [data-baseweb="tab-list"] {
|
| 54 |
+
background-color: transparent;
|
| 55 |
+
border-bottom: 1px solid var(--line);
|
| 56 |
+
}
|
| 57 |
+
.stTabs [data-baseweb="tab"] {
|
| 58 |
+
color: #8f8f8f;
|
| 59 |
+
font-weight: 700;
|
| 60 |
+
border: none;
|
| 61 |
+
padding: 10px 15px;
|
| 62 |
+
}
|
| 63 |
+
.stTabs [data-baseweb="tab--active"] {
|
| 64 |
+
color: var(--accent);
|
| 65 |
+
border-bottom: 3px solid var(--accent);
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
.stButton > button,
|
| 69 |
+
.stFormSubmitButton > button,
|
| 70 |
+
.stDownloadButton > button {
|
| 71 |
+
background-color: var(--accent) !important;
|
| 72 |
+
color: var(--bg-1) !important; /* β
era #121212 hardcoded */
|
| 73 |
+
font-weight: 700 !important;
|
| 74 |
+
border-radius: 10px !important;
|
| 75 |
+
border: none !important;
|
| 76 |
+
}
|
| 77 |
+
.stButton > button:hover,
|
| 78 |
+
.stFormSubmitButton > button:hover,
|
| 79 |
+
.stDownloadButton > button:hover {
|
| 80 |
+
background-color: #ffb300 !important;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
.card {
|
| 84 |
+
background: linear-gradient(180deg, var(--bg-2) 0%, #171717 100%);
|
| 85 |
+
border: 1px solid var(--line);
|
| 86 |
+
border-radius: 16px;
|
| 87 |
+
padding: 18px 18px 16px 18px;
|
| 88 |
+
box-shadow: 0 10px 24px rgba(0,0,0,0.18);
|
| 89 |
+
height: 100%;
|
| 90 |
+
}
|
| 91 |
+
.card-title {
|
| 92 |
+
color: var(--text-2);
|
| 93 |
+
font-size: 0.9rem;
|
| 94 |
+
margin-bottom: 8px;
|
| 95 |
+
text-transform: uppercase;
|
| 96 |
+
letter-spacing: 0.6px;
|
| 97 |
+
}
|
| 98 |
+
.card-value {
|
| 99 |
+
color: var(--text-1);
|
| 100 |
+
font-size: 1.75rem;
|
| 101 |
+
font-weight: 800;
|
| 102 |
+
line-height: 1.15;
|
| 103 |
+
}
|
| 104 |
+
.card-value-small {
|
| 105 |
+
color: var(--text-1);
|
| 106 |
+
font-size: 1.25rem;
|
| 107 |
+
font-weight: 800;
|
| 108 |
+
line-height: 1.15;
|
| 109 |
+
}
|
| 110 |
+
.card-sub {
|
| 111 |
+
color: var(--text-2);
|
| 112 |
+
font-size: 0.9rem;
|
| 113 |
+
margin-top: 6px;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
.status-pill {
|
| 117 |
+
display: inline-block;
|
| 118 |
+
padding: 7px 12px;
|
| 119 |
+
border-radius: 999px;
|
| 120 |
+
font-size: 0.9rem;
|
| 121 |
+
font-weight: 700;
|
| 122 |
+
border: 1px solid transparent;
|
| 123 |
+
margin-right: 8px;
|
| 124 |
+
margin-bottom: 8px;
|
| 125 |
+
}
|
| 126 |
+
.status-success {
|
| 127 |
+
background-color: rgba(31,169,113,0.16);
|
| 128 |
+
color: #8ff0c5;
|
| 129 |
+
border-color: rgba(31,169,113,0.35);
|
| 130 |
+
}
|
| 131 |
+
.status-warning {
|
| 132 |
+
background-color: rgba(255,159,28,0.16);
|
| 133 |
+
color: #ffd190;
|
| 134 |
+
border-color: rgba(255,159,28,0.35);
|
| 135 |
+
}
|
| 136 |
+
.status-danger {
|
| 137 |
+
background-color: rgba(229,72,77,0.16);
|
| 138 |
+
color: #ffb0b2;
|
| 139 |
+
border-color: rgba(229,72,77,0.35);
|
| 140 |
+
}
|
| 141 |
+
.status-info {
|
| 142 |
+
background-color: rgba(77,163,255,0.16);
|
| 143 |
+
color: #aad0ff;
|
| 144 |
+
border-color: rgba(77,163,255,0.35);
|
| 145 |
+
}
|
| 146 |
+
.small-note { color: var(--text-2); font-size: 0.9rem; }
|
| 147 |
+
</style>
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# βββ Database codici VCD Renault βββββββββββββββββββββββββββββββββββββββββββββ
|
| 152 |
+
# β
FIX: estratto dal file principale (era embedded in mezzo al codice UI)
|
| 153 |
+
RELIABLE_VCD_CODES: dict[str, dict[str, str]] = {
|
| 154 |
+
# MOTORI
|
| 155 |
+
"5AM": {"Categoria": "Motore", "Significato": "Motore Elettrico R90/Q90 (92 CV)", "AttendibilitΓ ": "Alta"},
|
| 156 |
+
"5AQ": {"Categoria": "Motore", "Significato": "Motore Elettrico R135 (135 CV)", "AttendibilitΓ ": "Alta"},
|
| 157 |
+
"5BT": {"Categoria": "Motore", "Significato": "Motore Elettrico R135 (135 CV)", "AttendibilitΓ ": "Alta"},
|
| 158 |
+
"MOTEL": {"Categoria": "Motore", "Significato": "Trazione 100% Elettrica", "AttendibilitΓ ": "Alta"},
|
| 159 |
+
"M135": {"Categoria": "Motore", "Significato": "Motore Elettrico R135 (135 CV)", "AttendibilitΓ ": "Alta"},
|
| 160 |
+
"M110": {"Categoria": "Motore", "Significato": "Motore Elettrico R110 (110 CV)", "AttendibilitΓ ": "Alta"},
|
| 161 |
+
# BATTERIE E CARICATORI
|
| 162 |
+
"052KWH": {"Categoria": "Batteria", "Significato": "Pacco batteria Z.E. 50 (52 kWh netti)", "AttendibilitΓ ": "Alta"},
|
| 163 |
+
"52KWH": {"Categoria": "Batteria", "Significato": "Pacco batteria Z.E. 50 (52 kWh netti)", "AttendibilitΓ ": "Alta"},
|
| 164 |
+
"41KWH": {"Categoria": "Batteria", "Significato": "Pacco batteria Z.E. 40 (41 kWh netti)", "AttendibilitΓ ": "Alta"},
|
| 165 |
+
"22KWH": {"Categoria": "Batteria", "Significato": "Pacco batteria Z.E. (22 kWh netti)", "AttendibilitΓ ": "Alta"},
|
| 166 |
+
"BT4AR1": {"Categoria": "Batteria", "Significato": "Architettura Batteria (Z.E. 40 / Z.E. 50)","AttendibilitΓ ": "Alta"},
|
| 167 |
+
"BT5SEQ": {"Categoria": "Batteria", "Significato": "Batteria di trazione Serie 5", "AttendibilitΓ ": "Alta"},
|
| 168 |
+
"CACBL2": {"Categoria": "Ricarica", "Significato": "Cavo di ricarica Modo 3 (Tipo 2)", "AttendibilitΓ ": "Alta"},
|
| 169 |
+
"CHR50": {"Categoria": "Ricarica", "Significato": "Ricarica Rapida DC 50kW (CCS Combo)", "AttendibilitΓ ": "Alta"},
|
| 170 |
+
"CHR00": {"Categoria": "Ricarica", "Significato": "Solo Ricarica AC (No ricarica DC)", "AttendibilitΓ ": "Alta"},
|
| 171 |
+
"CHAM1": {"Categoria": "Ricarica", "Significato": "Caricatore di bordo AC 22kW (Chameleon)", "AttendibilitΓ ": "Alta"},
|
| 172 |
+
# ALLESTIMENTI
|
| 173 |
+
"EA1": {"Categoria": "Allestimento","Significato": "Base (Life / Equilibre)", "AttendibilitΓ ": "Alta"},
|
| 174 |
+
"EA2": {"Categoria": "Allestimento","Significato": "Intermedio (Zen / Evolution)", "AttendibilitΓ ": "Alta"},
|
| 175 |
+
"EA3": {"Categoria": "Allestimento","Significato": "Top (Intens / Techno)", "AttendibilitΓ ": "Alta"},
|
| 176 |
+
"EA4": {"Categoria": "Allestimento","Significato": "Premium (Edition One / Iconic)", "AttendibilitΓ ": "Alta"},
|
| 177 |
+
# COLORI
|
| 178 |
+
"OV369": {"Categoria": "Colore", "Significato": "Bianco Ghiaccio (Tinta unita)", "AttendibilitΓ ": "Alta"},
|
| 179 |
+
"QNC": {"Categoria": "Colore", "Significato": "Bianco Quarzo (Metallizzato)", "AttendibilitΓ ": "Alta"},
|
| 180 |
+
"KNG": {"Categoria": "Colore", "Significato": "Grigio Cassiopea (Metallizzato)", "AttendibilitΓ ": "Alta"},
|
| 181 |
+
"KPW": {"Categoria": "Colore", "Significato": "Grigio Titanio (Metallizzato)", "AttendibilitΓ ": "Alta"},
|
| 182 |
+
"GNE": {"Categoria": "Colore", "Significato": "Nero Etoile (Metallizzato)", "AttendibilitΓ ": "Alta"},
|
| 183 |
+
"RQH": {"Categoria": "Colore", "Significato": "Blu Iron (Metallizzato)", "AttendibilitΓ ": "Alta"},
|
| 184 |
+
"NNP": {"Categoria": "Colore", "Significato": "Rosso Passion (Metallizzato)", "AttendibilitΓ ": "Alta"},
|
| 185 |
+
"RQE": {"Categoria": "Colore", "Significato": "Blu Celadon (Metallizzato)", "AttendibilitΓ ": "Alta"},
|
| 186 |
+
# RUOTE
|
| 187 |
+
"RALU15": {"Categoria": "Ruote", "Significato": "Cerchi in lega da 15 pollici", "AttendibilitΓ ": "Alta"},
|
| 188 |
+
"RALU16": {"Categoria": "Ruote", "Significato": "Cerchi in lega da 16 pollici", "AttendibilitΓ ": "Alta"},
|
| 189 |
+
"RALU17": {"Categoria": "Ruote", "Significato": "Cerchi in lega da 17 pollici", "AttendibilitΓ ": "Alta"},
|
| 190 |
+
"RDIF15": {"Categoria": "Ruote", "Significato": "Cerchi in acciaio da 15 pollici", "AttendibilitΓ ": "Alta"},
|
| 191 |
+
"RDIF16": {"Categoria": "Ruote", "Significato": "Cerchi in acciaio da 16 pollici", "AttendibilitΓ ": "Alta"},
|
| 192 |
+
"RDIF01": {"Categoria": "Ruote", "Significato": "Cerchi standard di fabbrica", "AttendibilitΓ ": "Alta"},
|
| 193 |
+
# CARROZZERIA E MODELLO
|
| 194 |
+
"X10": {"Categoria": "Modello", "Significato": "Renault Zoe (Codice famiglia X10)", "AttendibilitΓ ": "Alta"},
|
| 195 |
+
"B10": {"Categoria": "Carrozzeria","Significato": "Berlina 5 porte hatchback", "AttendibilitΓ ": "Alta"},
|
| 196 |
+
"DG": {"Categoria": "Guida", "Significato": "Veicolo con guida a sinistra (LHD)", "AttendibilitΓ ": "Alta"},
|
| 197 |
+
"TR4X2": {"Categoria": "Powertrain","Significato": "Trazione anteriore (2 ruote motrici)", "AttendibilitΓ ": "Alta"},
|
| 198 |
+
"PHAS1": {"Categoria": "Modello", "Significato": "Fase 1 (Pre-restyling)", "AttendibilitΓ ": "Alta"},
|
| 199 |
+
"PHAS2": {"Categoria": "Modello", "Significato": "Fase 2 (Restyling)", "AttendibilitΓ ": "Alta"},
|
| 200 |
+
# INTERNI E COMFORT
|
| 201 |
+
"HARM02": {"Categoria": "Interni", "Significato": "Armonia interna in tinta scura", "AttendibilitΓ ": "Alta"},
|
| 202 |
+
"CAREG": {"Categoria": "Clima", "Significato": "Climatizzatore Automatico Regolato", "AttendibilitΓ ": "Alta"},
|
| 203 |
+
"1234Y": {"Categoria": "Clima", "Significato": "Gas refrigerante R1234yf (Pompa calore)", "AttendibilitΓ ": "Alta"},
|
| 204 |
+
"ADAC": {"Categoria": "Strumentazione","Significato": "Quadro strumenti completamente digitale","AttendibilitΓ ": "Alta"},
|
| 205 |
+
"VLCUIR": {"Categoria": "Interni", "Significato": "Volante rivestito in pelle / ecopelle", "AttendibilitΓ ": "Alta"},
|
| 206 |
+
"RETRCR": {"Categoria": "VisibilitΓ ","Significato": "Retrovisore interno fotocromatico", "AttendibilitΓ ": "Alta"},
|
| 207 |
+
"SFBANA": {"Categoria": "Interni", "Significato": "Sedile posteriore sdoppiabile (1/3β2/3)", "AttendibilitΓ ": "Alta"},
|
| 208 |
+
"ALEVA": {"Categoria": "Comfort", "Significato": "Alzacristalli elettrici anteriori", "AttendibilitΓ ": "Alta"},
|
| 209 |
+
"LVAREL": {"Categoria": "Comfort", "Significato": "Alzacristalli elettrici posteriori", "AttendibilitΓ ": "Alta"},
|
| 210 |
+
"VSTLAR": {"Categoria": "Esterni", "Significato": "Vetri posteriori oscurati (Privacy Glass)","AttendibilitΓ ": "Alta"},
|
| 211 |
+
# SICUREZZA E ADAS
|
| 212 |
+
"ELEC": {"Categoria": "Powertrain","Significato": "Alimentazione elettrica (EV)", "AttendibilitΓ ": "Alta"},
|
| 213 |
+
"ABS": {"Categoria": "Sicurezza", "Significato": "Sistema frenata antibloccaggio (ABS)", "AttendibilitΓ ": "Alta"},
|
| 214 |
+
"ASRESP": {"Categoria": "Sicurezza", "Significato": "Controllo elettronico stabilitΓ (ESP/ESC)","AttendibilitΓ ": "Alta"},
|
| 215 |
+
"AFURGE": {"Categoria": "Sicurezza", "Significato": "Assistenza alla Frenata di Emergenza", "AttendibilitΓ ": "Alta"},
|
| 216 |
+
"AEBS07": {"Categoria": "ADAS", "Significato": "Frenata automatica di emergenza attiva", "AttendibilitΓ ": "Alta"},
|
| 217 |
+
"DANGMO": {"Categoria": "ADAS", "Significato": "Sensore Angolo Cieco (Blind Spot Warning)","AttendibilitΓ ": "Alta"},
|
| 218 |
+
"RV": {"Categoria": "ADAS", "Significato": "Regolatore e Limitatore di VelocitΓ ", "AttendibilitΓ ": "Alta"},
|
| 219 |
+
"PRAHL": {"Categoria": "Illuminazione","Significato": "Commutazione automatica abbaglianti", "AttendibilitΓ ": "Alta"},
|
| 220 |
+
"ABLAV": {"Categoria": "VisibilitΓ ","Significato": "Sensore Pioggia e Luce (Tergicristalli Auto)","AttendibilitΓ ": "Alta"},
|
| 221 |
+
"FDIU2": {"Categoria": "Illuminazione","Significato": "Fari diurni a LED a forma di C", "AttendibilitΓ ": "Alta"},
|
| 222 |
+
"PROJAB": {"Categoria": "Illuminazione","Significato": "Fari fendinebbia", "AttendibilitΓ ": "Alta"},
|
| 223 |
+
"RRCAM": {"Categoria": "Parcheggio","Significato": "Retrocamera di parcheggio", "AttendibilitΓ ": "Alta"},
|
| 224 |
+
"ITPK1": {"Categoria": "Parcheggio","Significato": "Sensori di parcheggio posteriori", "AttendibilitΓ ": "Alta"},
|
| 225 |
+
"ITPK4": {"Categoria": "Parcheggio","Significato": "Sensori di parcheggio anteriori e posteriori","AttendibilitΓ ": "Alta"},
|
| 226 |
+
"DPRPN": {"Categoria": "Sicurezza", "Significato": "Monitoraggio pressione pneumatici (TPMS)", "AttendibilitΓ ": "Alta"},
|
| 227 |
+
"FSTPO": {"Categoria": "Guida", "Significato": "Freno di stazionamento elettrico (Auto-Hold)","AttendibilitΓ ": "Alta"},
|
| 228 |
+
"AIRBA2": {"Categoria": "Sicurezza", "Significato": "Airbag frontali conducente e passeggero", "AttendibilitΓ ": "Alta"},
|
| 229 |
+
"AIRBDE": {"Categoria": "Sicurezza", "Significato": "Disattivazione airbag passeggero", "AttendibilitΓ ": "Alta"},
|
| 230 |
+
"CMAR3P": {"Categoria": "Sicurezza", "Significato": "Cinture di sicurezza posteriori a 3 punti","AttendibilitΓ ": "Alta"},
|
| 231 |
+
"ISOFIX": {"Categoria": "Sicurezza", "Significato": "Attacchi ISOFIX per seggiolini", "AttendibilitΓ ": "Alta"},
|
| 232 |
+
"SSCALL": {"Categoria": "Sicurezza", "Significato": "Sistema chiamata d'emergenza (eCall)", "AttendibilitΓ ": "Alta"},
|
| 233 |
+
"SKTGRV": {"Categoria": "Dotazione", "Significato": "Kit gonfiaggio pneumatici (No ruota scorta)","AttendibilitΓ ": "Alta"},
|
| 234 |
+
"CPETIR": {"Categoria": "Chiusure", "Significato": "Chiusura centralizzata elettrica", "AttendibilitΓ ": "Alta"},
|
| 235 |
+
"SSHYB": {"Categoria": "Powertrain","Significato": "Senza sistema ibrido (EV Puro)", "AttendibilitΓ ": "Alta"},
|
| 236 |
+
"BVEL": {"Categoria": "Trasmissione","Significato": "Riduttore monomarcia per veicoli elettrici","AttendibilitΓ ": "Alta"},
|
| 237 |
+
# VARIE
|
| 238 |
+
"SERIE": {"Categoria": "Dotazione", "Significato": "Equipaggiamento di serie", "AttendibilitΓ ": "Alta"},
|
| 239 |
+
"ITA": {"Categoria": "Mercato", "Significato": "Configurazione mercato Italia", "AttendibilitΓ ": "Alta"},
|
| 240 |
+
"ITA01": {"Categoria": "Mercato", "Significato": "Configurazione mercato Italia", "AttendibilitΓ ": "Alta"},
|
| 241 |
+
"EQPEUR": {"Categoria": "Mercato", "Significato": "Equipaggiamento Europa", "AttendibilitΓ ": "Alta"},
|
| 242 |
+
"KM": {"Categoria": "Strumentazione","Significato": "Tachimetro e odometro in chilometri", "AttendibilitΓ ": "Alta"},
|
| 243 |
+
}
|
ui_components.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ui_components.py β Componenti Streamlit riutilizzabili: card, mappa, veicolo.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import streamlit as st
|
| 8 |
+
|
| 9 |
+
from utils import safe_get, format_number, format_datetime
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
import pydeck as pdk
|
| 13 |
+
except Exception:
|
| 14 |
+
pdk = None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# βββ Status pill HTML βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 18 |
+
|
| 19 |
+
def status_pill_html(text: str, kind: str = "info") -> str:
|
| 20 |
+
return f'<span class="status-pill status-{kind}">{text}</span>'
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# βββ KPI card βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 24 |
+
# β
FIX: render_kpi_card e render_info_tile erano quasi identiche.
|
| 25 |
+
# Unificate con parametro `small`.
|
| 26 |
+
|
| 27 |
+
def render_kpi_card(title: str, value: str, subtitle: str = "", small: bool = False) -> None:
|
| 28 |
+
value_class = "card-value-small" if small else "card-value"
|
| 29 |
+
st.markdown(
|
| 30 |
+
f"""
|
| 31 |
+
<div class="card">
|
| 32 |
+
<div class="card-title">{title}</div>
|
| 33 |
+
<div class="{value_class}">{value}</div>
|
| 34 |
+
<div class="card-sub">{subtitle}</div>
|
| 35 |
+
</div>
|
| 36 |
+
""",
|
| 37 |
+
unsafe_allow_html=True,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def render_info_tile(title: str, value: str, subtitle: str = "") -> None:
|
| 42 |
+
"""Alias per render_kpi_card con testo piΓΉ piccolo (compatibilitΓ )."""
|
| 43 |
+
render_kpi_card(title, value, subtitle, small=True)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# βββ Mappa GPS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 47 |
+
|
| 48 |
+
def build_google_maps_url(lat: Any, lon: Any) -> str | None:
|
| 49 |
+
if lat is None or lon is None:
|
| 50 |
+
return None
|
| 51 |
+
return f"https://www.google.com/maps?q={lat},{lon}"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def render_map(lat: Any, lon: Any, zoom: int = 15) -> None:
|
| 55 |
+
if lat is None or lon is None:
|
| 56 |
+
st.warning("Dati GPS non disponibili.")
|
| 57 |
+
return
|
| 58 |
+
|
| 59 |
+
import pandas as pd
|
| 60 |
+
df = pd.DataFrame({"lat": [float(lat)], "lon": [float(lon)]})
|
| 61 |
+
|
| 62 |
+
if pdk is None:
|
| 63 |
+
st.map(df, zoom=zoom)
|
| 64 |
+
return
|
| 65 |
+
|
| 66 |
+
layer = pdk.Layer(
|
| 67 |
+
"ScatterplotLayer",
|
| 68 |
+
data=df,
|
| 69 |
+
get_position="[lon, lat]",
|
| 70 |
+
get_radius=35,
|
| 71 |
+
get_fill_color=[255, 40, 40, 200],
|
| 72 |
+
pickable=True,
|
| 73 |
+
auto_highlight=True,
|
| 74 |
+
)
|
| 75 |
+
tooltip = {
|
| 76 |
+
"html": "<b>Il tuo veicolo</b><br/>Lat: {lat}<br/>Lon: {lon}",
|
| 77 |
+
"style": {"backgroundColor": "#111", "color": "white"},
|
| 78 |
+
}
|
| 79 |
+
view_state = pdk.ViewState(latitude=float(lat), longitude=float(lon), zoom=zoom, pitch=0)
|
| 80 |
+
st.pydeck_chart(pdk.Deck(layers=[layer], initial_view_state=view_state, tooltip=tooltip))
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# βββ Scheda veicolo βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 84 |
+
|
| 85 |
+
def render_vehicle_card(vin: str, cockpit: Any, details: Any, lock_status: Any) -> None:
|
| 86 |
+
raw_details = getattr(details, "raw_data", {}) if details else {}
|
| 87 |
+
|
| 88 |
+
# Immagine ufficiale dal portale MyRenault
|
| 89 |
+
img_url = None
|
| 90 |
+
for asset in raw_details.get("assets", []):
|
| 91 |
+
if asset.get("viewpoint") == "mybrand_5":
|
| 92 |
+
for r in asset.get("renditions", []):
|
| 93 |
+
if r.get("resolutionType") == "ONE_MYRENAULT_LARGE":
|
| 94 |
+
img_url = r.get("url")
|
| 95 |
+
break
|
| 96 |
+
if img_url:
|
| 97 |
+
st.image(img_url, caption="Il tuo veicolo", use_container_width=True)
|
| 98 |
+
|
| 99 |
+
modello_label = raw_details.get("model", {}).get("label", "Renault")
|
| 100 |
+
versione_raw = raw_details.get("version", {}).get("label", "N/D")
|
| 101 |
+
motore_label = raw_details.get("engineType", "N/D")
|
| 102 |
+
batt_label = raw_details.get("batteryType", "N/D")
|
| 103 |
+
|
| 104 |
+
st.markdown(f"### π {modello_label} {versione_raw}")
|
| 105 |
+
|
| 106 |
+
r1c1, r1c2 = st.columns(2)
|
| 107 |
+
with r1c1:
|
| 108 |
+
st.write(f"**Modello:** {modello_label}")
|
| 109 |
+
st.write(f"**Targa:** {raw_details.get('registrationNumber', 'N/D')}")
|
| 110 |
+
st.write(f"**VIN:** {vin}")
|
| 111 |
+
with r1c2:
|
| 112 |
+
st.write(f"**Batteria:** {batt_label}")
|
| 113 |
+
st.write(f"**Motore:** {motore_label}")
|
| 114 |
+
st.write(f"**Odometro:** {format_number(safe_get(cockpit, 'totalMileage'), ' km')}")
|
| 115 |
+
|
| 116 |
+
st.markdown("---")
|
| 117 |
+
st.markdown("**π
Storia dell'auto**")
|
| 118 |
+
h1, h2 = st.columns(2)
|
| 119 |
+
with h1:
|
| 120 |
+
st.info(f"ποΈ **Prodotta il:**\n\n{raw_details.get('manufacturingDate', 'N/D')}")
|
| 121 |
+
with h2:
|
| 122 |
+
st.success(f"π **Immatricolata il:**\n\n{raw_details.get('registrationDate', 'N/D')}")
|
utils.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
utils.py β Funzioni helper: formatter, session state, async runner.
|
| 3 |
+
Nessuna chiamata API o rendering Streamlit diretto qui.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from typing import Any, Awaitable
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import streamlit as st
|
| 12 |
+
|
| 13 |
+
from config import AUTO_REFRESH_DEFAULT_SECONDS, DEBUG_LOG_LIMIT
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# βββ Segreti βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 17 |
+
|
| 18 |
+
def safe_secret(key: str, default: str = "") -> str:
|
| 19 |
+
try:
|
| 20 |
+
return st.secrets.get(key, default)
|
| 21 |
+
except Exception:
|
| 22 |
+
return default
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# βββ Session state ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 26 |
+
|
| 27 |
+
def init_state() -> None:
|
| 28 |
+
defaults: dict[str, Any] = {
|
| 29 |
+
"autenticato": False,
|
| 30 |
+
"dati_auto": None,
|
| 31 |
+
"ultimo_refresh": None,
|
| 32 |
+
"ultimo_errore": None,
|
| 33 |
+
"email_input": "",
|
| 34 |
+
"password_input": "",
|
| 35 |
+
"_hidden_password": "",
|
| 36 |
+
"auto_refresh_enabled": False,
|
| 37 |
+
"auto_refresh_seconds": AUTO_REFRESH_DEFAULT_SECONDS,
|
| 38 |
+
"lookback_days": 180,
|
| 39 |
+
"map_zoom": 15,
|
| 40 |
+
"debug_events": [],
|
| 41 |
+
"costo_kwh": 0.25,
|
| 42 |
+
# multi-vehicle
|
| 43 |
+
"vehicle_list": [],
|
| 44 |
+
"renault_vin_selected": None,
|
| 45 |
+
}
|
| 46 |
+
for key, value in defaults.items():
|
| 47 |
+
if key not in st.session_state:
|
| 48 |
+
st.session_state[key] = value
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_current_credentials() -> tuple[str, str]:
|
| 52 |
+
email = str(st.session_state.get("email_input", "")).strip()
|
| 53 |
+
password = str(st.session_state.get("_hidden_password", ""))
|
| 54 |
+
if not password:
|
| 55 |
+
password = str(st.session_state.get("password_input", ""))
|
| 56 |
+
return email, password
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# βββ Debug log ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 60 |
+
|
| 61 |
+
def add_debug_event(message: str, level: str = "info") -> None:
|
| 62 |
+
event = {
|
| 63 |
+
"Ora": datetime.now().strftime("%d/%m/%Y %H:%M:%S"),
|
| 64 |
+
"Livello": level.upper(),
|
| 65 |
+
"Messaggio": message,
|
| 66 |
+
}
|
| 67 |
+
events = [event] + st.session_state.get("debug_events", [])
|
| 68 |
+
st.session_state["debug_events"] = events[:DEBUG_LOG_LIMIT]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# βββ Async runner βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 72 |
+
|
| 73 |
+
def run_async(coro: Awaitable[Any]) -> Any:
|
| 74 |
+
try:
|
| 75 |
+
return asyncio.run(coro)
|
| 76 |
+
except RuntimeError:
|
| 77 |
+
loop = asyncio.new_event_loop()
|
| 78 |
+
try:
|
| 79 |
+
asyncio.set_event_loop(loop)
|
| 80 |
+
return loop.run_until_complete(coro)
|
| 81 |
+
finally:
|
| 82 |
+
loop.close()
|
| 83 |
+
asyncio.set_event_loop(None)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# βββ Accesso sicuro ad oggetti / dict ββββββββββββββββββββββββββββββββββββββββ
|
| 87 |
+
|
| 88 |
+
def safe_get(obj: Any, *names: str, default: Any = None) -> Any:
|
| 89 |
+
if obj is None:
|
| 90 |
+
return default
|
| 91 |
+
for name in names:
|
| 92 |
+
if isinstance(obj, dict) and name in obj:
|
| 93 |
+
value = obj.get(name)
|
| 94 |
+
if value is not None:
|
| 95 |
+
return value
|
| 96 |
+
if hasattr(obj, name):
|
| 97 |
+
value = getattr(obj, name)
|
| 98 |
+
if value is not None:
|
| 99 |
+
return value
|
| 100 |
+
return default
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# βββ Estrazione / normalizzazione valori βββββββββββββββββββββββββββββββββββββ
|
| 104 |
+
|
| 105 |
+
def extract_display_value(value: Any, fallback: str = "N/D") -> str:
|
| 106 |
+
if value is None:
|
| 107 |
+
return fallback
|
| 108 |
+
if isinstance(value, (str, int, float, bool)):
|
| 109 |
+
text = str(value).strip()
|
| 110 |
+
return text if text else fallback
|
| 111 |
+
for attr in ("label", "name", "code", "value"):
|
| 112 |
+
if hasattr(value, attr):
|
| 113 |
+
v = getattr(value, attr)
|
| 114 |
+
if v not in (None, ""):
|
| 115 |
+
return str(v)
|
| 116 |
+
raw = getattr(value, "raw_data", None)
|
| 117 |
+
if isinstance(raw, dict):
|
| 118 |
+
for key in ("label", "name", "code", "value"):
|
| 119 |
+
v = raw.get(key)
|
| 120 |
+
if v not in (None, ""):
|
| 121 |
+
return str(v)
|
| 122 |
+
return fallback
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def humanize_energy_label(value: Any) -> str:
|
| 126 |
+
text = extract_display_value(value, fallback="N/D").strip()
|
| 127 |
+
mapping = {
|
| 128 |
+
"ELECTRICITY": "Elettrica",
|
| 129 |
+
"ELEC": "Elettrica",
|
| 130 |
+
"PETROL": "Benzina",
|
| 131 |
+
"DIESEL": "Diesel",
|
| 132 |
+
"HYBRID": "Ibrida",
|
| 133 |
+
"PLUGIN_HYBRID": "Ibrida plug-in",
|
| 134 |
+
}
|
| 135 |
+
return mapping.get(text.upper(), text)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def prettify_generic_status(value: Any) -> str:
|
| 139 |
+
raw = str(value).strip().lower()
|
| 140 |
+
mapping = {
|
| 141 |
+
"locked": "Chiusa",
|
| 142 |
+
"unlocked": "Aperta",
|
| 143 |
+
"closed": "Chiusa",
|
| 144 |
+
"open": "Aperta",
|
| 145 |
+
"yes": "Sì",
|
| 146 |
+
"no": "No",
|
| 147 |
+
"true": "Sì",
|
| 148 |
+
"false": "No",
|
| 149 |
+
"1": "Sì",
|
| 150 |
+
"0": "No",
|
| 151 |
+
"none": "N/D",
|
| 152 |
+
"n/d": "N/D",
|
| 153 |
+
"": "N/D",
|
| 154 |
+
}
|
| 155 |
+
return mapping.get(raw, str(value) if value not in (None, "") else "N/D")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def bool_like(value: Any) -> bool:
|
| 159 |
+
"""
|
| 160 |
+
β
FIX: era `== 1.0` (quindi 1.5 β False); ora usa `> 0` per coerenza.
|
| 161 |
+
"""
|
| 162 |
+
try:
|
| 163 |
+
return float(value) > 0
|
| 164 |
+
except (ValueError, TypeError):
|
| 165 |
+
pass
|
| 166 |
+
return str(value).strip().lower() in {
|
| 167 |
+
"1", "1.0", "true", "yes", "on",
|
| 168 |
+
"plugged", "connected", "locked", "charging", "charge_in_progress",
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def format_datetime(value: Any, fallback: str = "N/D") -> str:
|
| 173 |
+
if value in (None, "", "N/D"):
|
| 174 |
+
return fallback
|
| 175 |
+
try:
|
| 176 |
+
ts = pd.to_datetime(value, utc=True, errors="coerce")
|
| 177 |
+
if pd.isna(ts):
|
| 178 |
+
return str(value)
|
| 179 |
+
return ts.tz_convert("Europe/Rome").tz_localize(None).strftime("%d/%m/%Y %H:%M")
|
| 180 |
+
except Exception:
|
| 181 |
+
return str(value)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def format_number(
|
| 185 |
+
value: Any,
|
| 186 |
+
suffix: str = "",
|
| 187 |
+
fallback: str = "N/D",
|
| 188 |
+
decimals: int = 0,
|
| 189 |
+
) -> str:
|
| 190 |
+
if value in (None, "", "N/D"):
|
| 191 |
+
return fallback
|
| 192 |
+
try:
|
| 193 |
+
number = float(value)
|
| 194 |
+
if decimals == 0:
|
| 195 |
+
return f"{int(round(number))}{suffix}"
|
| 196 |
+
return f"{number:.{decimals}f}{suffix}"
|
| 197 |
+
except Exception:
|
| 198 |
+
return f"{value}{suffix}"
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def normalize_charge_mode(value: Any) -> str:
|
| 202 |
+
raw = str(value).strip().lower()
|
| 203 |
+
if raw in {"always", "always_charging", "always_schedule"}:
|
| 204 |
+
return "Sempre"
|
| 205 |
+
if raw in {"scheduled", "schedule_mode", "schedule"}:
|
| 206 |
+
return "Programmata"
|
| 207 |
+
return str(value) if value not in (None, "") else "N/D"
|