55 lines
1.7 KiB
Python
55 lines
1.7 KiB
Python
import paho.mqtt.client as mqtt
|
|
import pymysql
|
|
import json
|
|
from config import Config
|
|
|
|
def get_db():
|
|
return pymysql.connect(
|
|
host=Config.MYSQL_HOST,
|
|
user=Config.MYSQL_USER,
|
|
password=Config.MYSQL_PASSWORD,
|
|
database=Config.MYSQL_DB,
|
|
cursorclass=pymysql.cursors.DictCursor
|
|
)
|
|
|
|
def on_connect(client, userdata, flags, rc):
|
|
print(f"Connecté au broker MQTT avec le code : {rc}")
|
|
client.subscribe(Config.MQTT_TOPIC_CLIMATE)
|
|
client.subscribe(Config.MQTT_TOPIC_SECURITY)
|
|
|
|
def on_message(client, userdata, msg):
|
|
topic = msg.topic
|
|
payload = json.loads(msg.payload.decode())
|
|
db = get_db()
|
|
cursor = db.cursor()
|
|
|
|
try:
|
|
if topic == Config.MQTT_TOPIC_CLIMATE:
|
|
cursor.execute(
|
|
"INSERT INTO climate_data (temperature, humidity, pressure, luminosity) VALUES (%s, %s, %s, %s)",
|
|
(payload.get('temperature'), payload.get('humidity'), payload.get('pressure'), payload.get('luminosity'))
|
|
)
|
|
print(f"Donnée climatique insérée : {payload}")
|
|
|
|
elif topic == Config.MQTT_TOPIC_SECURITY:
|
|
cursor.execute(
|
|
"INSERT INTO security_events (event_type, location) VALUES (%s, %s)",
|
|
(payload.get('event_type'), payload.get('location'))
|
|
)
|
|
print(f"Événement sécurité inséré : {payload}")
|
|
|
|
db.commit()
|
|
except Exception as e:
|
|
print(f"Erreur lors de l'insertion : {e}")
|
|
finally:
|
|
db.close()
|
|
|
|
def start_mqtt():
|
|
client = mqtt.Client()
|
|
client.on_connect = on_connect
|
|
client.on_message = on_message
|
|
client.connect(Config.MQTT_BROKER, Config.MQTT_PORT, 60)
|
|
client.loop_forever()
|
|
|
|
if __name__ == '__main__':
|
|
start_mqtt() |