编程语言
首页 > 编程语言> > Python MQTT 简单 Demo

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

标签:Python,Demo,mqtt,MQTT,CONNECT,print,Config,def,connect
来源: https://www.cnblogs.com/Yogile/p/16473455.html