smart-house-web: в работе

This commit is contained in:
3 changed files with 72 additions and 2 deletions

View File

@@ -8,5 +8,5 @@ tracing = "0.1"
tracing-subscriber = "0.3"
tokio = { version = "1.52", features = ["rt", "rt-multi-thread", "signal", "time"] }
axum = "0.8"
serde = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

View File

@@ -1,4 +1,8 @@
struct PowerSocket {
use serde::{Deserialize, Serialize};
use std::fmt::Display;
#[derive(Debug, Serialize, Deserialize)]
pub struct PowerSocket {
power_rate: f32,
on: bool,
}
@@ -7,4 +11,69 @@ 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) -> impl Display {
let state = if self.is_on() { "ON" } else { "OFF" };
let power = self.get_power();
format!("PowerSocket[ {} : {:02.1} ]", state, power)
}
}
#[derive(Debug, 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) -> impl Display {
let temperature = self.get_temperature();
format!("Thermometer[ {:02.1} ]", temperature)
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum Device {
PowerSocket(PowerSocket),
Thermometer(Thermometer),
}
impl Device {
pub fn report(&self) -> impl Display {
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)
}
}

View File

@@ -34,3 +34,4 @@ mod server;
pub use server::run_server;
mod house;
pub use house::{Device, PowerSocket, Thermometer};