Finally fixed.

This commit is contained in:
ferdzo
2024-08-29 23:55:56 +02:00
parent 4c7e1a50f3
commit 3f6229e1f7

View File

@@ -1,72 +1,67 @@
import json import json
import time
import os import os
from datetime import datetime from datetime import datetime
import paho.mqtt.client as mqtt import paho.mqtt.client as mqtt
import redis import redis
import time
from dotenv import load_dotenv from dotenv import load_dotenv
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_BROKER = os.getenv('MQTT_BROKER')
mqtt_data = {}
def get_devices(): def get_devices():
"""Fetch devices from Redis.""" """" Simple method to get all devices """
# Get devices from Redis
devices_json = redis_client.get('devices') devices_json = redis_client.get('devices')
if devices_json: if devices_json:
return json.loads(devices_json) return json.loads(devices_json)
return [] return []
def on_message(client, userdata, msg): def on_message(client, userdata, msg):
"""Callback function to handle MQTT messages.""" """" Simple method to handle messages """
topic_parts = msg.topic.split('/') topic = msg.topic.split('/')
device_name = topic_parts[0] device_name = topic[0]
sensor_type = topic_parts[-2] sensor = topic[-2]
# Retrieve and decode message payload if device_name not in mqtt_data:
payload = float(msg.payload.decode()) mqtt_data[device_name] = {"time": datetime.now(),
# 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, "device": device_name,
"temperature": None, "temperature": None,
"humidity": None "humidity": None}
}
# Update device data based on sensor type if sensor == "tempreature":
if sensor_type == "temperature": mqtt_data[device_name]["temperature"] = float(msg.payload.decode())
device_data["temperature"] = payload elif sensor == "humidity":
elif sensor_type == "humidity": mqtt_data[device_name]["humidity"] = float(msg.payload.decode())
device_data["humidity"] = payload
# Update time and save to Redis mqtt_data[device_name]["time"] = str(datetime.now())
device_data["time"] = datetime.now().isoformat() redis_client.set(device_name, json.dumps(mqtt_data))
redis_client.set(device_name, json.dumps(device_data)) # Update time on receiving each message
print(f"Updated data for {device_name}: {device_data}") print(mqtt_data)
def start_mqtt_client(): def start_mqtt_client():
"""Initialize and start the MQTT client.""" """ Start the MQTT client """
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1) devices = get_devices()
client = mqtt.Client()
client.on_message = on_message client.on_message = on_message
client.connect(MQTT_BROKER) client.connect(MQTT_BROKER)
client.loop_start()
# Fetch and subscribe to device topics print("MQTT Client Started")
devices = get_devices()
for device in devices: for device in devices:
client.subscribe(f"{device['name']}/sensor/+/state") client.subscribe(f"{device['name']}/sensor/+/state")
client.loop_start() # Keep the script running
print("MQTT Client Started")
try: try:
while True: while True:
time.sleep(10) # Sleep to prevent high CPU usage time.sleep(10) # Sleep to prevent high CPU usage
@@ -75,5 +70,6 @@ def start_mqtt_client():
finally: finally:
client.loop_stop() # Stop the loop when exiting client.loop_stop() # Stop the loop when exiting
if __name__ == "__main__": if __name__ == "__main__":
start_mqtt_client() start_mqtt_client()