Przeglądaj źródła

主题增加mac地址

dev
OCEAN 3 miesięcy temu
rodzic
commit
2d86850fec
3 zmienionych plików z 42 dodań i 8 usunięć
  1. +1
    -0
      Cargo.lock
  2. +10
    -0
      Cargo.toml
  3. +31
    -8
      src/main.rs

+ 1
- 0
Cargo.lock Wyświetl plik

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

[[package]]


+ 10
- 0
Cargo.toml Wyświetl plik

@@ -9,3 +9,13 @@ anyhow = "1.0"
rumqttc = "0.23"
serde = { version = "1.0", features = ["derive"] }
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 Wyświetl plik

@@ -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));
}
}
}


Ładowanie…
Anuluj
Zapisz