Compare commits
11 Commits
master
...
feat/smart
| Author | SHA1 | Date | |
|---|---|---|---|
| 3358f96cbb | |||
| 1a09272b57 | |||
| f691d2250f | |||
| 360fc6b6bb | |||
| 50c8e1e9d6 | |||
| 5a27637bed | |||
| 66aa05c954 | |||
| 5a87aaecad | |||
| 76266f17cf | |||
| 162b5ffefc | |||
| 967698b0bc |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,2 +1,3 @@
|
||||
/.idea/
|
||||
/**/.DS_Store
|
||||
/tmp/
|
||||
|
||||
2
smart-house-web/.gitignore
vendored
Normal file
2
smart-house-web/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/target/
|
||||
/Cargo.lock
|
||||
15
smart-house-web/Cargo.toml
Normal file
15
smart-house-web/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["backend"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = "z"
|
||||
strip = "symbols"
|
||||
lto = "fat"
|
||||
panic = "abort"
|
||||
codegen-units = 1
|
||||
overflow-checks = false
|
||||
debug-assertions = false
|
||||
incremental = false
|
||||
|
||||
[workspace.dependencies]
|
||||
40
smart-house-web/README.md
Normal file
40
smart-house-web/README.md
Normal file
@@ -0,0 +1,40 @@
|
||||
# ДЗ 2026-04-28 - Веб-сервис умного дома
|
||||
|
||||
## Цель:
|
||||
|
||||
Превращаем умный дом в веб-сервис.
|
||||
|
||||
## Срок:
|
||||
|
||||
Сдать до: **2026-05-25**
|
||||
|
||||
## Описание/Пошаговая инструкция выполнения домашнего задания:
|
||||
|
||||
Реализовать backend сервис для управления умным домом и frontend приложение для взаимодействия с ним.
|
||||
|
||||
- Технология взаимодействия с backend сервисом (gRPC, REST, GraphQL, ...) выбирается произвольно.
|
||||
|
||||
API backend сервиса предоставляет доступ ко всему базовому функционалу библиотеки умного дома:
|
||||
|
||||
- [ ] Добавление/удаление/перечисление комнат в доме и получение информации о конкретной комнате.
|
||||
- [ ] Добавление/удаление/перечисление устройств в комнате и получение информации о конкретном устройстве.
|
||||
- [ ] Получение отчёта о доме.
|
||||
- [ ] Присутствуют функциональные тесты, которые общаются с backend-ом и проверяют его ответы.
|
||||
|
||||
Frontend приложение:
|
||||
|
||||
- [ ] Отображает список комнат в доме.
|
||||
- [ ] Позволяет перейти к конкретной комнате или добавить новую комнату.
|
||||
- [ ] Отображает список устройств в комнате.
|
||||
- [ ] Позволяет перейти к конкретному устройству или добавить новое устройство.
|
||||
- [ ] Позволяет запросить отчёт о состоянии дома.
|
||||
|
||||
**Критерии оценки:**
|
||||
|
||||
- Workspace успешно собирается.
|
||||
- Приложения-примеры успешно выполняются.
|
||||
- Команды cargo clippy, и cargo fmt --check не выводят ошибок и предупреждений.
|
||||
|
||||
## Демо
|
||||
|
||||
**TBD**
|
||||
15
smart-house-web/backend/Cargo.toml
Normal file
15
smart-house-web/backend/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "backend"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = "0.3"
|
||||
tokio = { version = "1.52", features = ["rt", "rt-multi-thread", "signal", "time"] }
|
||||
axum = "0.8"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
|
||||
[dev-dependencies]
|
||||
hyper = "1.9.0"
|
||||
118
smart-house-web/backend/src/house.rs
Normal file
118
smart-house-web/backend/src/house.rs
Normal file
@@ -0,0 +1,118 @@
|
||||
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, Default, 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 }
|
||||
}
|
||||
|
||||
pub fn rooms(&self) -> Vec<String> {
|
||||
let mut output = Vec::with_capacity(self.rooms.len());
|
||||
for (room, _) in self.rooms.iter() {
|
||||
output.push(room.into());
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
pub fn add_room(&mut self, name: String) {
|
||||
self.rooms.insert(name, Room::default());
|
||||
}
|
||||
|
||||
pub fn drop_room(&mut self, name: &str) {
|
||||
self.rooms.remove(name);
|
||||
}
|
||||
}
|
||||
47
smart-house-web/backend/src/lib.rs
Normal file
47
smart-house-web/backend/src/lib.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
/// Ошибка инициализации логгера
|
||||
const CODE_LOGGER_INITIALIZATION_ERROR: i32 = 1;
|
||||
|
||||
/// Ошибка инициализации рантайма Tokio
|
||||
const CODE_TOKIO_RUNTIME_CREATION_ERROR: i32 = 2;
|
||||
|
||||
/// Ошибка привязки слушателя
|
||||
const CODE_LISTENER_BINDING_ERROR: i32 = 3;
|
||||
|
||||
/// Ошибка запуска сервера
|
||||
const CODE_STARTIG_SERVER_ERROR: i32 = 4;
|
||||
|
||||
/// Ошибка установки обработчика сигнала завершения
|
||||
const CODE_CTRL_C_SIGNAL_INSTALL_ERROR: i32 = 5;
|
||||
|
||||
/// Инициализация логирования
|
||||
pub fn init_logger() {
|
||||
use std::process::exit;
|
||||
use tracing::{Level, trace};
|
||||
use tracing_subscriber::{
|
||||
Layer, filter::Targets, fmt::layer, layer::SubscriberExt, registry, util::SubscriberInitExt,
|
||||
};
|
||||
|
||||
let layer = layer()
|
||||
.compact()
|
||||
.with_thread_names(true)
|
||||
.with_file(false)
|
||||
.with_line_number(false)
|
||||
.with_filter(
|
||||
Targets::new()
|
||||
.with_target("axum::serve", Level::INFO)
|
||||
.with_default(Level::TRACE),
|
||||
)
|
||||
.boxed();
|
||||
if let Err(e) = registry().with(vec![layer]).try_init() {
|
||||
eprintln!("Logger initialization failed: {:?}", e);
|
||||
exit(CODE_LOGGER_INITIALIZATION_ERROR);
|
||||
} else {
|
||||
trace!("Logger succesfully initialized");
|
||||
}
|
||||
}
|
||||
|
||||
mod server;
|
||||
pub use server::run_server;
|
||||
|
||||
mod house;
|
||||
pub use house::{Device, House, PowerSocket, Room, Thermometer};
|
||||
6
smart-house-web/backend/src/main.rs
Normal file
6
smart-house-web/backend/src/main.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
use backend::{init_logger, run_server};
|
||||
|
||||
fn main() {
|
||||
init_logger();
|
||||
run_server();
|
||||
}
|
||||
101
smart-house-web/backend/src/server.rs
Normal file
101
smart-house-web/backend/src/server.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
use axum::routing::{delete, get, put};
|
||||
use std::{
|
||||
process::exit,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::{error, info};
|
||||
|
||||
use crate::House;
|
||||
|
||||
/// Запуск сервера
|
||||
pub fn run_server() {
|
||||
let runtime = match tokio::runtime::Builder::new_multi_thread()
|
||||
.name("tokio")
|
||||
.thread_name_fn(|| {
|
||||
static LAST_ID: AtomicUsize = AtomicUsize::new(0);
|
||||
let id = LAST_ID.fetch_add(1, Ordering::SeqCst);
|
||||
format!("tkwr-{id}")
|
||||
})
|
||||
.worker_threads(2)
|
||||
.thread_stack_size(256 * 1024)
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
Ok(runtime) => runtime,
|
||||
Err(e) => {
|
||||
error!("Failed to create Tokio runtime: {:?}", e);
|
||||
exit(crate::CODE_TOKIO_RUNTIME_CREATION_ERROR);
|
||||
}
|
||||
};
|
||||
runtime.block_on(server_main());
|
||||
}
|
||||
|
||||
/// Тип состояния
|
||||
type ServerState = Arc<RwLock<House>>;
|
||||
|
||||
/// Основная функция сервера
|
||||
async fn server_main() {
|
||||
let state: ServerState = Arc::new(RwLock::new(House::default()));
|
||||
|
||||
let app = axum::Router::new()
|
||||
// Тестовый эндпоинт для экспериментов
|
||||
.route("/debug", get(debug::debug))
|
||||
// API комнат
|
||||
.route("/rooms", get(rooms::get_rooms))
|
||||
.route("/room", put(rooms::add_room))
|
||||
.route("/room/{name}", delete(rooms::remove_room))
|
||||
// TODO
|
||||
.with_state(state)
|
||||
.fallback(fallback);
|
||||
let addr = "127.0.0.1:8080";
|
||||
let listener = match tokio::net::TcpListener::bind(addr).await {
|
||||
Ok(listener) => listener,
|
||||
Err(e) => {
|
||||
error!("Failed to bind listener to {}: {:?}", addr, e);
|
||||
exit(crate::CODE_LISTENER_BINDING_ERROR);
|
||||
}
|
||||
};
|
||||
info!("Starting server at {}...", addr);
|
||||
if let Err(e) = axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown_signal())
|
||||
.await
|
||||
{
|
||||
error!("Failed to start server: {:?}", e);
|
||||
exit(crate::CODE_STARTIG_SERVER_ERROR);
|
||||
};
|
||||
info!("Shutdown server");
|
||||
}
|
||||
|
||||
/// Эндпоинт по-умолчанию
|
||||
async fn fallback() -> axum::response::Response {
|
||||
use axum::response::IntoResponse;
|
||||
(axum::http::StatusCode::NOT_FOUND, "404 NOT FOUND").into_response()
|
||||
}
|
||||
|
||||
/// Аккуратное завершение работы сервера
|
||||
async fn shutdown_signal() {
|
||||
// let timeout = async {
|
||||
// tokio::time::sleep(std::time::Duration::from_secs(10)).await;
|
||||
// info!("10 seconds timeout expired");
|
||||
// };
|
||||
let ctrl_c = async {
|
||||
tokio::signal::ctrl_c().await.map_err(|e| {
|
||||
error!("Can't install Ctrl+C signal handler: {:?}", e);
|
||||
exit(crate::CODE_CTRL_C_SIGNAL_INSTALL_ERROR);
|
||||
});
|
||||
info!("Ctrl+C pressed");
|
||||
};
|
||||
let pending = std::future::pending::<()>();
|
||||
tokio::select! {
|
||||
// _ = timeout => {},
|
||||
_ = ctrl_c => {},
|
||||
_ = pending => {},
|
||||
}
|
||||
}
|
||||
|
||||
mod debug;
|
||||
mod rooms;
|
||||
5
smart-house-web/backend/src/server/debug.rs
Normal file
5
smart-house-web/backend/src/server/debug.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
use axum::{Json, extract::State};
|
||||
|
||||
pub async fn debug(State(_server_state): State<super::ServerState>) -> Json<(String, String)> {
|
||||
("ONE".into(), "TWO".into()).into()
|
||||
}
|
||||
25
smart-house-web/backend/src/server/rooms.rs
Normal file
25
smart-house-web/backend/src/server/rooms.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
};
|
||||
|
||||
pub async fn get_rooms(State(server_state): State<super::ServerState>) -> Json<Vec<String>> {
|
||||
server_state.read().await.rooms().into()
|
||||
}
|
||||
|
||||
pub async fn add_room(
|
||||
State(server_state): State<super::ServerState>,
|
||||
Json(name): Json<String>,
|
||||
) -> StatusCode {
|
||||
server_state.write().await.add_room(name);
|
||||
StatusCode::CREATED
|
||||
}
|
||||
|
||||
pub async fn remove_room(
|
||||
State(server_state): State<super::ServerState>,
|
||||
Path(name): Path<String>,
|
||||
) -> StatusCode {
|
||||
server_state.write().await.drop_room(&name);
|
||||
StatusCode::ACCEPTED
|
||||
}
|
||||
14
smart-house-web/backend/test.http
Normal file
14
smart-house-web/backend/test.http
Normal file
@@ -0,0 +1,14 @@
|
||||
### DEBUG
|
||||
GET http://localhost:8080/debug
|
||||
|
||||
### list rooms
|
||||
GET http://localhost:8080/rooms
|
||||
|
||||
### add room
|
||||
PUT http://localhost:8080/room
|
||||
Content-Type: application/json
|
||||
|
||||
"ROOM"
|
||||
|
||||
### drop room
|
||||
DELETE http://localhost:8080/room/ROOM
|
||||
4
smart-house-web/backend/tests/api_tests.rs
Normal file
4
smart-house-web/backend/tests/api_tests.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn smoke() {
|
||||
println!("Hello test!")
|
||||
}
|
||||
Reference in New Issue
Block a user