Files
rust-otus/smart-house-web/backend/src/house.rs

103 lines
2.1 KiB
Rust

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<PowerSocket> for Device {
fn from(value: PowerSocket) -> Self {
Device::PowerSocket(value)
}
}
impl From<Thermometer> for Device {
fn from(value: Thermometer) -> Self {
Device::Thermometer(value)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Room {
devices: HashMap<String, Device>,
}
impl Room {
pub fn new(devices: HashMap<String, Device>) -> Self {
Self { devices }
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct House {
rooms: HashMap<String, Room>,
}
impl House {
pub fn new(rooms: HashMap<String, Room>) -> Self {
Self { rooms }
}
}