DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Frameworks
  4. How To Use MQTT in Flask

How To Use MQTT in Flask

This article introduces how to use MQTT in the Flask project and implements the connection and other functions between the MQTT client and the MQTT broker.

Ming Zhao user avatar by
Ming Zhao
·
Nov. 29, 22 · Tutorial
Like (1)
Save
Tweet
Share
3.53K Views

Join the DZone community and get the full member experience.

Join For Free

Flask is a lightweight Web application framework written with Python, which is called a "micro-framework" because it uses a simple core for extension of other features, such as ORM, form validation tools, file upload, various open authentication techniques, etc.

MQTT is a lightweight Internet of Things (IoT) message transmission protocol based on publish/subscribe mode. It can provide a real-time and reliable message service for networked devices with very less code and smaller bandwidth. It is widely used in IoT, mobile Internet, intelligent hardware, IoV, power and energy industries, etc.

This article mainly introduces how to use MQTT in the Flask project and implements the connection, subscription, messaging, unsubscribing, and other functions between the MQTT client and MQTT broker.

We will use the Flask-MQTT client library, which is a Flask extension and can be regarded as a decorator of paho-mqtt to simplify the MQTT integration in Flask applications.

Project Initialization

This project is developed and tested with Python 3.8, and users may use the following commands to verify the version of Python.

 
$ python3 --version
Python 3.8.2

Use Pip to install the Flask-MQTT library.

 
pip3 install flask-mqtt

Use Flask-MQTT

We will adopt the Free public MQTT broker that was created on the basis of the MQTT cloud service - EMQX Cloud. The following is the server access information:

  • Broker: broker.emqx.io
  • TCP Port: 1883
  • Websocket Port: 8083

Import Flask-MQTT

Import the Flask library and Flask-MQTT extension, and create the Flask application.

 
from flask import Flask, request, jsonify
from flask_mqtt import Mqtt

app = Flask(__name__)

Configure Flask-MQTT Extension

 
app.config['MQTT_BROKER_URL'] = 'broker.emqx.io'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''  # Set this item when you need to verify username and password
app.config['MQTT_PASSWORD'] = ''  # Set this item when you need to verify username and password
app.config['MQTT_KEEPALIVE'] = 5  # Set KeepAlive time in seconds
app.config['MQTT_TLS_ENABLED'] = False  # If your server supports TLS, set it True
topic = '/flask/mqtt'

mqtt_client = Mqtt(app)

For complete configuration items, please refer to the Flask-MQTT configuration document.

Write Connect Callback Function

We can handle successful or failed MQTT connections in this callback function, and this example will subscribe to the /flask/mqtt topic after a successful connection.

 
@mqtt_client.on_connect()
def handle_connect(client, userdata, flags, rc):
   if rc == 0:
       print('Connected successfully')
       mqtt_client.subscribe(topic) # subscribe topic
   else:
       print('Bad connection. Code:', rc)

Write Message Callback Function

This function will print the messages received by the /flask/mqtt topic.

 
@mqtt_client.on_message()
def handle_mqtt_message(client, userdata, message):
   data = dict(
       topic=message.topic,
       payload=message.payload.decode()
  )
   print('Received message on topic: {topic} with payload: {payload}'.format(**data))

Create Message Publish API

We create a simple POST API to publish the MQTT messages.

In a practical case, the API may need some more complicated business logic processing.

 
@app.route('/publish', methods=['POST'])
def publish_message():
   request_data = request.get_json()
   publish_result = mqtt_client.publish(request_data['topic'], request_data['msg'])
   return jsonify({'code': publish_result[0]})

Run Flask Application

When the Flask application is started, the MQTT client will connect to the server and subscribe to the topic /flask/mqtt.

 
if __name__ == '__main__':
   app.run(host='127.0.0.1', port=5000)

Test

Now, we use the MQTT client - MQTT X to connect, subscribe, and publish tests.

Receive Message

  1. Create a connection in MQTT X and connect to the MQTT server.

    Create a connection in MQTT X and connect to the MQTT server.

  2. Publish Hello from MQTT X to the /flask/mqtt topic in MQTT X.


  3. We will see the message sent by MQTT X in the Flask running window. 

We will see the message sent by MQTT X in the Flask running window.

Publish Message

  1. Subscribe to the /flask/mqtt topic in MQTT X.

    Subscribe to the /flask/mqtt topic in MQTT X.

  2. Use Postman to call the /publish API: Send the message Hello from Flask to the /flask/mqtt topic.

    Use Postman to call the /publish API: Send the message Hello from Flask to the /flask/mqtt topic.

  3. We can see the message sent from Flask in MQTT X.

    We can see the message sent from Flask in MQTT X.

Complete Code

 
from flask import Flask, request, jsonify
from flask_mqtt import Mqtt

app = Flask(__name__)

app.config['MQTT_BROKER_URL'] = 'broker.emqx.io'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''  # Set this item when you need to verify username and password
app.config['MQTT_PASSWORD'] = ''  # Set this item when you need to verify username and password
app.config['MQTT_KEEPALIVE'] = 5  # Set KeepAlive time in seconds
app.config['MQTT_TLS_ENABLED'] = False  # If your broker supports TLS, set it True
topic = '/flask/mqtt'

mqtt_client = Mqtt(app)


@mqtt_client.on_connect()
def handle_connect(client, userdata, flags, rc):
   if rc == 0:
       print('Connected successfully')
       mqtt_client.subscribe(topic) # subscribe topic
   else:
       print('Bad connection. Code:', rc)


@mqtt_client.on_message()
def handle_mqtt_message(client, userdata, message):
   data = dict(
       topic=message.topic,
       payload=message.payload.decode()
  )
   print('Received message on topic: {topic} with payload: {payload}'.format(**data))


@app.route('/publish', methods=['POST'])
def publish_message():
   request_data = request.get_json()
   publish_result = mqtt_client.publish(request_data['topic'], request_data['msg'])
   return jsonify({'code': publish_result[0]})

if __name__ == '__main__':
   app.run(host='127.0.0.1', port=5000)

Limitations

Flask-MQTT is currently not suitable for use with multiple worker instances. So if you use a WSGI server like gevent or gunicorn make sure you only have one worker instance.

Summary

So far, we have completed a simple MQTT client using Flask-MQTT and can subscribe and publish messages in the Flask application.

MQTT Flask (web framework)

Published at DZone with permission of Ming Zhao. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Memory Debugging: A Deep Level of Insight
  • How to Configure AWS Glue Job Using Python-Based AWS CDK
  • Distributed Stateful Edge Platforms
  • Handling Virtual Threads

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: