From 3f6229e1f7b59357c9e7da9bf37028fc47fd8552 Mon Sep 17 00:00:00 2001 From: ferdzo Date: Thu, 29 Aug 2024 23:55:56 +0200 Subject: [PATCH] Finally fixed. --- iotDashboard/mqtt_service.py | 80 +++++++++++++++++------------------- 1 file changed, 38 insertions(+), 42 deletions(-) diff --git a/iotDashboard/mqtt_service.py b/iotDashboard/mqtt_service.py index 72e1db1..3e30db7 100644 --- a/iotDashboard/mqtt_service.py +++ b/iotDashboard/mqtt_service.py @@ -1,72 +1,67 @@ import json +import time import os from datetime import datetime import paho.mqtt.client as mqtt import redis -import time from dotenv import load_dotenv load_dotenv() -# Initialize Redis client -redis_host = os.getenv('REDIS_HOST') -redis_client = redis.StrictRedis(host=redis_host, port=6379, db=0) -# MQTT Broker settings +REDIS_HOST = os.getenv('REDIS_HOST', 'localhost') +redis_client = redis.StrictRedis(host=REDIS_HOST, port=6379, db=0) + +print("Connected to Redis Server") + MQTT_BROKER = os.getenv('MQTT_BROKER') +mqtt_data = {} + + def get_devices(): - """Fetch devices from Redis.""" + """" Simple method to get all devices """ + # Get devices from Redis devices_json = redis_client.get('devices') if devices_json: return json.loads(devices_json) return [] + def on_message(client, userdata, msg): - """Callback function to handle MQTT messages.""" - topic_parts = msg.topic.split('/') - device_name = topic_parts[0] - sensor_type = topic_parts[-2] + """" Simple method to handle messages """ + topic = msg.topic.split('/') + device_name = topic[0] + sensor = topic[-2] - # Retrieve and decode message payload - payload = float(msg.payload.decode()) + if device_name not in mqtt_data: + mqtt_data[device_name] = {"time": datetime.now(), + "device": device_name, + "temperature": None, + "humidity": None} - # Retrieve current device data from Redis or initialize - device_data_json = redis_client.get(device_name) - if device_data_json: - device_data = json.loads(device_data_json) - else: - device_data = { - "time": datetime.now().isoformat(), - "device": device_name, - "temperature": None, - "humidity": None - } + if sensor == "tempreature": + mqtt_data[device_name]["temperature"] = float(msg.payload.decode()) + elif sensor == "humidity": + mqtt_data[device_name]["humidity"] = float(msg.payload.decode()) - # Update device data based on sensor type - if sensor_type == "temperature": - device_data["temperature"] = payload - elif sensor_type == "humidity": - device_data["humidity"] = payload - - # Update time and save to Redis - device_data["time"] = datetime.now().isoformat() - redis_client.set(device_name, json.dumps(device_data)) - print(f"Updated data for {device_name}: {device_data}") + mqtt_data[device_name]["time"] = str(datetime.now()) + redis_client.set(device_name, json.dumps(mqtt_data)) + # Update time on receiving each message + print(mqtt_data) def start_mqtt_client(): - """Initialize and start the MQTT client.""" - client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1) + """ Start the MQTT client """ + devices = get_devices() + + client = mqtt.Client() client.on_message = on_message client.connect(MQTT_BROKER) - - # Fetch and subscribe to device topics - devices = get_devices() + client.loop_start() + print("MQTT Client Started") for device in devices: client.subscribe(f"{device['name']}/sensor/+/state") - client.loop_start() - print("MQTT Client Started") - + # Keep the script running try: while True: time.sleep(10) # Sleep to prevent high CPU usage @@ -75,5 +70,6 @@ def start_mqtt_client(): finally: client.loop_stop() # Stop the loop when exiting + if __name__ == "__main__": - start_mqtt_client() + start_mqtt_client() \ No newline at end of file