From c2a749df78e5f78ad42f2fefc374d641c881253b Mon Sep 17 00:00:00 2001 From: OCEAN <1010331798@qq.com> Date: Tue, 1 Apr 2025 16:55:04 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/main.rs b/src/main.rs index 6253fcd..b594527 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ use serialport; use actix_web::{web, App, HttpServer, HttpResponse}; use actix_cors::Cors; use std::fs; +use std::sync::{Arc, Mutex}; #[derive(Serialize, Deserialize)] struct WeightData { @@ -26,7 +27,7 @@ struct ScaleTypeResponse { scale_type: String, } -#[derive(Deserialize)] +#[derive(Deserialize, Clone)] struct MqttConfig { client_id: String, host: String, @@ -146,24 +147,27 @@ async fn run_mqtt_and_serial() -> Result<()> { Ok(_) => {} } + let mqtt_config = config.mqtt.clone(); + // 创建MQTT连接函数 - let create_mqtt_client = || -> (Client, rumqttc::Connection) { + let create_mqtt_client = move || -> (Client, rumqttc::Connection) { let mut mqttopts = MqttOptions::new( - &config.mqtt.client_id, - &config.mqtt.host, - config.mqtt.port + &mqtt_config.client_id, + &mqtt_config.host, + mqtt_config.port ); mqttopts.set_keep_alive(Duration::from_secs(60)); // 增加保活时间到60秒 - mqttopts.set_credentials(&config.mqtt.username, &config.mqtt.password); + mqttopts.set_credentials(&mqtt_config.username, &mqtt_config.password); mqttopts.set_clean_session(true); Client::new(mqttopts, 10) }; // 初始化MQTT客户端 - let (mut client, mut connection) = create_mqtt_client(); + let (client, mut connection) = create_mqtt_client(); + let client = Arc::new(Mutex::new(client)); + let client_clone = client.clone(); // 在单独的线程中处理MQTT连接 - let mqtt_config = config.mqtt.clone(); thread::spawn(move || { loop { for notification in connection.iter() { @@ -174,7 +178,7 @@ async fn run_mqtt_and_serial() -> Result<()> { thread::sleep(Duration::from_secs(5)); // 等待5秒后重试 // 重新创建连接 let (new_client, new_connection) = create_mqtt_client(); - client = new_client; + *client_clone.lock().unwrap() = new_client; connection = new_connection; break; } @@ -235,7 +239,8 @@ async fn run_mqtt_and_serial() -> Result<()> { // 添加重试机制 while retry_count < max_retries { - match client.publish(&topic, QoS::AtLeastOnce, false, json_data.clone()) { + let mut client_guard = client.lock().unwrap(); + match client_guard.publish(&topic, QoS::AtLeastOnce, false, json_data.clone()) { Ok(_) => { println!("成功发送数据到MQTT"); break;