HomeServer/src/devices.rs

52 lines
1.1 KiB
Rust
Raw Normal View History

2023-09-19 08:52:12 +00:00
use std::fs;
2023-10-10 09:05:51 +00:00
use anyhow::{Context, Result};
2023-09-19 08:52:12 +00:00
use serde::{Deserialize, Serialize};
2023-09-21 05:30:39 +00:00
use serde_json::{from_str, to_string, to_string_pretty};
2023-09-19 08:52:12 +00:00
#[derive(Clone, PartialEq, Eq, Deserialize, Serialize, Debug)]
pub struct Devices {
2023-09-22 05:43:56 +00:00
pub plugs: Vec<(String, bool)>,
2023-09-19 08:52:12 +00:00
}
impl Devices {
pub async fn read(file: &str) -> Result<Self> {
2023-10-10 09:05:51 +00:00
Ok(from_str(
&fs::read_to_string(file).context(format!("{file}"))?,
)?)
2023-09-19 08:52:12 +00:00
}
2023-09-19 09:18:22 +00:00
#[allow(unused)]
2023-09-19 08:52:12 +00:00
pub fn save(&self, file: &str) -> Result<()> {
2023-09-19 09:18:22 +00:00
fs::write(file, to_string_pretty(self)?)?;
2023-09-19 08:52:12 +00:00
Ok(())
}
}
2023-09-21 08:08:23 +00:00
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct DevicesWithName {
2023-09-22 05:43:56 +00:00
pub plugs: Vec<(String, Option<String>, bool)>,
2023-09-21 08:08:23 +00:00
}
impl DevicesWithName {
pub fn to_json(&self) -> Result<String> {
Ok(to_string(self)?)
}
}
2023-09-19 08:52:12 +00:00
#[cfg(test)]
mod test {
use super::Devices;
use anyhow::Result;
#[test]
fn create_conf() -> Result<()> {
let devices = Devices {
2023-09-22 05:43:56 +00:00
plugs: vec![("Dev1".to_string(), true), ("Dev2".to_string(), false)],
2023-09-19 08:52:12 +00:00
};
2023-09-19 09:18:22 +00:00
devices.save("test_devices.conf")
2023-09-19 08:52:12 +00:00
}
}