50 lines
1.8 KiB
Python
50 lines
1.8 KiB
Python
import argparse
|
|
import paho.mqtt.client as mqtt_client
|
|
from dotenv import load_dotenv
|
|
import logging
|
|
|
|
from logger_config import setup_logger
|
|
from db_utils import connect_to_mysql
|
|
from functools import partial
|
|
|
|
def on_message(table_sql, _client, _userdata, msg):
|
|
try:
|
|
logging.info(f"Message reçu sur {msg.topic}: {msg.payload.decode()}")
|
|
cursor = mydb.cursor()
|
|
sonde_name = '/'.join(msg.topic.split('/')[1:])
|
|
sql = f"INSERT INTO {table_sql} (Sonde, Temperature) VALUES (%s, %s)"
|
|
val = (sonde_name, msg.payload.decode())
|
|
cursor.execute(sql, val)
|
|
mydb.commit()
|
|
logging.info(f"Insertion réussie : {val}")
|
|
except Exception as e:
|
|
logging.error(f"Erreur lors de l'insertion du message : {e}")
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--log", required=True, help="Nom du fichier de log")
|
|
parser.add_argument("--table", required=True, help="Nom complet de la table SQL")
|
|
parser.add_argument("--topic", required=True, help="Topic MQTT à écouter")
|
|
args = parser.parse_args()
|
|
|
|
# 📋 Initialiser le logger
|
|
setup_logger(args.log)
|
|
|
|
# 🔑 Charger les variables d'environnement
|
|
load_dotenv()
|
|
|
|
# 🔌 Connexion MySQL
|
|
mydb = connect_to_mysql()
|
|
|
|
# 📡 Connexion MQTT
|
|
try:
|
|
client = mqtt_client.Client()
|
|
client.username_pw_set("Bwps", "scJ5ACj2keRfI^")
|
|
client.on_message = partial(on_message, args.table)
|
|
client.connect("54.36.188.119", 1883, 60)
|
|
client.subscribe(args.topic)
|
|
logging.info(f"Connexion MQTT réussie et abonnement au topic '{args.topic}'.")
|
|
client.loop_forever()
|
|
except Exception as err:
|
|
logging.error(f"Erreur MQTT : {err}")
|