66 lines
1.6 KiB
Rust
66 lines
1.6 KiB
Rust
use std::fs;
|
|
|
|
use anyhow::{Context, Result};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{from_str, to_string, to_string_pretty};
|
|
|
|
#[derive(Clone, PartialEq, Eq, Deserialize, Serialize, Debug)]
|
|
pub struct Devices {
|
|
pub plugs: Vec<(String, bool)>,
|
|
pub thermostat: Vec<String>,
|
|
pub thermometer: Vec<String>,
|
|
}
|
|
|
|
impl Devices {
|
|
pub async fn read(file: &str) -> Result<Self> {
|
|
Ok(from_str(
|
|
&fs::read_to_string(file).context(format!("{file}"))?,
|
|
)?)
|
|
}
|
|
|
|
#[allow(unused)]
|
|
pub fn save(&self, file: &str) -> Result<()> {
|
|
fs::write(file, to_string_pretty(self)?)?;
|
|
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
|
|
pub struct DeviceWithName {
|
|
pub id: String,
|
|
pub desc: Option<String>,
|
|
pub toggle: bool,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
|
|
pub struct DevicesWithName {
|
|
pub plugs: Vec<DeviceWithName>,
|
|
pub thermostat: Vec<DeviceWithName>,
|
|
pub temperature_and_humidity: Vec<DeviceWithName>,
|
|
pub dish_washer: Vec<DeviceWithName>,
|
|
pub washing_machines: Vec<DeviceWithName>,
|
|
}
|
|
|
|
impl DevicesWithName {
|
|
pub fn to_json(&self) -> Result<String> {
|
|
Ok(to_string(self)?)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod test {
|
|
use super::Devices;
|
|
use anyhow::Result;
|
|
|
|
#[test]
|
|
fn create_conf() -> Result<()> {
|
|
let devices = Devices {
|
|
plugs: vec![("Dev1".to_string(), true), ("Dev2".to_string(), false)],
|
|
thermostat: Vec::new(),
|
|
thermometer: Vec::new(),
|
|
};
|
|
|
|
devices.save("test_devices.conf")
|
|
}
|
|
}
|