# HG changeset patch # User Dennis Fink # Date 2020-02-24 18:58:23 # Node ID 5229d5941a1b25191909fa0b467c5106f633a5de # Parent d2da7d83904ca76a563f01d2989f936175694f0c Simplified sensor handling diff --git a/mqtt2prometheus.py b/mqtt2prometheus.py --- a/mqtt2prometheus.py +++ b/mqtt2prometheus.py @@ -51,27 +51,19 @@ energy_consumption = Gauge( ) -TOPIC_TO_HANDLER = { - "availability/#": handle_availability, - "space/status": handle_space_status, - "space/member_count": handle_member_count, - "sensors/people_now_present": handle_people_now_present, - "sensors/temperature/#": handle_temperature, - "sensors/humidity/#": handle_humidity, - "sensors/barometer/#": handle_barometer, - "sensors/power_consumption/#": handle_power_consumption, - "sensors/co2_emission/#": handle_co2_emission, - "sensors/energy_consumption/#": handle_energy_consumption, -} - - def on_connect(client, userdata, flags, rc): client.publish("availability/mqtt2prometheus", "online", 2, True) - for topic, handler in TOPIC_TO_HANDLER: + topics_handler = { + "availability/#": handle_availability, + "space/status": handle_space_status, + "space/member_count": handle_member_count, + "sensors/people_now_present": handle_people_now_present, + "sensors/#": handle_sensors, + } + + for topic, handler in topics_handler.items(): client.message_callback_add(topic, handler) - - for topic in ["availability/#", "space/status", "space/member_count", "sensors/#"]: client.subscribe(topic) @@ -100,58 +92,17 @@ def handle_availability(client, userdata availability.labels(c).set(v) -def handle_temperature(client, userdata, msg): - t = msg.topic.split("/") - location = "-".join(t[2:]) - try: - temperature.labels(location).set(float(msg.payload)) - except: - pass - - -def handle_humidity(client, userdata, msg): - t = msg.topic.split("/") - location = "-".join(t[2:]) - try: - humidity.labels(location).set(float(msg.payload)) - except: - pass - - -def handle_barometer(client, userdata, msg): - t = msg.topic.split("/") +def handle_sensor(client, userdata, msg): + t = msg.topic_split("/") location = "-".join(t[2:]) - try: - barometer.labels(location).set(float(msg.payload)) - except: - pass - - -def handle_power_consumption(client, userdata, msg): - t = msg.topic.split("/") - location = "-".join(t[2:]) - try: - power_consumption.labels(location).set(float(msg.payload)) - except: - pass - - -def handle_co2_emission(client, userdata, msg): - t = msg.topic.split("/") - location = "-".join(t[2:]) - try: - co2_emission.labels(location).set(float(msg.payload)) - except: - pass - - -def handle_energy_consumption(client, userdata, msg): - t = msg.topic.split("/") - location = "-".join(t[2:]) - try: - energy_consumption.labels(location).set(float(msg.payload)) - except: - pass + if t[1] == "people_now_present": + return + metric = globals().get(t[1], None) + if metric is not None: + try: + metric.labels(location).set(float(msg.payload)) + except: + pass def main():