Path: blob/master/gate-controller/src-tauri/src/config.rs
1072 views
use serde::{Deserialize, Serialize};1use std::fs::{self, OpenOptions};2use std::io::Write;3use std::path::PathBuf;4use tauri::{AppHandle, Manager};56#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]7pub enum RelayType {8#[serde(rename = "ch340")]9CH340,10#[serde(rename = "hw348")]11HW348,12#[serde(rename = "cp210x")]13CP210x,14}1516#[derive(Serialize, Deserialize, Debug, Clone)]17pub struct ConfiguredRelay {18pub id: String,19#[serde(rename = "type")]20pub relay_type: RelayType,21#[serde(skip_serializing_if = "Option::is_none")]22pub channels: Option<u8>,23}2425#[derive(Serialize, Deserialize, Debug, Clone, Default)]26pub struct AppConfig {27pub relays: Vec<ConfiguredRelay>,28#[serde(skip_serializing_if = "Option::is_none")]29pub webhook_token: Option<String>,30}3132fn get_config_dir(app: &AppHandle) -> Result<PathBuf, String> {33let config_dir = app.path().app_config_dir().map_err(|e| e.to_string())?;34if !config_dir.exists() {35fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?;36}37Ok(config_dir)38}3940fn get_config_path(app: &AppHandle) -> Result<PathBuf, String> {41Ok(get_config_dir(app)?.join("config.json"))42}4344fn get_log_path(app: &AppHandle) -> Result<PathBuf, String> {45Ok(get_config_dir(app)?.join("webhook_logs.txt"))46}4748pub fn append_to_log(app: &AppHandle, log_line: &str) -> Result<(), String> {49let path = get_log_path(app)?;50let mut file = OpenOptions::new()51.create(true)52.append(true)53.open(path)54.map_err(|e| e.to_string())?;5556writeln!(file, "{}", log_line).map_err(|e| e.to_string())57}5859pub fn load_config(app: &AppHandle) -> Result<AppConfig, String> {60let path = get_config_path(app)?;61if !path.exists() {62return Ok(AppConfig::default());63}64let content = fs::read_to_string(path).map_err(|e| e.to_string())?;65if content.trim().is_empty() {66return Ok(AppConfig::default());67}68serde_json::from_str(&content).map_err(|e| e.to_string())69}7071pub fn save_config(app: &AppHandle, config: &AppConfig) -> Result<(), String> {72let path = get_config_path(app)?;73let content = serde_json::to_string_pretty(config).map_err(|e| e.to_string())?;74fs::write(path, content).map_err(|e| e.to_string())75}767778