use config::{Config, FileFormat}; use err_derive::Error; use log::{error, info}; use serde::{Deserialize, Serialize}; use std::fs::File; use std::io::Write; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct AppConfig { pub camera_ip: String, pub camera_port: u32, pub tracker_ip: String, pub tracker_port: u32, pub tracker_refresh_rate_millis: u32, } impl Default for AppConfig { fn default() -> Self { AppConfig { camera_ip: "10.0.0.33".to_string(), camera_port: 8765, tracker_ip: "10.0.0.210".to_string(), tracker_port: 6543, tracker_refresh_rate_millis: 100, } } } pub fn load_config() -> AppConfig { let settings = Config::builder() .add_source(config::File::new("./settings.toml", FileFormat::Toml)) .build(); settings .and_then(|val| val.try_deserialize()) .unwrap_or_default() } #[derive(Error, Debug)] pub enum SaveConfigError { #[error(display = "Could not serialize app state: {:?}", _0)] SerdeError(#[cause] toml::ser::Error), #[error(display = "Could not write app state to file: {:?}", _0)] IoError(#[cause] std::io::Error), } pub fn save_config(config: &AppConfig) -> Result<(), SaveConfigError> { let toml_str = toml::to_string(&config)?; let mut file = File::create("./settings.toml")?; file.write_all(toml_str.as_bytes())?; info!("Config file saved successfully"); Ok(()) }