Skip to content

Instantly share code, notes, and snippets.

@xvzf
Last active April 26, 2020 14:38
Show Gist options
  • Save xvzf/4e87e2b53d24d1d27492d19be2a13330 to your computer and use it in GitHub Desktop.
Save xvzf/4e87e2b53d24d1d27492d19be2a13330 to your computer and use it in GitHub Desktop.
from flask import Flask
from flask_mqtt import Mqtt
def create_app():
app = Flask(__name__)
app.config['MQTT_BROKER_URL'] = 'mosquito.lanarama.local' # use the free broker from HIVEMQ
app.config['MQTT_BROKER_PORT'] = 1883 # default port for non-tls connection
app.config['MQTT_USERNAME'] = '' # set the username here if you need authentication for the broker
app.config['MQTT_PASSWORD'] = '' # set the password here if the broker demands authentication
app.config['MQTT_KEEPALIVE'] = 5 # set the time interval for sending a ping to the broker to 5 seconds
app.config['MQTT_TLS_ENABLED'] = False # set TLS to disabled for testing purposes
app.mqtt_values = {}
mqtt = Mqtt(app)
@mqtt.on_connect()
def handle_mqtt_connect(*args):
# Can be multiple
mqtt.subscribe("topic/to/subscribe/to")
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
app.mqtt_values[message.topic] = float(message.payload.decode())
@app.route("/metrics")
def get_metrics():
buf = ""
for topic, data in app.mqtt_values:
for k, v in data:
# Builds a strink like:
#
# kuehlschrank_temperatur{topic="test"} 22.1
buf += f"{k.replace("/", "_")}{{topic=\"{ topic }\"}} {v}" \n
return buf
return app
if __name__ == "__main__":
app = create_app()
app.run(host="::", port="9080")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment