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.

72 lines
1.8 KiB

5 months ago
import os
5 months ago
import subprocess
5 months ago
import paho.mqtt.client as mqtt
import time
broker = '121.40.129.71'
port = 48835
# 回调函数,当客户端收到连接响应时被调用
def on_connect(client, userdata, flags, rc, properties=None):
print("连接结果: " + str(rc))
# 订阅响应主题
client.subscribe("request/topic")
# 回调函数,当客户端收到消息时被调用
def on_message(client, userdata, msg):
print("收到消息: " + msg.topic + " " + str(msg.payload))
5 months ago
if not os.path.exists("smp_coder/user.txt"):
with open("smp_coder/user.txt", "a") as f:
5 months ago
f.write(msg.payload.decode("utf-8") + "\n")
else:
# 全局变量,用于标记是否收到响应
global response_received
response_received = True
# 创建客户端实例
5 months ago
try:
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,)
except:
client = mqtt.Client()
5 months ago
# 设置回调函数
client.on_connect = on_connect
client.on_message = on_message
# 连接到MQTT代理
client.connect(broker, port, 60)
# 启动一个后台线程来处理网络流量和回调
client.loop_start()
# 发布消息
# 等待响应
response_received = False
while not response_received:
print("等待响应...")
time.sleep(1)
client.publish("response/topic", "Set user.txt success!", qos=2)
5 months ago
5 months ago
5 months ago
command = ["sudo", "myenv/bin/python3", "smp_coder/extur_smp.py"]
with open("logex.txt", "w") as log_file:
process = subprocess.Popen(command, stdout=log_file, stderr=log_file, bufsize=1, universal_newlines=True)
5 months ago
print("启动树莓派拍照客户端成功。")
5 months ago
client.publish("response/topic", "smp_coder started successfully!", qos=2)
5 months ago
# 停止网络循环并断开连接
client.loop_stop()
client.disconnect()
5 months ago
print("收到响应,客户端退出。")
5 months ago