How to use MQTT in Python

Python is a widely used interpreted, high-level programming, and general-purpose programming language. Python's design philosophy emphasizes code readability and concise syntax (especially the use of space indentation to divide code blocks instead of braces or keywords). Python allows developers to express ideas with less code. Whether it is a small or large program, the language tries to make the structure of the program clear. 1

MQTT is based publish / subscribe model of lightweight Things messaging protocol , can provide real-time reliable messaging services for the networked device with minimal 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 use the paho-mqtt client library in a Python project to realize the functions of connecting, subscribing, unsubscribing, sending and receiving messages between the client and the MQTT server.

Project initialization

This project uses Python 3.6 for development and testing. Readers can confirm the Python version with the following command.

➜  ~ python3 --version             
Python 3.6.7

Choose MQTT client library

paho-mqtt is currently the most used MQTT client library in Python. It provides support for MQTT v3.1 and v3.1.1 for client classes on Python 2.7 or 3.x. It also provides some helper functions to make it very easy to publish messages to the MQTT server.

Pip install Paho MQTT client

Pip is a Python package management tool that provides functions for searching, downloading, installing, and uninstalling Python packages.

pip3 install -i https://pypi.doubanio.com/simple paho-mqtt

Python MQTT use

Connect to MQTT server

This article will use the EMQ X provides free public MQTT server , the service is based on the EMQ X MQTT of Things cloud platform created. The server access information is as follows:

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

Import Paho MQTT client

from paho.mqtt import client as mqtt_client

Set MQTT Broker connection parameters

Set the MQTT Broker connection address, port and topic, and we call the Python random.randintfunction to randomly generate the MQTT client id.

broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt"
client_id = f'python-mqtt-{random.randint(0, 1000)}'

Write MQTT connection function

Write connection callback function on_connect, the function will be called after the client connection, this function can be based rcto determine whether the client connection is successful. Usually at the same time we will create an MQTT client that will connect to broker.emqx.io.

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)
    # Set Connecting Client ID
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

make an announcement

First define a while loop, the loop we will set up a client calls per second MQTT publishfunction to /python/mqttsend a message subject.

 def publish(client):
     msg_count = 0
     while True:
         time.sleep(1)
         msg = f"messages: {msg_count}"
         result = client.publish(topic, msg)
         # result: [0, 1]
         status = result[0]
         if status == 0:
             print(f"Send `{msg}` to topic `{topic}`")
         else:
             print(f"Failed to send message to topic {topic}")
         msg_count += 1

Subscribe to news

Write a message callback function on_message, which will be called after the client receives a message from MQTT Broker. In this function, we will print out the name of the subscribed topic and the content of the received message.

def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

    client.subscribe(topic)
    client.on_message = on_message

Complete code

News release code

# python 3.6

import random
import time

from paho.mqtt import client as mqtt_client


broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 1000)}'


def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def publish(client):
    msg_count = 0
    while True:
        time.sleep(1)
        msg = f"messages: {msg_count}"
        result = client.publish(topic, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")
        msg_count += 1


def run():
    client = connect_mqtt()
    client.loop_start()
    publish(client)


if __name__ == '__main__':
    run()

Message subscription code

# python3.6

import random

from paho.mqtt import client as mqtt_client


broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 100)}'


def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

    client.subscribe(topic)
    client.on_message = on_message


def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()


if __name__ == '__main__':
    run()

test

News release

Run the MQTT message publishing code, we will see that the client connects successfully and publishes the message successfully.

python3 pub.py

Insert picture description here

News subscription

Run the MQTT message subscription code, we will see that the client is successfully connected and the published message is successfully received.

python3 sub.py

Insert picture description here

to sum up

So far, we have completed the use paho-mqtt client connects to the public MQTT server , and to achieve the connection test client and server MQTT, publish and subscribe messaging.

Unlike high-level languages ​​such as C++ or Java, Python is more suitable for device-side business logic implementation. With Python, you can reduce the logic complexity of the code and reduce the cost of interaction with the device. We believe that Python will have wider applications in the field of Internet of Things.

Next, we will publish more articles about IoT development and Python, so stay tuned.

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

Original link: https://www.emqx.io/cn/blog/how-to-use-mqtt-in-python


  1. https://zh.wikipedia.org/wiki/Python ↩︎

Guess you like

Origin blog.csdn.net/emqx_broker/article/details/108060006
Recommended