Python MQTT 简单 Demo


依赖

下载 pahao-mqtt

pip install paho-mqtt

引用:

from paho.mqtt import client as MQTTClient
from time import sleep

示例

非匿名连接

初始化数据:

class Config:
    BROKER = "[MQTT 服务器 IP 或 域名]"
    PORT = [MQTT 服务器端口]
    TOPIC = "[主题]"
    CLIENT_ID = "[客户端 ID]"
    USERNAME = "[用户名]"
    PASSWORD = 口令"
    CONNECT = None
    MESSAGE = "[消息]"

建立连接

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)
    Config.CONNECT = MQTTClient.Client(Config.CLIENT_ID)
    Config.CONNECT.username_pw_set(Config.USERNAME, Config.PASSWORD)
    Config.CONNECT.on_connect = on_connect
    Config.CONNECT.connect(Config.BROKER, Config.PORT)

通过主题发布消息

def publish():
    while(True):
        sleep(1)
        result = Config.CONNECT.publish(Config.TOPIC, Config.MESSAGE)
        status = result[0]
        if status == 0:
            print(f"Send `{Config.MESSAGE}` to topic `{Config.TOPIC}`")
        else:
            print(f"Failed to send message to topic {Config.TOPIC}")

def app():
    connect_mqtt()
    publish()
    Config.CONNECT.loop_forever()

通过主题订阅消息

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

def app():
    connect_mqtt()
    subscribe()
    Config.CONNECT.loop_forever()

运行

if __name__ == '__main__':
    app()

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/274642.html

(0)
上一篇 2022年7月16日
下一篇 2022年7月16日

相关推荐

发表回复

登录后才能评论