use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PowerSocket { power_rate: f32, on: bool, } impl PowerSocket { pub fn new(power_rate: f32, on: bool) -> Self { Self { power_rate, on } } pub fn is_on(&self) -> bool { self.on } pub fn set_on(&mut self, on: bool) { self.on = on } pub fn get_power(&self) -> f32 { if self.is_on() { self.power_rate } else { 0.0 } } pub fn report(&self) -> String { let state = if self.is_on() { "ON" } else { "OFF" }; let power = self.get_power(); format!("PowerSocket[ {} : {:02.1} ]", state, power) } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Thermometer { temperature: f32, } impl Thermometer { pub fn new(temperature: f32) -> Self { Self { temperature } } pub fn get_temperature(&self) -> f32 { self.temperature } pub fn report(&self) -> String { let temperature = self.get_temperature(); format!("Thermometer[ {:02.1} ]", temperature) } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type")] pub enum Device { PowerSocket(PowerSocket), Thermometer(Thermometer), } impl Device { pub fn report(&self) -> String { match self { Device::PowerSocket(v) => format!("{}", v.report()), Device::Thermometer(v) => format!("{}", v.report()), } } } impl From for Device { fn from(value: PowerSocket) -> Self { Device::PowerSocket(value) } } impl From for Device { fn from(value: Thermometer) -> Self { Device::Thermometer(value) } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Room { devices: HashMap, } impl Room { pub fn new(devices: HashMap) -> Self { Self { devices } } } #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct House { rooms: HashMap, } impl House { pub fn new(rooms: HashMap) -> Self { Self { rooms } } }