Refactor sensor data publishing and health check server configuration. Updated MQTT topic structure for individual data points, improved error handling, and added garbage collection to manage memory. Enhanced logging for health check server accessibility and sensor status updates.
This commit is contained in:
@ -166,24 +166,26 @@ class SensorTracker:
|
||||
else:
|
||||
sensor_type = "temperature-humidity"
|
||||
|
||||
# Create topic for offline status using new structure: Location/{location_name}/{sensor_type}/data
|
||||
data_topic = f"Location/{location}/{sensor_type}/data"
|
||||
# Create base topic path
|
||||
base_topic = f"Location/{location}/{sensor_type}"
|
||||
current_time = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# Create JSON payload with offline status
|
||||
payload = {
|
||||
"timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"location": location,
|
||||
"sensor_type": sensor_type,
|
||||
"ip": host_info["ip"],
|
||||
"status": "offline",
|
||||
"error": sensor.get("last_error", "Unknown error"),
|
||||
"consecutive_failures": sensor["consecutive_failures"],
|
||||
"uptime_percentage": round(sensor["uptime_percentage"], 2)
|
||||
}
|
||||
# Publish offline status to individual topics
|
||||
topics_data = [
|
||||
(f"{base_topic}/Time", current_time),
|
||||
(f"{base_topic}/Status", "offline")
|
||||
]
|
||||
|
||||
result = mqtt_client.publish(data_topic, json.dumps(payload))
|
||||
result.wait_for_publish()
|
||||
logging.info(f"Published offline status to '{data_topic}'")
|
||||
# Publish offline status
|
||||
for topic, value in topics_data:
|
||||
try:
|
||||
payload = str(value)
|
||||
result = mqtt_client.publish(topic, payload)
|
||||
result.wait_for_publish()
|
||||
logging.info(f"Published offline status to '{topic}': {payload}")
|
||||
except Exception as e:
|
||||
logging.error(f"Error publishing offline status to '{topic}': {e}")
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to publish offline status: {e}")
|
||||
|
||||
|
Reference in New Issue
Block a user