#!/home/debian/Gestion_sondes/myenv/bin/python3 import mysql.connector from datetime import datetime, timedelta from dotenv import load_dotenv import os import ovh # Charger .env load_dotenv('/home/debian/Gestion_sondes/.env') # MySQL MYSQL_HOST = os.getenv('DB_HOST') MYSQL_USER = os.getenv('DB_USER') MYSQL_PASSWORD = os.getenv('DB_PASSWORD') MYSQL_DB = os.getenv('DB_NAME') # OVH SMS APP_KEY = os.getenv('OVH_APP_KEY') APP_SECRET = os.getenv('OVH_APP_SECRET') CONSUMER_KEY = os.getenv('OVH_CONSUMER_KEY') SERVICE_NAME = os.getenv('OVH_SERVICE_NAME') SMS_RECEIVER = os.getenv('SMS_RECEIVER') SMS_SENDER = os.getenv('OVH_SMS_SENDER') # Tables à surveiller tables = ['Saclay', 'Meudon'] # ajoute tes sites ici # seuils DELAI_MINUTES = 15 RAPPEL_HEURES = 6 # Dossier pour mémoriser les états STATE_DIR = '/tmp/surveillance_states' os.makedirs(STATE_DIR, exist_ok=True) def should_send_alert(site): state_file = os.path.join(STATE_DIR, f'{site}.state') now = datetime.now() if not os.path.exists(state_file): with open(state_file, 'w') as f: f.write(now.isoformat()) return True with open(state_file, 'r') as f: last_alert = datetime.fromisoformat(f.read().strip()) if now - last_alert >= timedelta(hours=RAPPEL_HEURES): with open(state_file, 'w') as f: f.write(now.isoformat()) return True return False def clear_state(site): state_file = os.path.join(STATE_DIR, f'{site}.state') if os.path.exists(state_file): os.remove(state_file) def envoyer_sms(message): client = ovh.Client( endpoint='ovh-eu', application_key=APP_KEY, application_secret=APP_SECRET, consumer_key=CONSUMER_KEY, ) result = client.post(f'/sms/{SERVICE_NAME}/jobs', receivers=[SMS_RECEIVER], message=message, priority='high', sender=SMS_SENDER ) print("🚨 SMS envoyé :", result) def main(): cnx = mysql.connector.connect( host=MYSQL_HOST, user=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DB ) cursor = cnx.cursor() now = datetime.now() limite = now - timedelta(minutes=DELAI_MINUTES) problemes = [] for table in tables: cursor.execute(f"SELECT MAX(Date) FROM {table}") result = cursor.fetchone() last_update = result[0] if not last_update or last_update < limite: if should_send_alert(table): problemes.append(f"{table} (dernier relevé : {last_update})") else: print(f"⏳ Problème déjà signalé pour {table}, attente du délai de rappel.") else: if os.path.exists(os.path.join(STATE_DIR, f'{table}.state')): message = f"✅ {table} : relevés à nouveau reçus. Situation normale." envoyer_sms(message) clear_state(table) print(f"📩 SMS de retour à la normale envoyé pour {table}.") else: print(f"✅ {table} OK (dernier relevé : {last_update})") cursor.close() cnx.close() if problemes: message = "⚠️ ALERTE : pas de relevés depuis >15min :\n" + "\n".join(problemes) envoyer_sms(message) else: print("👍 Tout est OK, aucun SMS envoyé.") if __name__ == "__main__": main()