Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
import paho.mqtt.client as mqtt
BROKER_ADDRESS = '127.0.0.1' # 示例代理地址 这个服务器没反应,你应该搭建自己的broker服务器或者使用可用的云broker
BROKER_PORT = 1883 # MQTT 默认端口
CLIENT_ID = 'mqttx_809f42de' # 客户端 ID
# 订阅的主题
TOPICS = [("examinfo", 0), ("activityinfo", 0)]
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
# 订阅所有主题
for topic, qos in TOPICS:
client.subscribe(topic, qos)
# 回调函数,当接收到订阅的主题消息时触发
def on_message(client, userdata, msg):
print(f"Received message on topic {msg.topic}: {str(msg.payload)}")
# 回调函数,当连接建立时触发
# 回调函数,当连接断开时触发
def on_disconnect(client, userdata, rc):
if rc != 0:
print(f"Unexpected disconnection. Will auto-reconnect")
client.reconnect_delay_set(min_delay=1, max_delay=60) # 设置重连延迟(可选)
client.loop_start() # 它会启动一个新的网络线程
client.connect(BROKER_ADDRESS, BROKER_PORT,60) # 尝试重新连接,而 60 是连接超时时间(秒)。如果连接成功,客户端会触发 on_connect 回调函数(如果已设置)。如果连接失败,客户端会根据之前设置的 reconnect_delay_set 策略来尝试重新连接。
else:
print("Normal disconnection. Shutting down...")
client.loop_stop() # 如果正常断开,则停止网络循环
# 实例化MQTT客户端
client = mqtt.Client(CLIENT_ID)
# 绑定回调函数
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
# 连接到MQTT服务器
try:
client.connect(BROKER_ADDRESS, BROKER_PORT, 60)
# 开始网络循环,以便客户端可以处理网络流量
client.loop_start()
except Exception as e:
print(f"Could not connect to the broker {BROKER_ADDRESS}:{BROKER_PORT}, {e}")
# 阻塞主线程,以便程序不会立即退出
try:
while True:
# 等待用户中断
pass
except KeyboardInterrupt:
print("Exiting...")
# 停止网络循环
client.loop_stop()
# 断开连接
client.disconnect()