From b5a692d2bd0321f6ba19e57979899b89550d8378 Mon Sep 17 00:00:00 2001 From: Michel Date: Sun, 31 Aug 2025 18:26:48 +0200 Subject: [PATCH] Modif Tracker --- README.md => Docs/README.md | Bin 10734 -> 10724 bytes graphique.png => Docs/graphique.png | Bin app/tracker.py | 235 +++++++++++++--------------- scripts/envoi_sms.php | 32 ---- 4 files changed, 107 insertions(+), 160 deletions(-) rename README.md => Docs/README.md (99%) rename graphique.png => Docs/graphique.png (100%) delete mode 100644 scripts/envoi_sms.php diff --git a/README.md b/Docs/README.md similarity index 99% rename from README.md rename to Docs/README.md index 47132cf9e6ac36d61620e2692fc14c15b817598a..521b32feef6827a409b5e1c4887c9e7daab494ba 100644 GIT binary patch delta 12 TcmaDC{3Lk89?s3jI5iXiER+Sf delta 22 dcmaD7{4RLI9!^ddhJ1!(hGGW&&AT}@6#!+W2X6oX diff --git a/graphique.png b/Docs/graphique.png similarity index 100% rename from graphique.png rename to Docs/graphique.png diff --git a/app/tracker.py b/app/tracker.py index 1d04b51..9c81ffc 100644 --- a/app/tracker.py +++ b/app/tracker.py @@ -1,8 +1,10 @@ -# tracker_app.py +# tracker.py # ------------------------------------------------------------- -# Streamlit — Gestion de la table MySQL Sondes.tracker +# Streamlit — Gestion de la table MySQL Sondes.tracker (avec address_hyphen) # ------------------------------------------------------------- -# Schéma attendu : id (PK), address, lieu, repere, mise_en_service (DATE), res_bits, date (timestamp) +# Schéma attendu : +# id (PK), address (ROM {0x..}), address_hyphen (28-..-..-..-..-..-..-..), +# lieu, repere, mise_en_service (DATE), res_bits, date (timestamp) # Authentification intégrée via .env (AUTH_USERS JSON) # ------------------------------------------------------------- @@ -27,7 +29,8 @@ load_dotenv() # lit .env si présent TABLE_NAME = "tracker" COL_ID = "id" -COL_ADDRESS = "address" +COL_ADDRESS = "address" # format ROM : {0x28,0xFF,...} +COL_ADDR_HYPHEN = "address_hyphen" # format hyphen : 28-xx-xx-xx-xx-xx-xx-xx COL_LIEU = "lieu" COL_REPERE = "repere" COL_MES = "mise_en_service" # DATE @@ -45,6 +48,8 @@ DB_CFG = dict( # Regex d'une ROM code DS18B20 au format {0x28,0xFF,0xAA,0xBB,0xCC,0xDD,0xEE,0xCRC} ROM_REGEX = re.compile(r"^{(?:0x[0-9A-Fa-f]{2},){7}0x[0-9A-Fa-f]{2}}$") +# Adresse hyphen : 8 octets hexa séparés par des tirets +HYPHEN_REGEX = re.compile(r"^[0-9A-Fa-f]{2}(?:-[0-9A-Fa-f]{2}){7}$") # Mapping résolution DS18B20 (bits -> infos) RES_MAP = { @@ -77,7 +82,6 @@ def verify_credentials(username: str, password: str) -> bool: expected = USERS.get(username.strip()) if expected is None: return False - # NOTE : stockage en clair pour l'exemple. En prod, préférer un hash (bcrypt/argon2). return _constant_time_equals(password, expected) def require_login() -> Optional[str]: @@ -85,8 +89,6 @@ def require_login() -> Optional[str]: return st.session_state.get("auth_user") st.markdown("

🔒 Tracker

", unsafe_allow_html=True) - - # Formulaire centré _, col2, _ = st.columns([1, 2, 1]) with col2: with st.form("login_form", clear_on_submit=False): @@ -115,34 +117,78 @@ def get_conn(): finally: conn.close() -# -------------- -# Fonctions SQL -# -------------- +# ----------------- +# Utilitaires +# ----------------- +def rom_help() -> str: + return ( + "Format ROM attendu : `{0x28,0xFF,0xAA,0xBB,0xCC,0xDD,0xEE,0x12}` " + "(8 octets en hex). Le premier octet est souvent 0x28 pour DS18B20." + ) +def is_valid_rom(address: str) -> bool: + return bool(ROM_REGEX.match(str(address).strip())) + +def is_valid_hyphen(address_h: str) -> bool: + return bool(HYPHEN_REGEX.match(str(address_h).strip())) + +def rom_to_hyphen(rom: str) -> str: + hexes = re.findall(r"0x([0-9A-Fa-f]{2})", str(rom)) + if len(hexes) != 8: + return "" + return "-".join(h.lower() for h in hexes) + +def hyphen_to_rom(h: str) -> str: + parts = str(h).strip().split("-") + if len(parts) != 8 or not all(re.fullmatch(r"[0-9A-Fa-f]{2}", p) for p in parts): + return "" + return "{" + ",".join(f"0x{p.upper()}" for p in parts) + "}" + +def res_label(bits: int) -> str: + info = RES_MAP.get(bits) + if not info: + return f"{bits} bits (inconnu)" + return f"{bits} bits (±{info['precision']}°C, {info['tconv_ms']} ms)" + +# ----------------- +# Fonctions SQL +# ----------------- def fetch_trackers(where_lieu: str | None = None) -> pd.DataFrame: query = ( - f"SELECT {COL_ID}, {COL_ADDRESS}, {COL_LIEU}, {COL_REPERE}, {COL_MES}, {COL_RESBITS}, {COL_DATE} " + f"SELECT {COL_ID}, {COL_ADDRESS}, {COL_ADDR_HYPHEN}, {COL_LIEU}, " + f"{COL_REPERE}, {COL_MES}, {COL_RESBITS}, {COL_DATE} " f"FROM {TABLE_NAME}" ) params = [] if where_lieu: query += f" WHERE {COL_LIEU} = %s" params.append(where_lieu) - query += f" ORDER BY {COL_LIEU}, {COL_REPERE}, {COL_ADDRESS}" + query += f" ORDER BY {COL_LIEU}, {COL_REPERE}, {COL_ADDR_HYPHEN}, {COL_ADDRESS}" with get_conn() as conn: df = pd.read_sql(query, conn, params=params) return df - -def insert_tracker(address: str, lieu: str, res_bits: int, repere: str | None = None, mise_en_service: date | None = None) -> int: +def insert_tracker(address: str, lieu: str, res_bits: int, + repere: str | None = None, mise_en_service: date | None = None, + address_hyphen: str | None = None) -> int: + addr_rom = (address or "").strip() if address else "" + addr_hyp = (address_hyphen or "").strip() if address_hyphen else "" + if addr_rom and not addr_hyp: + addr_hyp = rom_to_hyphen(addr_rom) + if addr_hyp and not addr_rom: + addr_rom = hyphen_to_rom(addr_hyp) + if not is_valid_rom(addr_rom) or not is_valid_hyphen(addr_hyp): + raise ValueError("Adresse invalide (ROM ou hyphen).") sql = f""" - INSERT INTO {TABLE_NAME} ({COL_ADDRESS}, {COL_LIEU}, {COL_REPERE}, {COL_MES}, {COL_RESBITS}) - VALUES (%s, %s, %s, %s, %s) + INSERT INTO {TABLE_NAME} + ({COL_ADDRESS}, {COL_ADDR_HYPHEN}, {COL_LIEU}, {COL_REPERE}, {COL_MES}, {COL_RESBITS}) + VALUES (%s, %s, %s, %s, %s, %s) """ with get_conn() as conn: cur = conn.cursor() cur.execute(sql, ( - address, + addr_rom, + addr_hyp.lower(), lieu, (repere.strip() if repere and str(repere).strip() else None), mise_en_service, @@ -151,17 +197,27 @@ def insert_tracker(address: str, lieu: str, res_bits: int, repere: str | None = conn.commit() return cur.lastrowid - -def update_tracker(row_id: int, address: str, lieu: str, res_bits: int, repere: str | None, mise_en_service: date | None) -> None: +def update_tracker(row_id: int, address: str, lieu: str, res_bits: int, + repere: str | None, mise_en_service: date | None, + address_hyphen: str | None = None) -> None: + addr_rom = (address or "").strip() + addr_hyp = (address_hyphen or "").strip() if address_hyphen else "" + if addr_rom and not addr_hyp: + addr_hyp = rom_to_hyphen(addr_rom) + if addr_hyp and not addr_rom: + addr_rom = hyphen_to_rom(addr_hyp) + if not is_valid_rom(addr_rom) or not is_valid_hyphen(addr_hyp): + raise ValueError("Adresse invalide (ROM ou hyphen).") sql = f""" UPDATE {TABLE_NAME} - SET {COL_ADDRESS}=%s, {COL_LIEU}=%s, {COL_REPERE}=%s, {COL_MES}=%s, {COL_RESBITS}=%s + SET {COL_ADDRESS}=%s, {COL_ADDR_HYPHEN}=%s, {COL_LIEU}=%s, {COL_REPERE}=%s, {COL_MES}=%s, {COL_RESBITS}=%s WHERE {COL_ID}=%s """ with get_conn() as conn: cur = conn.cursor() cur.execute(sql, ( - address, + addr_rom, + addr_hyp.lower(), lieu, (repere.strip() if repere and str(repere).strip() else None), mise_en_service, @@ -170,7 +226,6 @@ def update_tracker(row_id: int, address: str, lieu: str, res_bits: int, repere: )) conn.commit() - def delete_tracker(row_id: int) -> None: sql = f"DELETE FROM {TABLE_NAME} WHERE {COL_ID}=%s" with get_conn() as conn: @@ -178,51 +233,20 @@ def delete_tracker(row_id: int) -> None: cur.execute(sql, (row_id,)) conn.commit() -# -------------- -# Utilitaires UI -# -------------- - -def rom_help() -> str: - """Message d'aide sur le format des adresses ROM DS18B20.""" - return ( - "Format attendu : `{0x28,0xFF,0xAA,0xBB,0xCC,0xDD,0xEE,0x12}` " - "(8 octets en hex)." - "Le premier octet (famille) est souvent 0x28 pour DS18B20." - ) - -def is_valid_rom(address: str) -> bool: - """Vérifie que l'adresse saisie correspond bien au format attendu.""" - return bool(ROM_REGEX.match(address.strip())) - - -def res_label(bits: int) -> str: - """Retourne un label lisible pour la résolution DS18B20.""" - info = RES_MAP.get(bits) - if not info: - return f"{bits} bits (inconnu)" - return f"{bits} bits (±{info['precision']}°C, {info['tconv_ms']} ms)" - # ================== # Application Streamlit # ================== - st.set_page_config(page_title="Tracker", page_icon="🌡️", layout="wide") - -# 🔐 Exige la connexion avant d'afficher l'app user = require_login() -st.title("🌡️ Gestion du parc sondes en stock ou installées") +st.title("🌡️ Gestion du parc sondes (stock ou installées)") with st.expander("Paramètres de connexion (lecture seule)"): st.write({k: ("***" if k in {"password"} else v) for k, v in DB_CFG.items()}) - st.caption("Configurez ces valeurs via le fichier .env (MYSQL_HOST, MYSQL_DB, MYSQL_USER, MYSQL_PASSWORD, MYSQL_PORT, AUTH_USERS)") + st.caption("Configurez ces valeurs via le fichier .env") -# Barre latérale — Filtres & Actions st.sidebar.header("Filtres & Actions") - -# Info utilisateur connecté st.sidebar.caption(f"Connecté en tant que **{user}**") -# Récupération de la liste des lieux existants _all = fetch_trackers() lieux = sorted([x for x in _all[COL_LIEU].dropna().unique()]) if not _all.empty else [] lieu_selected = st.sidebar.selectbox("Filtrer par lieu", options=["(Tous)"] + lieux, index=0) @@ -231,14 +255,16 @@ lieu_selected = st.sidebar.selectbox("Filtrer par lieu", options=["(Tous)"] + li st.sidebar.subheader("Ajouter une sonde") with st.sidebar.form("add_form", clear_on_submit=True): new_address = st.text_input("Adresse ROM", placeholder="{0x28,0xFF,...}", help=rom_help()) - new_lieu = st.text_input("Lieu d'installation", placeholder="Ex: Chaufferie / Saclay") - new_repere = st.text_input("Repère (optionnel)", placeholder="Ex: R1, Panneau N°, Local 3…") + preview_h = rom_to_hyphen(new_address) if new_address else "" + st.text_input("Adresse hyphen (auto)", value=preview_h, disabled=True) + new_lieu = st.text_input("Lieu d'installation") + new_repere = st.text_input("Repère (optionnel)") new_mes = st.date_input("Mise en service (optionnel)", value=None, format="YYYY-MM-DD") new_res = st.selectbox("Résolution (bits)", options=[9,10,11,12]) submitted = st.form_submit_button("Ajouter") if submitted: if not is_valid_rom(new_address): - st.warning("Adresse ROM invalide. Voir l'aide sur le format.") + st.warning("Adresse ROM invalide.") elif not new_lieu.strip(): st.warning("Lieu requis.") else: @@ -248,25 +274,21 @@ with st.sidebar.form("add_form", clear_on_submit=True): int(new_res), new_repere, new_mes if isinstance(new_mes, date) else None, + address_hyphen=rom_to_hyphen(new_address.strip()), ) st.success(f"Sonde ajoutée (id={rid}).") time.sleep(0.6) st.rerun() -# Bouton de déconnexion (session Streamlit) st.sidebar.divider() if st.sidebar.button("Se déconnecter"): for _k in list(st.session_state.keys()): - try: - del st.session_state[_k] - except Exception: - pass + st.session_state.pop(_k, None) st.success("Déconnecté.") time.sleep(0.3) st.rerun() -# Vue principale (liste / édition) - +# Vue principale if lieu_selected != "(Tous)": df = fetch_trackers(where_lieu=lieu_selected) else: @@ -275,89 +297,46 @@ else: if df.empty: st.info("Aucune sonde enregistrée.") else: - # Colonne lisible pour la résolution df["resolution"] = df[COL_RESBITS].apply(res_label) - st.subheader("Enregistrements") - st.caption("Double-cliquez pour éditer les cellules. *resolution* et *date* sont non éditables.") - edited = st.data_editor( - df[[COL_ID, COL_ADDRESS, COL_LIEU, COL_REPERE, COL_MES, COL_RESBITS, "resolution", COL_DATE]], + df[[COL_ID, COL_ADDRESS, COL_ADDR_HYPHEN, COL_LIEU, COL_REPERE, COL_MES, COL_RESBITS, "resolution", COL_DATE]], hide_index=True, - column_config={ - COL_ID: st.column_config.NumberColumn("ID", disabled=True), - COL_ADDRESS: st.column_config.TextColumn("Adresse (ROM)", help=rom_help()), - COL_LIEU: st.column_config.TextColumn("Lieu"), - COL_REPERE: st.column_config.TextColumn("Repère"), - COL_MES: st.column_config.DateColumn("Mise en service", format="YYYY-MM-DD"), - COL_RESBITS: st.column_config.NumberColumn("Résolution (bits)", min_value=9, max_value=12, step=1), - "resolution": st.column_config.TextColumn("Détails", disabled=True), - COL_DATE: st.column_config.DatetimeColumn("Date insertion", disabled=True, format="YYYY-MM-DD HH:mm:ss"), - }, use_container_width=True, num_rows="dynamic", ) - - # Détections removed_ids = set(df[COL_ID]) - set(edited[COL_ID]) to_update = [] for _, row in edited.iterrows(): orig = df.loc[df[COL_ID] == row[COL_ID]].iloc[0] changed = ( (row[COL_ADDRESS] != orig[COL_ADDRESS]) or + (row[COL_ADDR_HYPHEN] != orig[COL_ADDR_HYPHEN]) or (row[COL_LIEU] != orig[COL_LIEU]) or - ((str(row.get(COL_REPERE) or "").strip()) != (str(orig.get(COL_REPERE) or "").strip())) or - ((str(row.get(COL_MES) or "")[:10]) != (str(orig.get(COL_MES) or "")[:10])) or + (row.get(COL_REPERE) or "") != (orig.get(COL_REPERE) or "") or + (str(row.get(COL_MES) or "")[:10] != str(orig.get(COL_MES) or "")[:10]) or (int(row[COL_RESBITS]) != int(orig[COL_RESBITS])) ) if changed: - # Mise en service : convertir en date ou None mes_val = row.get(COL_MES) if pd.isna(mes_val): mes_val = None - elif isinstance(mes_val, pd.Timestamp): + elif hasattr(mes_val, "date"): mes_val = mes_val.date() - elif isinstance(mes_val, str) and mes_val: - try: - mes_val = pd.to_datetime(mes_val).date() - except Exception: - mes_val = None - to_update.append( - ( - int(row[COL_ID]), - str(row[COL_ADDRESS]), - str(row[COL_LIEU]), - int(row[COL_RESBITS]), - (str(row.get(COL_REPERE)).strip() if row.get(COL_REPERE) and str(row.get(COL_REPERE)).strip() else None), - mes_val, - ) - ) + to_update.append((int(row[COL_ID]), str(row[COL_ADDRESS]), str(row[COL_ADDR_HYPHEN] or ""), + str(row[COL_LIEU]), int(row[COL_RESBITS]), + str(row.get(COL_REPERE) or None), mes_val)) + col1, col2 = st.columns([1,1]) + if st.button("Enregistrer les modifications"): + for rid, addr_rom, addr_hyp, lieu, rbits, repere, mes in to_update: + update_tracker(rid, addr_rom, lieu, rbits, repere, mes, address_hyphen=addr_hyp) + for rid in removed_ids: + delete_tracker(rid) + st.success("Modifications enregistrées ✔️") + time.sleep(0.6) + st.rerun() + if st.button("Annuler"): + st.rerun() - # Validation des adresses modifiées - invalid_ids = [rid for (rid, addr, *_rest) in to_update if not is_valid_rom(addr)] - if invalid_ids: - st.error(f"Adresses ROM invalides pour id: {sorted(invalid_ids)}. Aucune mise à jour effectuée.") - else: - col1, col2, col3 = st.columns([1,1,2]) - with col1: - if st.button("Enregistrer les modifications", disabled=(len(to_update)==0 and len(removed_ids)==0)): - for rid, addr, lieu, rbits, repere, mes in to_update: - update_tracker(rid, addr, lieu, rbits, repere, mes) - for rid in removed_ids: - delete_tracker(int(rid)) - st.success("Modifications enregistrées ✔️") - time.sleep(0.6) - st.rerun() - with col2: - if st.button("Annuler les modifs"): - st.rerun() - with col3: - st.caption(f"À enregistrer : {len(to_update)} mise(s) à jour, {len(removed_ids)} suppression(s)") - -# Pied de page st.divider() -st.caption( - "Astuce : vous pouvez coller directement une adresse ROM depuis vos logs au format {0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..}." - - "Si vos noms de colonnes diffèrent, ajustez les constantes en tête de fichier." -) +st.caption("Astuce : collez une adresse ROM {0x..,...} → la version hyphen est générée automatiquement.") diff --git a/scripts/envoi_sms.php b/scripts/envoi_sms.php deleted file mode 100644 index 78cd443..0000000 --- a/scripts/envoi_sms.php +++ /dev/null @@ -1,32 +0,0 @@ -get('/sms/'); -foreach ($smsServices as $smsService) { - - print_r($smsService); -} - -?> \ No newline at end of file