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.

This commit is contained in:
Naab2k3
2025-06-24 13:23:09 +07:00
parent 6824f81290
commit 7ce3ff2d5b

View File

@ -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: