102 lines
3.1 KiB
Python
Executable File
102 lines
3.1 KiB
Python
Executable File
#!/home/debian/Gestion_sondes/myenv/bin/python3
|
|
|
|
from datetime import datetime, timedelta
|
|
from dotenv import load_dotenv
|
|
import os
|
|
import db_utils
|
|
import logging
|
|
from utils_sms import envoyer_sms
|
|
|
|
# Dossier Logs
|
|
LOG_DIR = '/home/debian/Gestion_sondes/Logs'
|
|
os.makedirs(LOG_DIR, exist_ok=True)
|
|
|
|
# Fichier de log (nommé par date)
|
|
log_filename = os.path.join(LOG_DIR, datetime.now().strftime("surveillance_%Y-%m-%d.log"))
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(levelname)s - %(message)s',
|
|
handlers=[
|
|
logging.FileHandler(log_filename),
|
|
logging.StreamHandler() # Affiche aussi les logs dans la console
|
|
]
|
|
)
|
|
|
|
# Charger .env
|
|
load_dotenv('/home/debian/Gestion_sondes/.env')
|
|
|
|
# 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 = ['Saclay', 'Meudon', 'Chaufferie']
|
|
DELAI_MINUTES = 15
|
|
RAPPEL_HEURES = 6
|
|
|
|
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 main():
|
|
cnx = db_utils.connect_to_mysql() # ← appel via db_utils
|
|
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:
|
|
logging.info(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)
|
|
logging.info(f"📩 SMS de retour à la normale envoyé pour {table}.")
|
|
else:
|
|
logging.info(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:
|
|
logging.info("👍 Tout est OK, aucun SMS envoyé.")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|