From 7ce3ff2d5b9612021eb6ef56aa5786138d23b919 Mon Sep 17 00:00:00 2001 From: Naab2k3 Date: Tue, 24 Jun 2025 13:23:09 +0700 Subject: [PATCH] Refactor MQTT alert topic structure in sensor_tracker.py to simplify the format by removing sensor type differentiation. Updated offline status publishing to align with the new topic structure, ensuring consistency across sensor types and enhancing clarity in data representation. --- sensor_tracker.py | 39 ++++++++++++++------------------------- 1 file changed, 14 insertions(+), 25 deletions(-) diff --git a/sensor_tracker.py b/sensor_tracker.py index 0a33425..66fef96 100644 --- a/sensor_tracker.py +++ b/sensor_tracker.py @@ -96,14 +96,8 @@ class SensorTracker: if not mqtt_client or not ALERTING_ENABLED: return - # Determine sensor type for topic structure - if sensor["type"] == "cwt_co2": - sensor_type = "CO2-gas" - else: - sensor_type = "temperature-humidity" - - # Create alert topic using new structure: Location/{location_name}/{sensor_type}/alerts - alert_topic = f"Location/{sensor['location']}/{sensor_type}/alerts" + # Create alert topic using new structure: Location/{location_name}/alerts + alert_topic = f"Location/{sensor['location']}/alerts" alert_message = { "alert_type": "sensor_failure", @@ -129,14 +123,8 @@ class SensorTracker: if not mqtt_client or not ALERTING_ENABLED: return - # Determine sensor type for topic structure - if sensor["type"] == "cwt_co2": - sensor_type = "CO2-gas" - else: - sensor_type = "temperature-humidity" - - # Create alert topic using new structure: Location/{location_name}/{sensor_type}/alerts - alert_topic = f"Location/{sensor['location']}/{sensor_type}/alerts" + # Create alert topic using new structure: Location/{location_name}/alerts + alert_topic = f"Location/{sensor['location']}/alerts" alert_message = { "alert_type": "sensor_recovery", @@ -160,22 +148,23 @@ class SensorTracker: """Publish offline status using new topic structure""" try: location = host_info["location"] - # Determine sensor type based on host_info type - if host_info["type"] == "cwt_co2": - sensor_type = "CO2-gas" - else: - sensor_type = "temperature-humidity" - # Create base topic path - base_topic = f"Location/{location}/{sensor_type}" + # Create base topic path - same structure as online sensors + base_topic = f"Location/{location}" current_time = datetime.now(LOCAL_TIMEZONE).strftime("%Y-%m-%d %H:%M:%S") - # Publish offline status to individual topics + # Publish offline status to match online sensor structure topics_data = [ (f"{base_topic}/Time", current_time), - (f"{base_topic}/Status", "offline") + (f"{base_topic}/Status", "offline"), + (f"{base_topic}/Temperature/temperature", "offline"), + (f"{base_topic}/Humidity/humidity", "offline") ] + # Add CO2 topic for CO2 sensors + if host_info["type"] == "cwt_co2": + topics_data.append((f"{base_topic}/CO2/CO2", "offline")) + # Publish offline status for topic, value in topics_data: try: