Basic MQTT communication with flask-MQTT.
One of the most famous and used communication protocols in the IoT area is MQTT, which manages this flow of messages by subscriptions and publications, here we will see how to do that communication used in a flask server.
To use this library we must install it with the following command:
pip install Flask-MQTT
MQTT settings:
First, we must create the flask application, then we must configure the MQTT, and finally, we create the client, if this order changes, there may be problems when creating the mqtt_client.
Topics
We can subscribe to a topic, unsubscribe and publish into a topic.
Handle situations
We can do different actions according to different situations and the most common situations are:
One of the advantage of using the mqtt communication protocol is that you dont need to have a response, in a REST API every requests need a response, if that response dont have a answer in a period of time, a time out will raise, but using mqtt protocol, you can begin a process through a mqtt message and the process can take a lot of time, but a time out dont raise.
Now, we can run our server and use any mqtt broker to send a message that we can see it in our terminal, I am using an a “MyMqtt” to send the messages.
In this point, we successfully integrate mqtt in a flask app.
Documentation:
- https://flask-mqtt.readthedocs.io/en/latest/usage.html
- https://mqtt.org