python链接mqtt订阅与发布
阅读原文时间:2023年07月11日阅读:1

MQTT 全称为 Message Queuing Telemetry Transport(消息队列遥测传输)是一种基于发布/订阅范式的“轻量级”消息协议。该协议构建于TCP/IP协议上

“至多一次”,消息发布完全依赖底层 TCP/IP 网络。会发生消息丢失或重复。这一级别可用于如下情况,环境传感器数据,丢失一次读记录无所谓,因为不久后还会有第二次发送。
“至少一次”,确保消息到达,但消息重复可能会发生。
“只有一次”,确保消息到达一次。这一级别可用于如下情况,在计费系统中,消息重复或丢失会导致不正确的结果。

安装:pip install paho-mqtt 如何安装失败,可以尝试换豆瓣源pip install paho-mqtt -i https://pypi.douban.com/simple/

订阅:

import random

from paho.mqtt import client as mqtt_client

broker = #ip地址
port = 1883
topic = "/python/mqtt"

generate client ID with pub prefix randomly

client_id = #client_id

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

消息发布

import random
import time

from paho.mqtt import client as mqtt_client
#基本链接数据同上
topic=""
def clicent_main(client,message: str):
"""
客户端发布消息
:param message: 消息主体
:return:
"""
time_now = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime(time.time()))
payload = {"msg": "%s" % message, "data": "%s" % time_now}
# publish(主题:Topic; 消息内容)
client.publish(topic, json.dumps(payload, ensure_ascii=False))
print("Successful send message!")
return True