Skip to main content

csi_webserver_core/
server.rs

1//! HTTP server composition: router construction and TCP serving.
2
3use axum::{
4    Router,
5    routing::{get, post},
6};
7
8use crate::routes;
9use crate::state::AppState;
10
11/// Bind address for the HTTP server (e.g. `"0.0.0.0:3000"`).
12pub struct ServerConfig {
13    pub bind: String,
14}
15
16/// Build the Axum router with all CSI API routes mounted.
17pub fn build_router(state: AppState) -> Router {
18    let device_routes = Router::new()
19        .route("/config", get(routes::config::get_config))
20        .route("/config/reset", post(routes::config::reset_config))
21        .route("/config/wifi", post(routes::config::set_wifi))
22        .route("/config/traffic", post(routes::config::set_traffic))
23        .route("/config/csi", post(routes::config::set_csi))
24        .route(
25            "/config/collection-mode",
26            post(routes::config::set_collection_mode),
27        )
28        .route("/config/output-mode", post(routes::config::set_output_mode))
29        .route("/config/rate", post(routes::config::set_rate))
30        .route("/config/protocol", post(routes::config::set_protocol))
31        .route("/config/io-tasks", post(routes::config::set_io_tasks))
32        .route("/config/csi-delivery", post(routes::config::set_csi_delivery))
33        .route("/control/start", post(routes::control::start_collection))
34        .route("/control/stop", post(routes::control::stop_collection))
35        .route("/control/status", get(routes::control::get_collection_status))
36        .route("/control/reset", post(routes::control::reset_esp32))
37        .route("/control/stats", post(routes::config::show_stats))
38        .route("/info", get(routes::info::get_info))
39        .route("/ws", get(routes::ws::ws_handler));
40
41    Router::new()
42        .route("/", get(|| async { "CSI Server Active" }))
43        .route("/api/devices", get(routes::devices::list_devices))
44        .nest("/api/devices/{id}", device_routes)
45        .with_state(state)
46}
47
48/// Bind `config.bind` and serve until the process exits.
49pub async fn serve(config: ServerConfig, state: AppState) -> std::io::Result<()> {
50    let listener = tokio::net::TcpListener::bind(&config.bind).await?;
51    tracing::info!("CSI server listening on http://{}", config.bind);
52    axum::serve(listener, build_router(state)).await
53}