61 lines
1.6 KiB
Python
61 lines
1.6 KiB
Python
|
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
|
||
|
from node_api import NodeAPI
|
||
|
|
||
|
client_id = "exporter"
|
||
|
topics = [
|
||
|
("$SYS/broker/clients/connected", 0),
|
||
|
("$CONNECTED/#", 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')
|
||
|
|
||
|
def on_connect(client, userdata, flags, rc):
|
||
|
print("Connected with result code " + str(rc))
|
||
|
|
||
|
client.subscribe(topics)
|
||
|
if rc==0:
|
||
|
client.connected_flag=True
|
||
|
client.publish("$CONNECTED/"+client_id, 1, retain=True)
|
||
|
else:
|
||
|
client.bad_connection_flag=True
|
||
|
|
||
|
|
||
|
#def on_disconnect(client, userdata, rc):
|
||
|
# client.publish(connection_topic,0,retain=True)
|
||
|
|
||
|
def on_message(client, userdata, msg):
|
||
|
topic = msg.topic.split('/')
|
||
|
|
||
|
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":
|
||
|
MQTT_BROKER_CLIENTS.set(int(msg.payload))
|
||
|
|
||
|
print(msg.topic, int(msg.payload))
|
||
|
|
||
|
|
||
|
client = mqtt.Client(client_id)
|
||
|
|
||
|
client.on_connect = on_connect
|
||
|
#client.on_disconnect = on_disconnect
|
||
|
client.on_message = on_message
|
||
|
client.will_set("$CONNECTED/"+client_id, 0, qos=0, retain=True)
|
||
|
client.connect('localhost')
|
||
|
client.loop_start()
|
||
|
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
# Start up the server to expose the metrics.
|
||
|
start_http_server(8000)
|
||
|
|
||
|
while True:
|
||
|
time.sleep(1)
|