mirror of
https://github.com/ferdzo/iotDashboard.git
synced 2026-04-05 01:06:24 +00:00
Finally fixed.
This commit is contained in:
@@ -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(),
|
||||||
|
"device": device_name,
|
||||||
|
"temperature": None,
|
||||||
|
"humidity": None}
|
||||||
|
|
||||||
# Retrieve current device data from Redis or initialize
|
if sensor == "tempreature":
|
||||||
device_data_json = redis_client.get(device_name)
|
mqtt_data[device_name]["temperature"] = float(msg.payload.decode())
|
||||||
if device_data_json:
|
elif sensor == "humidity":
|
||||||
device_data = json.loads(device_data_json)
|
mqtt_data[device_name]["humidity"] = float(msg.payload.decode())
|
||||||
else:
|
|
||||||
device_data = {
|
|
||||||
"time": datetime.now().isoformat(),
|
|
||||||
"device": device_name,
|
|
||||||
"temperature": None,
|
|
||||||
"humidity": None
|
|
||||||
}
|
|
||||||
|
|
||||||
# Update device data based on sensor type
|
mqtt_data[device_name]["time"] = str(datetime.now())
|
||||||
if sensor_type == "temperature":
|
redis_client.set(device_name, json.dumps(mqtt_data))
|
||||||
device_data["temperature"] = payload
|
# Update time on receiving each message
|
||||||
elif sensor_type == "humidity":
|
print(mqtt_data)
|
||||||
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}")
|
|
||||||
|
|
||||||
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()
|
||||||
Reference in New Issue
Block a user