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