Refactor MQTT topic structure in sensor_bridge.py to adopt a nested format for temperature, humidity, and CO2 data. Updated publishing methods to reflect the new tree structure, enhancing data organization and clarity in sensor reporting.

This commit is contained in:
Naab2k3
2025-06-24 11:32:38 +07:00
parent e83f614182
commit 8dc518ce28

View File

@ -77,15 +77,15 @@ def read_and_publish_temperature_humidity(mqtt_client, modbus_client, host_info)
humidity = raw_hum * 100 / 1000 humidity = raw_hum * 100 / 1000
logging.info(f"Humidity from {host_info['ip']}: {humidity:.1f}%RH") logging.info(f"Humidity from {host_info['ip']}: {humidity:.1f}%RH")
# Publish data # Publish data in new tree structure
location = host_info["location"] location = host_info["location"]
current_time = datetime.now(LOCAL_TIMEZONE).strftime("%Y-%m-%d %H:%M:%S") current_time = datetime.now(LOCAL_TIMEZONE).strftime("%Y-%m-%d %H:%M:%S")
base_topic = f"Location/{location}" base_topic = f"Location/{location}"
topics_data = [ topics_data = [
(f"{base_topic}/Time", current_time), (f"{base_topic}/Time", current_time),
(f"{base_topic}/Status", "online"), (f"{base_topic}/Status", "online"),
(f"{base_topic}/Temperature", round(temperature, 1)), (f"{base_topic}/Temperature/temperature_value", round(temperature, 1)),
(f"{base_topic}/Humidity", round(humidity, 1)) (f"{base_topic}/Humidity/humidity_value", round(humidity, 1)),
] ]
all_published = True all_published = True
@ -136,16 +136,16 @@ def read_and_publish_cwt_co2(mqtt_client, modbus_client, host_info):
logging.info(f"CWT from {host_info['ip']} - Temp: {temperature:.1f}°C, Humidity: {humidity:.1f}%RH, CO2: {co2_ppm}ppm") logging.info(f"CWT from {host_info['ip']} - Temp: {temperature:.1f}°C, Humidity: {humidity:.1f}%RH, CO2: {co2_ppm}ppm")
# Publish data # Publish data in new tree structure
location = host_info["location"] location = host_info["location"]
current_time = datetime.now(LOCAL_TIMEZONE).strftime("%Y-%m-%d %H:%M:%S") current_time = datetime.now(LOCAL_TIMEZONE).strftime("%Y-%m-%d %H:%M:%S")
base_topic = f"Location/{location}" base_topic = f"Location/{location}"
topics_data = [ topics_data = [
(f"{base_topic}/Time", current_time), (f"{base_topic}/Time", current_time),
(f"{base_topic}/Status", "online"), (f"{base_topic}/Status", "online"),
(f"{base_topic}/Temperature", round(temperature, 1)), (f"{base_topic}/Temperature/temperature_value", round(temperature, 1)),
(f"{base_topic}/Humidity", round(humidity, 1)), (f"{base_topic}/Humidity/humidity_value", round(humidity, 1)),
(f"{base_topic}/CO2", co2_ppm) (f"{base_topic}/CO2/CO2_value", co2_ppm),
] ]
all_published = True all_published = True