MQTT的Python使用示例

MQTT的Python使用示例

一、下载安装

终端执行下面命令:

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

完成安装

二、使用示例

完整代码示例,订阅消息部分:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# create time : 2021/7/12 11:42
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
", 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()

发布消息部分:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# create time : 2021/7/12 11:41

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
", 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()

三、使用示例

个人封装使用示例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# create time : 2021/7/12 10:30
import json
import time

from paho.mqtt.client import Client

HOST = "XX.XX.XX.XX"
PORT = 10083
USERNAME = "robot"
PASSWORD = "XXXXXXXX"
CLIENT_ID = "9678de037b9d4eb3a"
KEEP_LIVE = 60

TOPIC = "/robot/00000000000000000033/task/add/push"
PAYLOAD = {
    "device_id": "00000000000000000033",
    "parameter": [
        {
            "cleaning_mode": {
                "cleaning_mode_id": "90000001",
                "cleaning_mode_name": "正常"
            },
            "cron_expr": "0 0 0 0 0 0",
            "enable": 1,
            "end_time": 1626085703000,
            "map_list": [
                {
                    "map_id": "9f4137b6-5894-4b13-b621-1adae6f5c9a0_1625539983144",
                    "map_sequence": 1,
                    "subregion": [
                        {
                            "sequence": 1,
                            "subregion_id": "8ae0365b-070e-4221-a9f5-c91a13ee0843"
                        }
                    ]
                }
            ],
            "server_map_id": "",
            "start_time": 0,
            "task_id": "2182",
            "task_name": "清扫"
        }
    ],
    "sequence": 5,
    "timestamp": 1626082109147
}


class SendTaskProcessor(object):

    def __init__(self, host, port, username, password, client_id):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.client = Client(client_id=client_id)

    def establish_conn(self):
        """建立连接"""

        def on_connect(client, userdata, flags, rc):
            if rc == 0:
                print("Connected to MQTT Broker!")
            else:
                print("Failed to connect, return code {}".format(rc))

        try:
            self.client.on_connect = on_connect
            self.client.username_pw_set(self.username, self.password)
            self.client.connect(self.host, self.port, KEEP_LIVE)
        except Exception as ex:
            print(ex)

    def pub_message(self, topic, payload, qos=0):
        """发布消息"""
        try:
            self.client.publish(topic, payload)
        except Exception as ex:
            print(ex)

    def sub_message(self, topic):
        """订阅消息"""

        def on_message(client, userdata, msg):
            """处理接收到的消息"""
            now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            # 注意这里的msg是一个json字符串格式
            recv_msg = json.loads(msg.payload)
            print(recv_msg)

        try:
            self.client.subscribe(topic)
        except Exception as ex:
            print(ex)
        else:
            # 处理接收到的消息
            self.client.on_message = on_message

    def process_task(self):
        self.establish_conn()
        # 订阅topic
        self.sub_message(TOPIC)
        self.client.loop_forever()

        # # 发布topic
        # self.client.loop_start()
        # data = json.dumps(PAYLOAD)
        # self.pub_message(TOPIC, data)


if __name__ == '__main__':
    processor = SendTaskProcessor(HOST, PORT, USERNAME, PASSWORD, CLIENT_ID)
    processor.process_task()

四、参考链接

https://zhuanlan.zhihu.com/p/187481769

https://blog.csdn.net/weixin_41656968/article/details/80848542

原文地址:https://www.cnblogs.com/huaibin/p/15006198.html