Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
parkpow
GitHub Repository: parkpow/deep-license-plate-recognition
Path: blob/master/gate-controller/src-tauri/src/config.rs
1072 views
1
use serde::{Deserialize, Serialize};
2
use std::fs::{self, OpenOptions};
3
use std::io::Write;
4
use std::path::PathBuf;
5
use tauri::{AppHandle, Manager};
6
7
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
8
pub enum RelayType {
9
#[serde(rename = "ch340")]
10
CH340,
11
#[serde(rename = "hw348")]
12
HW348,
13
#[serde(rename = "cp210x")]
14
CP210x,
15
}
16
17
#[derive(Serialize, Deserialize, Debug, Clone)]
18
pub struct ConfiguredRelay {
19
pub id: String,
20
#[serde(rename = "type")]
21
pub relay_type: RelayType,
22
#[serde(skip_serializing_if = "Option::is_none")]
23
pub channels: Option<u8>,
24
}
25
26
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
27
pub struct AppConfig {
28
pub relays: Vec<ConfiguredRelay>,
29
#[serde(skip_serializing_if = "Option::is_none")]
30
pub webhook_token: Option<String>,
31
}
32
33
fn get_config_dir(app: &AppHandle) -> Result<PathBuf, String> {
34
let config_dir = app.path().app_config_dir().map_err(|e| e.to_string())?;
35
if !config_dir.exists() {
36
fs::create_dir_all(&config_dir).map_err(|e| e.to_string())?;
37
}
38
Ok(config_dir)
39
}
40
41
fn get_config_path(app: &AppHandle) -> Result<PathBuf, String> {
42
Ok(get_config_dir(app)?.join("config.json"))
43
}
44
45
fn get_log_path(app: &AppHandle) -> Result<PathBuf, String> {
46
Ok(get_config_dir(app)?.join("webhook_logs.txt"))
47
}
48
49
pub fn append_to_log(app: &AppHandle, log_line: &str) -> Result<(), String> {
50
let path = get_log_path(app)?;
51
let mut file = OpenOptions::new()
52
.create(true)
53
.append(true)
54
.open(path)
55
.map_err(|e| e.to_string())?;
56
57
writeln!(file, "{}", log_line).map_err(|e| e.to_string())
58
}
59
60
pub fn load_config(app: &AppHandle) -> Result<AppConfig, String> {
61
let path = get_config_path(app)?;
62
if !path.exists() {
63
return Ok(AppConfig::default());
64
}
65
let content = fs::read_to_string(path).map_err(|e| e.to_string())?;
66
if content.trim().is_empty() {
67
return Ok(AppConfig::default());
68
}
69
serde_json::from_str(&content).map_err(|e| e.to_string())
70
}
71
72
pub fn save_config(app: &AppHandle, config: &AppConfig) -> Result<(), String> {
73
let path = get_config_path(app)?;
74
let content = serde_json::to_string_pretty(config).map_err(|e| e.to_string())?;
75
fs::write(path, content).map_err(|e| e.to_string())
76
}
77
78