Browse Source

主题增加mac地址

dev
OCEAN 3 months ago
parent
commit
2d86850fec
3 changed files with 42 additions and 8 deletions
  1. +1
    -0
      Cargo.lock
  2. +10
    -0
      Cargo.toml
  3. +31
    -8
      src/main.rs

+ 1
- 0
Cargo.lock View File

@@ -647,6 +647,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"serialport", "serialport",
"winapi",
] ]


[[package]] [[package]]


+ 10
- 0
Cargo.toml View File

@@ -9,3 +9,13 @@ anyhow = "1.0"
rumqttc = "0.23" rumqttc = "0.23"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"

[profile.release]
opt-level = 3
lto = true
codegen-units = 1
panic = 'abort'
strip = true

[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["winbase"] }

+ 31
- 8
src/main.rs View File

@@ -6,6 +6,7 @@ use std::io::{self, Read};
use std::time::Duration; use std::time::Duration;
use std::thread; use std::thread;
use serialport; use serialport;
use std::process::Command;


#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct WeightData { struct WeightData {
@@ -13,7 +14,19 @@ struct WeightData {
timestamp: u64, 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<()> { fn main() -> Result<()> {
// 创建 MQTT 客户端 // 创建 MQTT 客户端
@@ -97,14 +110,24 @@ fn main() -> Result<()> {
.as_secs(), .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));
} }
} }
} }


Loading…
Cancel
Save