From 157905283ebd2341a23b6ac4922e4959e61db48f Mon Sep 17 00:00:00 2001 From: Thomas Jensen Date: Sat, 20 Jul 2019 22:13:07 +0200 Subject: [PATCH] add statuses and alerts --- exporter.py | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/exporter.py b/exporter.py index 6b59199..4cb6610 100644 --- a/exporter.py +++ b/exporter.py @@ -1,20 +1,25 @@ from prometheus_client import start_http_server, Summary, Gauge -import paho.mqtt.publish as publish import paho.mqtt.client as mqtt -import random -import time +import time, json, re from node_api import NodeAPI client_id = "exporter" topics = [ ("$SYS/broker/clients/connected", 0), - ("$CONNECTED/#", 0) + ("$CONNECTED/#", 0), + ("+/alert", 0), + ("homelab/ats/supply/+", 0) ] node_api = NodeAPI() MQTT_CONNECTED = Gauge('mqtt_node_connected', 'MQTT node connection status', ['node', 'description']) MQTT_BROKER_CLIENTS = Gauge('mqtt_broker_clients', 'MQTT broker clients connected') +MQTT_ALERT = Gauge('mqtt_alert_state', 'MQTT alert topic states', ['origin', 'alert']) +MQTT_STATUS = Gauge('mqtt_status', 'MQTT status topic', ['status']) + +def on_log(client, userdata, level, buff): + print(buff) def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) @@ -36,17 +41,28 @@ def on_message(client, userdata, msg): if topic[0] == "$CONNECTED": MQTT_CONNECTED.labels(topic[1], node_api.get(topic[1])).set(int(msg.payload)) - if msg.topic == "$SYS/broker/clients/connected": + elif msg.topic == "$SYS/broker/clients/connected": MQTT_BROKER_CLIENTS.set(int(msg.payload)) - print(msg.topic, int(msg.payload)) + elif topic[1] == "alert": + for alert, state in json.loads(msg.payload).items(): + MQTT_ALERT.labels(topic[0], alert).set(int(state)) + elif re.match("homelab/ats/supply/src[12]", msg.topic): + MQTT_STATUS.labels('ats_preferred_' + topic[3]).set(json.loads(msg.payload)['preferred']) + + try: + my_json = json.loads(msg.payload) + print(msg.topic, json.dumps(my_json, indent=4, sort_keys=True)) + except ValueError as e: + print(msg.topic, msg.payload) client = mqtt.Client(client_id) client.on_connect = on_connect #client.on_disconnect = on_disconnect client.on_message = on_message +#client.on_log = on_log client.will_set("$CONNECTED/"+client_id, 0, qos=0, retain=True) client.connect('localhost') client.loop_start()