Add devices module with MQTT client

master
esensar 2018-04-26 14:12:20 +02:00
parent 7cb99cd04f
commit 574cb8bb49
2 changed files with 43 additions and 14 deletions

View File

@ -1,23 +1,18 @@
import atexit
from flask import Flask
from flask_mqtt import Mqtt
from app.mod_devices import setup_mqtt, tear_down_mqtt
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config')
app.config.from_pyfile('config.py')
mqtt = Mqtt(app)
def on_stop():
print('Application stopping')
tear_down_mqtt()
setup_mqtt(app)
atexit.register(on_stop)
@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())

View File

@ -0,0 +1,34 @@
from flask_mqtt import Mqtt
mqtt = Mqtt()
def setup_mqtt(app):
mqtt.init_app(app)
mqtt.client.on_message = handle_mqtt_message
mqtt.client.on_subscribe = handle_subscribe
print('MQTT client initialized')
def tear_down_mqtt():
mqtt.unsubscribe_all()
if hasattr(mqtt, 'client') and mqtt.client is not None:
mqtt.client.disconnect()
print('MQTT client destroyed')
@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
print('MQTT client connected')
mqtt.subscribe('topic/state')
@mqtt.on_disconnect()
def handle_disconnect():
print('MQTT client disconnected')
def handle_subscribe(client, userdata, mid, granted_qos):
print('MQTT client subscribed')
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
print(message.payload.decode())