You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import paho.mqtt.client as mqtt
import time
import os
# 检查是否存在edu_coder/user.txt文件如果不存在则执行get_user.sh脚本
if not os.path.exists("edu_coder/user.txt"):
os.system("cd edu_coder && bash get_user.sh")
# os.system("bash edu_coder/get_user.sh")
# MQTT代理地址
broker = '121.40.129.71'
# MQTT代理端口
port = 48835
# 回调函数,当客户端收到连接响应时被调用
def on_connect(client, userdata, flags, rc, properties=None):
print("连接结果: " + str(rc))
# 订阅响应主题
client.subscribe("response/topic")
# 回调函数,当客户端收到消息时被调用
def on_message(client, userdata, msg):
print("收到消息: " + msg.topic + " " + str(msg.payload))
# 如果收到的消息是"Set user.txt success!"则设置response_received为True
if msg.payload.decode() == "Set user.txt success!":
global response_received
response_received = True
# 创建客户端实例
try:
client = mqtt.Client()
except:
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,)
# 设置回调函数
client.on_connect = on_connect
client.on_message = on_message
# 连接到MQTT代理
client.connect(broker, port, 60)
# 启动一个后台线程来处理网络流量和回调
client.loop_start()
# 读取edu_coder/user.txt文件中的用户信息
with open("edu_coder/user.txt", "r", encoding="utf8") as f:
user = f.read().strip()
# # 发布消息
# client.publish("request/topic", user, qos=2)
# 等待响应
response_received = False
while not response_received:
# 发布消息
client.publish("request/topic", user, qos=0)
print("等待响应...")
time.sleep(1)
# 停止网络循环并断开连接
client.loop_stop()
client.disconnect()
print("收到响应,客户端退出。")