|
|
|
import os
|
|
|
|
|
|
|
|
import paho.mqtt.client as mqtt
|
|
|
|
import time
|
|
|
|
|
|
|
|
broker = '121.40.129.71'
|
|
|
|
port = 48835
|
|
|
|
|
|
|
|
print(os.getcwd())
|
|
|
|
|
|
|
|
|
|
|
|
with open("smp_coder/user.txt", "r") as f:
|
|
|
|
user_id = f.read().strip()
|
|
|
|
user_id = user_id.split("=")[-1]
|
|
|
|
|
|
|
|
# topic = "request/{}".format(user_id)
|
|
|
|
|
|
|
|
# 回调函数,当客户端收到连接响应时被调用
|
|
|
|
def on_connect(client, userdata, flags, rc, properties=None):
|
|
|
|
print("连接结果: " + str(rc))
|
|
|
|
# 订阅请求主题
|
|
|
|
client.subscribe("request/{}".format(user_id), qos=2)
|
|
|
|
|
|
|
|
# 回调函数,当客户端收到消息时被调用
|
|
|
|
def on_message(client, userdata, msg):
|
|
|
|
print("收到消息: " + msg.topic + " " + str(msg.payload))
|
|
|
|
|
|
|
|
if msg.payload.decode() == "image produce": # 收到拍照请求
|
|
|
|
# 打开相机,拍照,保存图片,发送图片
|
|
|
|
os.system("bash smp_coder/camera.sh")
|
|
|
|
|
|
|
|
|
|
|
|
client.publish("response/{}".format(user_id), "image produce success!", qos=2)
|
|
|
|
client.publish("image/{}".format(user_id), open("/tmp/image.jpg", "rb").read(), qos=2)
|
|
|
|
|
|
|
|
if msg.payload.decode() == "exit": # 收到退出请求
|
|
|
|
client.publish("response/{}".format(user_id), "exit success!", qos=2)
|
|
|
|
client.loop_stop()
|
|
|
|
client.disconnect()
|
|
|
|
# 全局变量,用于标记是否收到响应
|
|
|
|
|
|
|
|
# 创建客户端实例
|
|
|
|
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()
|
|
|
|
|
|
|
|
# 发布消息
|
|
|
|
|
|
|
|
|
|
|
|
# 等待响应
|
|
|
|
response_received = False
|
|
|
|
while not response_received:
|
|
|
|
print("等待响应...")
|
|
|
|
time.sleep(2)
|
|
|
|
|
|
|
|
|
|
|
|
# 停止网络循环并断开连接
|
|
|
|
client.loop_stop()
|
|
|
|
client.disconnect()
|
|
|
|
|
|
|
|
print("收到响应,客户端退出。")
|
|
|
|
|
|
|
|
|
|
|
|
|