Python 连接 EMQX,并发布和订阅主题

发布时间 2023-06-23 01:41:55作者: Himmelbleu

下载包

pip install paho-mqtt

编写函数

import paho.mqtt.client as mqtt

HOST = "localhost"
PORT = 1883
TIME = 60


# 定义发送主题的实体类对象
class Topic:
    def __init__(self, theme, qos, payload=None):
        # theme:主题
        self.theme = theme
        # qos:mqtt 质量
        self.qos = qos
        # payload:消息
        self.payload = payload


# 连接 EMQX
def connEmqx(client_id, username, password):
    c = mqtt.Client(client_id)
    c.username_pw_set(username, password)
    c.connect(HOST, PORT, TIME)
    return c


# 发布
def pubEmqx(client_id, username, password, topic: Topic):
    c = connEmqx(client_id, username, password)
    c.publish(topic=topic.theme, payload=topic.payload, qos=topic.qos)


# 订阅
def subEmqx(client_id, username, password, topic: Topic, on_message):
    c = connEmqx(client_id, username, password)
    c.on_message = on_message
    c.subscribe(topic=topic.theme, qos=topic.qos)
    c.loop_forever()

发布主题

# main.py

from emqx_utils import Topic, pubEmqx

pub_data = json.dumps({'username': 'Himmelbleu'})

pubEmqx('pyclient1', 'pyclient1', '123456', Topic(theme='command', payload=pub_data, qos=0))

调用 pubEmqx 函数,填写客户端 ID、用户名和密码,将主题、消息、质量等传递给第四个参数。程序运行发布一个主题 command。

订阅主题

# main.py

from emqx_utils import Topic, subEmqx

# 处理订阅的消息
def handleSubTopicMsg(client, userdata, msg):
    print(msg)

# 开始订阅
subEmqx('pyclient2', 'pyclient2', '123456', Topic(theme='command', qos=0), handleSubTopicMsg)

调用 subEmqx 函数,编写一个 handleSubTopicMsg 回调函数,当服务器有消息转发过来时就会触发回调函数,控制台就可以打印消息。