|
|
@@ -6,6 +6,7 @@ use std::io::{self, Read}; |
|
|
|
use std::time::Duration; |
|
|
|
use std::thread; |
|
|
|
use serialport; |
|
|
|
use std::process::Command; |
|
|
|
|
|
|
|
#[derive(Serialize, Deserialize)] |
|
|
|
struct WeightData { |
|
|
@@ -13,7 +14,19 @@ struct WeightData { |
|
|
|
timestamp: u64, |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
fn get_mac_address() -> String { |
|
|
|
let output = Command::new("getmac") |
|
|
|
.arg("/fo") |
|
|
|
.arg("csv") |
|
|
|
.arg("/nh") |
|
|
|
.output() |
|
|
|
.expect("Failed to execute getmac command"); |
|
|
|
|
|
|
|
let output_str = String::from_utf8_lossy(&output.stdout); |
|
|
|
let first_line = output_str.lines().next().unwrap_or(""); |
|
|
|
let mac = first_line.split(',').next().unwrap_or("").trim_matches('"'); |
|
|
|
mac.replace('-', ":").to_lowercase() |
|
|
|
} |
|
|
|
|
|
|
|
fn main() -> Result<()> { |
|
|
|
// 创建 MQTT 客户端 |
|
|
@@ -97,14 +110,24 @@ fn main() -> Result<()> { |
|
|
|
.as_secs(), |
|
|
|
}; |
|
|
|
|
|
|
|
// 序列化数据 |
|
|
|
let json_data = serde_json::to_string(&weight_data)?; |
|
|
|
// 开始循环发送数据 |
|
|
|
loop { |
|
|
|
// 序列化数据 |
|
|
|
let json_data = serde_json::to_string(&weight_data)?; |
|
|
|
println!("当前JSON数据: {}", json_data); |
|
|
|
|
|
|
|
// 获取MAC地址 |
|
|
|
let mac_address = get_mac_address(); |
|
|
|
println!("MAC地址: {}", mac_address); |
|
|
|
// 发布到 MQTT,主题中包含MAC地址 |
|
|
|
if let Err(e) = client.publish(format!("weight/data/{}", mac_address), QoS::AtLeastOnce, false, json_data) { |
|
|
|
eprintln!("MQTT发布错误: {:?}", e); |
|
|
|
} else { |
|
|
|
println!("成功发送数据到MQTT"); |
|
|
|
} |
|
|
|
|
|
|
|
// 发布到 MQTT |
|
|
|
if let Err(e) = client.publish("weight/data", QoS::AtLeastOnce, false, json_data) { |
|
|
|
eprintln!("MQTT发布错误: {:?}", e); |
|
|
|
} else { |
|
|
|
println!("成功发送数据到MQTT"); |
|
|
|
// 等待3秒 |
|
|
|
thread::sleep(Duration::from_secs(3)); |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|