vcs-camera-satellite/src/config.rs

57 lines
1.5 KiB
Rust
Raw Normal View History

2024-08-10 12:10:32 -07:00
use config::{Config, FileFormat};
use serde::{Deserialize, Serialize};
use snafu::prelude::*;
use std::fs::File;
use std::io::Write;
use tracing::{info, instrument};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AppConfig {
pub destination_ip: String,
pub destination_port: u32,
2024-08-25 17:17:40 -07:00
pub aspect_ratio: f64,
2024-08-10 12:10:32 -07:00
}
impl Default for AppConfig {
fn default() -> Self {
AppConfig {
destination_ip: "localhost".to_string(),
destination_port: 7891,
2024-08-25 17:17:40 -07:00
aspect_ratio: 16.0 / 9.0,
2024-08-10 12:10:32 -07:00
}
}
}
pub fn load_config() -> AppConfig {
Config::builder()
.add_source(config::File::new("./settings.toml", FileFormat::Toml))
.build()
.and_then(|val| val.try_deserialize())
.unwrap_or_default()
}
#[derive(Debug, Snafu)]
pub enum SaveConfigError {
#[snafu(display("Could not serialize app state: {source}"))]
SerdeError { source: toml::ser::Error },
#[snafu(display("Could not write app state to file: {path}"))]
IoError {
source: std::io::Error,
path: String,
},
}
#[instrument]
pub fn save_config(config: &AppConfig) -> Result<(), SaveConfigError> {
let toml_str = toml::to_string(&config).context(SerdeSnafu)?;
let mut file = File::create("./settings.toml").context(IoSnafu {
path: "./settings.toml",
})?;
file.write_all(toml_str.as_bytes()).context(IoSnafu {
path: "./settings.toml",
})?;
info!("Config file saved successfully");
Ok(())
}