Przeglądaj źródła

增加配置文件

dev
OCEAN 3 miesięcy temu
rodzic
commit
91e43662f7
2 zmienionych plików z 59 dodań i 10 usunięć
  1. +3
    -0
      config.json
  2. +56
    -10
      src/main.rs

+ 3
- 0
config.json Wyświetl plik

@@ -0,0 +1,3 @@
{
"scale_type": "001"
}

+ 56
- 10
src/main.rs Wyświetl plik

@@ -9,6 +9,7 @@ use serialport;
use std::process::Command;
use actix_web::{web, App, HttpServer, HttpResponse};
use actix_cors::Cors;
use std::fs;

#[derive(Serialize, Deserialize)]
struct WeightData {
@@ -21,18 +22,52 @@ struct MacResponse {
mac_address: String,
}

#[derive(Serialize)]
struct ScaleTypeResponse {
scale_type: String,
}

#[derive(Deserialize)]
struct Config {
scale_type: String,
}

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 = 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()
// 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()

let config_path = "config.json";
match fs::read_to_string(config_path) {
Ok(content) => {
match serde_json::from_str::<Config>(&content) {
Ok(config) => config.scale_type,
Err(_) => String::from("Unknown")
}
},
Err(_) => String::from("Unknown")
}
}

fn get_scale_type() -> String {
let config_path = "config.json";
match fs::read_to_string(config_path) {
Ok(content) => {
match serde_json::from_str::<Config>(&content) {
Ok(config) => config.scale_type,
Err(_) => String::from("Unknown")
}
},
Err(_) => String::from("Unknown")
}
}

// HTTP处理函数
@@ -45,6 +80,16 @@ async fn get_mac() -> HttpResponse {
HttpResponse::Ok().json(response)
}

// 新增的HTTP处理函数
async fn get_scale() -> HttpResponse {
let scale_type = get_scale_type();
println!("HTTP请求:获取天平类型 = {}", scale_type);
let response = ScaleTypeResponse {
scale_type,
};
HttpResponse::Ok().json(response)
}

#[actix_web::main]
async fn main() -> Result<()> {
println!("程序启动...");
@@ -64,6 +109,7 @@ async fn main() -> Result<()> {
App::new()
.wrap(cors) // 添加CORS中间件
.route("/mac", web::get().to(get_mac))
.route("/scale", web::get().to(get_scale)) // 新增的路由
})
.bind(("0.0.0.0", 8080))?
.run();


Ładowanie…
Anuluj
Zapisz