2018-04-26 14:45:28 +00:00
|
|
|
import atexit
|
|
|
|
from flask import Blueprint
|
2018-04-26 12:12:20 +00:00
|
|
|
from flask_mqtt import Mqtt
|
|
|
|
|
2018-04-26 14:45:28 +00:00
|
|
|
devices = Blueprint('devices', __name__)
|
2018-04-26 12:12:20 +00:00
|
|
|
mqtt = Mqtt()
|
|
|
|
|
2018-04-26 14:45:28 +00:00
|
|
|
def on_stop():
|
|
|
|
tear_down_mqtt()
|
2018-04-26 13:03:38 +00:00
|
|
|
|
2018-04-26 14:45:28 +00:00
|
|
|
atexit.register(on_stop)
|
|
|
|
|
|
|
|
@devices.route("/")
|
|
|
|
def hello():
|
|
|
|
return "Hello from devices!"
|
|
|
|
|
|
|
|
|
|
|
|
@devices.record
|
|
|
|
def setup_mqtt(setup_state):
|
|
|
|
mqtt.init_app(setup_state.app)
|
2018-04-26 12:12:20 +00:00
|
|
|
mqtt.client.on_message = handle_mqtt_message
|
|
|
|
mqtt.client.on_subscribe = handle_subscribe
|
|
|
|
print('MQTT client initialized')
|
|
|
|
|
2018-04-26 13:03:38 +00:00
|
|
|
|
2018-04-26 12:12:20 +00:00
|
|
|
def tear_down_mqtt():
|
|
|
|
mqtt.unsubscribe_all()
|
|
|
|
if hasattr(mqtt, 'client') and mqtt.client is not None:
|
|
|
|
mqtt.client.disconnect()
|
|
|
|
print('MQTT client destroyed')
|
|
|
|
|
2018-04-26 13:03:38 +00:00
|
|
|
|
2018-04-26 12:12:20 +00:00
|
|
|
@mqtt.on_connect()
|
|
|
|
def handle_connect(client, userdata, flags, rc):
|
|
|
|
print('MQTT client connected')
|
|
|
|
mqtt.subscribe('topic/state')
|
|
|
|
|
2018-04-26 13:03:38 +00:00
|
|
|
|
2018-04-26 12:12:20 +00:00
|
|
|
@mqtt.on_disconnect()
|
|
|
|
def handle_disconnect():
|
|
|
|
print('MQTT client disconnected')
|
|
|
|
|
2018-04-26 13:03:38 +00:00
|
|
|
|
2018-04-26 12:12:20 +00:00
|
|
|
def handle_subscribe(client, userdata, mid, granted_qos):
|
|
|
|
print('MQTT client subscribed')
|
|
|
|
|
2018-04-26 13:03:38 +00:00
|
|
|
|
2018-04-26 12:12:20 +00:00
|
|
|
def handle_mqtt_message(client, userdata, message):
|
|
|
|
data = dict(
|
|
|
|
topic=message.topic,
|
|
|
|
payload=message.payload.decode()
|
|
|
|
)
|
|
|
|
print(message.payload.decode())
|