msg MQTT message

main
zart 5 months ago
parent 37688ff4c8
commit 25d360f93c

@ -31,7 +31,7 @@ check_python_library() {
# 检查某个软件
check_software "git"
check_software "redis-server"
# 检查某个库文件
#check_library "/usr/lib/libc.so.6"
@ -40,28 +40,6 @@ check_software "redis-server"
#check_python_library "numpy"
# 检查是否安装了redis
if ! command -v redis-server &> /dev/null; then
echo "未找到redis-server尝试安装redis..."
if command -v apt-get &> /dev/null; then
sudo apt-get update
sudo apt-get install -y redis-server
elif command -v yum &> /dev/null; then
sudo yum install -y redis
else
echo "无法自动安装redis请手动安装redis后重试。"
exit 1
fi
fi
# 检查redis-server安装是否成功
if command -v redis-server &> /dev/null; then
echo "Redis安装成功"
else
echo "Redis安装失败请手动安装后重试。"
exit 1
fi
# 设置仓库URL和本地目录
repo_url="https://bdgit.educoder.net/pv2ajsu8k/smp_pc_20240625.git"
local_dir="smp_pc"

@ -0,0 +1,68 @@
import os
import paho.mqtt.client as mqtt
import time
broker = '121.40.129.71'
port = 48835
with open("../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("response/{}".format(user_id), qos=2)
client.subscribe("image/{}".format(user_id), qos=2)
# 回调函数,当客户端收到消息时被调用
def on_message(client, userdata, msg):
# print("收到消息: " + msg.topic + " " + str(msg.payload))
if msg.topic == "response/{}".format(user_id):
print("收到响应: " + str(msg.payload))
if msg.topic == "image/{}".format(user_id):
with open("image.jpg", "wb") as f:
f.write(msg.payload)
print("图片已保存。")
global response_received
response_received = True
# 创建客户端实例
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(1)
client.publish("request/{}".format(user_id), "image produce", qos=2)
# 停止网络循环并断开连接
client.loop_stop()
client.disconnect()
print("收到响应,客户端退出。")

@ -23,7 +23,10 @@ def on_message(client, userdata, msg):
response_received = True
# 创建客户端实例
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,)
try:
client = mqtt.Client()
except:
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,)
# 设置回调函数
client.on_connect = on_connect

@ -1,51 +0,0 @@
# -*- coding: utf-8 -*-# -*- coding: utf-8 -*-
# 订阅者
import paho.mqtt.client as mqtt
broker = '121.40.129.71'
# 连接成功回调
def on_connect(client, userdata, flags, rc,properties):
if rc.is_failure:
print(f"连接失败: {rc}. loop_forever()将重新连接")
else:
print(f'连接成功: {rc}')
client.subscribe('host_status/#')
def on_subscribe(client, userdata, mid, reason_code_list, properties): # 订阅回调
if reason_code_list[0].is_failure:
print(f'订阅失败: {reason_code_list[0]}')
else:
print(f'订阅成功: {reason_code_list[0].value}')
def on_unsubscribe(client, userdata, mid, reason_code_list, properties): # 取消订阅回调
if len(reason_code_list) == 0 or not reason_code_list[0].is_failure:
print("取消订阅成功(if SUBACK is received in MQTTv3 it success)")
else:
print(f"取消订阅失败: {reason_code_list[0]}")
client.disconnect() # 断开连接
# 消息接收回调
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
mqtt = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="book_1")
mqtt.on_connect = on_connect
mqtt.on_message = on_message
mqtt.on_subscribe = on_subscribe
mqtt.on_unsubscribe = on_unsubscribe
mqtt.is_connected()
mqtt.user_data_set(["user_data", "book_1"])
mqtt.connect(broker, 48835, 60)
mqtt.loop_forever()
print(f"收到以下消息: {mqtt.user_data_get()}")
# while True:
# rc = mqtt.loop(timeout=1.0)
# print(11)
# if rc != 0:
# mqtt.reconnect()

@ -1,63 +0,0 @@
import time
import paho.mqtt.client as mqtt
broker = '121.40.129.71'
def on_publish(client, userdata, mid, reason_code, properties):
# reason_code and properties will only be present in MQTTv5. It's always unset in MQTTv3
print(f"mid: {mid}, reason_code: {reason_code}, properties: {properties}") # mid: 消息ID, reason_code: 返回码, properties: 属性
def on_connect(client, userdata, flags, rc, properties):
if rc.is_failure:
print(f"连接失败: {rc}. loop_forever()将重新连接")
else:
print(f'连接成功: {rc}')
client.subscribe('host_status/#')
# unacked_publish = set()
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="book_1")
mqttc.on_publish = on_publish
mqttc.on_connect = on_connect
# mqttc.user_data_set(unacked_publish)
mqttc.connect(broker, 48835, 60)
# mqttc.loop_start()
while True:
if not mqttc.is_connected():
print("连接断开,重新连接")
mqttc.connect(broker, 48835, 60,)
keys = input("输入任意键发送消息输入q退出")
if keys == 'q':
break
mqttc.loop(timeout=1.0)
# Our application produce some messages
msg_info = mqttc.publish("tts/1", keys, qos=1)
# unacked_publish.add(msg_info.mid)
# msg_info2 = mqttc.publish("host_status", "my message2", qos=1)
# unacked_publish.add(msg_info2.mid)
# # Wait for all message to be published
# while len(unacked_publish):
# time.sleep
# Our application produce some messages
# msg_info = mqttc.publish("host_status", "my message", qos=1)
# # unacked_publish.add(msg_info.mid)
#
# msg_info2 = mqttc.publish("host_status", "my message2", qos=1)
# # unacked_publish.add(msg_info2.mid)
# # Wait for all message to be published
# while len(unacked_publish):
# time.sleep(0.1)
# Due to race-condition described above, the following way to wait for all publish is safer
# msg_info.wait_for_publish()
# msg_info2.wait_for_publish()
#
mqttc.disconnect()
mqttc.loop_stop()

@ -1,14 +0,0 @@
import paho.mqtt.client as mqtt
def publish_image(mqtt_client, topic, image_path):
with open(image_path, "rb") as image_file:
image_data = image_file.read()
mqtt_client.publish(topic, image_data)
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,)
client.connect("121.40.129.71", 48835, 60) # 连接到 MQTT 代理
client.loop_start()
img_path = input("Enter the path of the image: ")
publish_image(client, "test/image", img_path)
client.loop_stop()

@ -1,4 +1,3 @@
#!/usr/bin/bash
libcamera-still -o image.jpg --timeout 1000
libcamera-still -o /tmp/image.jpg --timeout 10

@ -6,10 +6,14 @@ import time
broker = '121.40.129.71'
port = 48835
with open("../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))
@ -20,8 +24,14 @@ def on_connect(client, userdata, flags, rc, properties=None):
def on_message(client, userdata, msg):
print("收到消息: " + msg.topic + " " + str(msg.payload))
os.system("cp user.txt user.bak")
if msg.payload.decode() == "image produce": # 收到拍照请求
# 打开相机,拍照,保存图片,发送图片
if not os.path.exists("/tmp/image.jpg"):
os.system("bash camera.sh")
else:
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)
# 全局变量,用于标记是否收到响应
global response_received
response_received = True
@ -46,9 +56,8 @@ client.loop_start()
response_received = False
while not response_received:
print("等待响应...")
time.sleep(1)
time.sleep(2)
client.publish("response/topic", "Set user.txt success!", qos=2)
# 停止网络循环并断开连接
client.loop_stop()

@ -26,7 +26,10 @@ def on_message(client, userdata, msg):
response_received = True
# 创建客户端实例
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,)
try:
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,)
except:
client = mqtt.Client()
# 设置回调函数
client.on_connect = on_connect

@ -1,18 +0,0 @@
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc,properties):
print("Connected with result code " + str(rc))
client.subscribe("test/image")
def on_message(client, userdata, msg):
with open("received_image.jpg", "wb") as image_file:
image_file.write(msg.payload)
print("Image received and saved")
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, )
client.on_connect = on_connect
client.on_message = on_message
client.connect("121.40.129.71", 48835, 60) # 连接到 MQTT 代理
client.loop_forever()

@ -1,32 +0,0 @@
# MQTT订阅客户端
import paho.mqtt.client as mqtt
broker = "121.40.129.71"
# 连接成功回调
def on_connect(client, userdata, flags, rc,properties):
print('Connected with result code '+str(rc))
client.subscribe('tts/#')
# 消息接收回调
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, clean_session=True)
# username = "gd32"
# password = "educoder"
# client.username_pw_set(username, password)
# 指定回调函数
client.on_connect = on_connect
client.on_message = on_message
# 建立连接
client.connect(broker, 48835, 60)
# 发布消息
# client.publish('emqtt',payload='Hello World',qos=0)
client.loop_forever()
Loading…
Cancel
Save