Affichage état gyro sur app

This commit is contained in:
2025-10-14 19:05:54 +02:00
parent e5896ad32f
commit e1f91660cf
2 changed files with 88 additions and 5 deletions

6
.env
View File

@@ -54,12 +54,10 @@ ALERT_SMS_TO_MEUDON=Michel:+33759600180
ALERT_SMS_CLIENT_TO_MEUDON=Sekou:+33625903364,Damien:+33680388259 ALERT_SMS_CLIENT_TO_MEUDON=Sekou:+33625903364,Damien:+33680388259
ALERT_SMS_CLIENT_TO_SACLAY=Nicolas:+33682069405,Sabrina:+33650270939,Mirceta:+33601162960 ALERT_SMS_CLIENT_TO_SACLAY=Nicolas:+33682069405,Sabrina:+33650270939,Mirceta:+33601162960
# Activer/désactiver globalement lenvoi client # Activer/désactiver globalement lenvoi client
ALERT_SMS_CLIENT_ENABLED=1 ALERT_SMS_CLIENT_ENABLED=0
# 1) couper les SMS internes # 1) couper les SMS internes
ALERT_INTERNAL_SMS_ENABLED=0# 0 = coupe tous les SMS “internes” (déclenchement) ALERT_INTERNAL_SMS_ENABLED=0# 0 = coupe tous les SMS “internes” (déclenchement)
# 2) limiter le flux par cooldown (par sonde) # 2) limiter le flux par cooldown (par sonde)
ALERT_SMS_COOLDOWN_SEC=3600# 3600s = 1 SMS max / sonde / heure ALERT_SMS_COOLDOWN_SEC=3600# 3600s = 1 SMS max / sonde / heure
# (compatibilité: si non défini, on retombe sur GYRO_SMS_MIN_SEC ou 120s) # (compatibilité: si non défini, on retombe sur GYRO_SMS_MIN_SEC ou 120s)

View File

@@ -39,6 +39,81 @@ SITES_AUTORISES = {"Saclay", "Meudon", "Roissy"} # anti-injection sur noms de t
def get_connection(): def get_connection():
return mysql.connector.connect(**db_config) return mysql.connector.connect(**db_config)
# --- Gyro: lecture + badge (auto) ---
def fetch_gyro(site: str):
"""Retourne (etat, ts) depuis la vue v_gyro_last pour le site donné."""
q = """
SELECT Etat, `Date`
FROM v_gyro_last
WHERE Lieu = %s AND Sonde = 'Gyro'
ORDER BY `Date` DESC
LIMIT 1
"""
cnx = get_connection()
try:
cur = cnx.cursor(dictionary=True)
cur.execute(q, (site,))
row = cur.fetchone()
if not row:
return None, None
etat = (row.get("Etat") or "").strip().upper()
ts = row.get("Date")
return etat, ts
finally:
try:
cur.close()
except Exception:
pass
try:
cnx.close()
except Exception:
pass
def render_gyro_badge(site: str, stale_after_min: int = 10):
"""Affiche un voyant Gyro (vert/rouge/orange) + fraîcheur des données."""
etat, ts = fetch_gyro(site)
# Etat → couleur/label
if etat in ("ON", "1"):
color, label = "#22c55e", "GYRO ON"
elif etat in ("OFF", "0"):
color, label = "#ef4444", "GYRO OFF"
elif etat in ("ALERTE", "ALARM", "ALARMED"):
color, label = "#f59e0b", "GYRO ALERTE"
else:
color, label = "#9E9E9E", "GYRO INCONNU"
# Fraîcheur
stale = True
age_txt = ""
if ts is not None:
try:
# ts provient normalement de MySQL déjà en datetime
from datetime import datetime as _dt
now = _dt.now(ts.tzinfo) if hasattr(ts, "tzinfo") and ts.tzinfo else _dt.now()
mins = int((now - ts).total_seconds() // 60)
stale = mins >= stale_after_min
age_txt = f"MAJ: {ts:%d/%m/%Y %H:%M} ({mins} min)"
except Exception:
pass
border = "4px dashed" if stale else "4px solid"
opacity = "0.6" if stale else "1"
st.markdown(f"""
<div style="display:flex;align-items:center;gap:12px;
padding:10px 14px;border:{border} {color};
border-radius:16px;background:rgba(0,0,0,0.03);">
<div style="width:18px;height:18px;border-radius:50%;
background:{color};opacity:{opacity};
box-shadow:0 0 14px {color};"></div>
<div style="font-weight:600;font-size:1rem;color:{color};">{label}</div>
<div style="margin-left:auto;font-size:0.85rem;color:#666;">
{age_txt}{' — données anciennes' if stale else ''}
</div>
</div>
""", unsafe_allow_html=True)
def get_conn(): def get_conn():
return mysql.connector.connect(**db_config) return mysql.connector.connect(**db_config)
@@ -344,7 +419,7 @@ def generer_pdf(site, date_str, periode):
pdf.releves_section(releves) pdf.releves_section(releves)
pdf.alertes_section(alertes) pdf.alertes_section(alertes)
output_dir = "PDF" output_dir = "../PDF"
os.makedirs(output_dir, exist_ok=True) os.makedirs(output_dir, exist_ok=True)
file_name = f"rapport_{site}_{date_str}.pdf" file_name = f"rapport_{site}_{date_str}.pdf"
output_path = os.path.join(output_dir, file_name) output_path = os.path.join(output_dir, file_name)
@@ -696,6 +771,16 @@ if st.session_state["authenticated"]:
# ------------------ Accueil ------------------ # ------------------ Accueil ------------------
if onglet_selectionne == "Accueil": if onglet_selectionne == "Accueil":
try: try:
# --- Voyant Gyro pour le site courant ---
st.subheader(f"🚨 Statut Gyro — {site_actuel}")
try:
st.autorefresh(interval=30000, key="gyro_autorefresh")
except Exception:
pass
render_gyro_badge(site_actuel)
# ----------------------------------------
conn = get_connection() conn = get_connection()
cursor = conn.cursor(dictionary=True) cursor = conn.cursor(dictionary=True)