From 3b812d49a9e65f9542cb51433e099fbbf9adfc3c Mon Sep 17 00:00:00 2001 From: esensar Date: Wed, 25 Apr 2018 15:51:28 +0200 Subject: [PATCH] Embed simple MQTT client in the application --- .gitignore | 3 +++ config.py | 5 +++++ hello.py | 19 ++++++++++++++++++- 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 config.py diff --git a/.gitignore b/.gitignore index af32b5d..cfb34f5 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,6 @@ pip-log.txt venv *.pyc build + +# Instance dir +instance/ diff --git a/config.py b/config.py new file mode 100644 index 0000000..fffa429 --- /dev/null +++ b/config.py @@ -0,0 +1,5 @@ +MQTT_BROKER_URL = 'mybroker.com' +MQTT_BROKER_PORT = 1883 +MQTT_USERNAME = 'user' +MQTT_PASSWORD = 'secret' +MQTT_REFRESH_TIME = 1.0 # refresh time in seconds diff --git a/hello.py b/hello.py index bbf7e46..767329b 100644 --- a/hello.py +++ b/hello.py @@ -1,6 +1,23 @@ from flask import Flask -app = Flask(__name__) +from flask_mqtt import Mqtt + +app = Flask(__name__, instance_relative_config=True) +app.config.from_object('config') +app.config.from_pyfile('config.py') +mqtt = Mqtt(app) @app.route("/") def hello(): return "Hello World!" + +@mqtt.on_connect() +def handle_connect(client, userdata, flags, rc): + mqtt.subscribe('topic/state') + +@mqtt.on_message() +def handle_mqtt_message(client, userdata, message): + data = dict( + topic=message.topic, + payload=message.payload.decode() + ) + print(message.payload.decode())