1

Flask is a lightweight web application framework written in Python, which is called a "micro-framework" because it uses a simple core and adds other functions with extensions, such as: ORM, form validation tools, file uploads, various Open authentication technologies, etc.

MQTT is a lightweight IoT message transmission protocol based on the publish/subscribe model, which can provide real-time and reliable message services for networked devices with very little code and bandwidth. It is widely used in the Internet of Things, mobile Internet, smart hardware, Internet of vehicles, electric power and other industries.

This article mainly introduces how to realize the connection, subscription, unsubscribe, sending and receiving of messages and other functions between the MQTT client and the MQTT server in the Flask project.

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

Project initialization

This project uses Python 3.8 for development and testing. Readers can use the following commands to confirm the Python version.

 $ python3 --version
Python 3.8.2

Install the Flask-MQTT library with Pip

 pip3 install flask-mqtt

Flask-MQTT usage

This article will use the free public MQTT server provided by EMQ, which is based on the MQTT cloud service - EMQX Cloud. The server access information is as follows:

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

Import Flask-MQTT

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

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

app = Flask(__name__)

Configure the Flask-MQTT extension

 app.config['MQTT_BROKER_URL'] = 'broker.emqx.io'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''  # 当你需要验证用户名和密码时,请设置该项
app.config['MQTT_PASSWORD'] = ''  # 当你需要验证用户名和密码时,请设置该项
app.config['MQTT_KEEPALIVE'] = 5  # 设置心跳时间,单位为秒
app.config['MQTT_TLS_ENABLED'] = False  # 如果你的服务器支持 TLS,请设置为 True
topic = '/flask/mqtt'

mqtt_client = Mqtt(app)

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

Write the connection callback function

The success or failure of the MQTT connection can be handled in this callback function. This example will subscribe to the topic /flask/mqtt after the connection is successful.

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

Write a message callback function

This function will print /flask/mqtt the message received by the 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 a publish message interface

We create a simple POST interface to implement MQTT message publishing.

In practical applications, this interface may require some more complex 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 the Flask app

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

When the Flask app starts, the MQTT client will connect to the server and subscribe to the topic /flask/mqtt .

test

Next, we use the MQTT client - MQTT X for connection, subscription, and publishing tests.

Test message reception

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

    MQTT X 中创建链接

  2. Publish message Hello from MQTT X /flask/mqtt in MQTT X.

    MQTT X 消息发布

  3. The messages sent by MQTT X will be visible in the Flask run window.

    Flask 接收 MQTT 消息

Test message publishing interface

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

    MQTT X 订阅主题

  2. Using Postman call /publish interface: send message Hello from Flask to /flask/mqtt topic.

    Postman 调用发布接口

  3. In MQTT X, you will be able to see the message sent by Flask.

    Flask 发布 MQTT 消息

full 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'] = ''  # 当你需要验证用户名和密码时,请设置该项
app.config['MQTT_PASSWORD'] = ''  # 当你需要验证用户名和密码时,请设置该项
app.config['MQTT_KEEPALIVE'] = 5  # 设置心跳时间,单位为秒
app.config['MQTT_TLS_ENABLED'] = False  # 如果你的服务器支持 TLS,请设置为 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)
   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)

Precautions

Flask-MQTT is currently not suitable for using multiple worker instances, if you need to use a WSGI server like gevent or gunicorn , make sure there is only one worker instance.

Summarize

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

Copyright statement: This article is original by EMQ, please indicate the source when reprinting.

Original link: https://www.emqx.com/zh/blog/how-to-use-mqtt-in-flask


EMQX
336 声望438 粉丝

EMQ(杭州映云科技有限公司)是一家开源物联网数据基础设施软件供应商,交付全球领先的开源 MQTT 消息服务器和流处理数据库,提供基于云原生+边缘计算技术的一站式解决方案,实现企业云边端实时数据连接、移动、...