From dcfb83fb2069bfcf4642b03453253e35479bf3da Mon Sep 17 00:00:00 2001 From: fx Date: Tue, 24 Oct 2023 01:15:22 +0200 Subject: first ping impl baseline, doesnt work --- src/services/mod.rs | 1 + src/services/ping.rs | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 src/services/mod.rs create mode 100644 src/services/ping.rs (limited to 'src/services') diff --git a/src/services/mod.rs b/src/services/mod.rs new file mode 100644 index 0000000..a766209 --- /dev/null +++ b/src/services/mod.rs @@ -0,0 +1 @@ +pub mod ping; diff --git a/src/services/ping.rs b/src/services/ping.rs new file mode 100644 index 0000000..6e710ec --- /dev/null +++ b/src/services/ping.rs @@ -0,0 +1,53 @@ +use std::sync::Arc; + +use axum::{extract::{WebSocketUpgrade, ws::WebSocket, State}, response::Response}; +use tokio::sync::mpsc::Sender; +use tracing::{debug, error}; + +use crate::{error::WebolError, AppState}; + +pub async fn spawn(tx: Sender) -> Result<(), WebolError> { + let payload = [0; 8]; + + let mut cont = true; + while cont { + let ping = surge_ping::ping( + "192.168.178.28".parse().map_err(WebolError::IpParse)?, + &payload + ).await; + + if let Err(ping) = ping { + cont = matches!(ping, surge_ping::SurgeError::Timeout { .. }); + + debug!("{}", cont); + + if !cont { + return Err(ping).map_err(WebolError::Ping) + } + + } else { + let (_, duration) = ping.unwrap(); + debug!("Ping took {:?}", duration); + cont = false; + // FIXME: remove unwrap + tx.send("Got ping".to_string()).await.unwrap(); + }; + } + + Ok(()) +} + +pub async fn ws_ping(ws: WebSocketUpgrade, State(_state): State>) -> Response { + ws.on_upgrade(handle_socket) +} + +// FIXME: Handle commands through enum +async fn handle_socket(mut socket: WebSocket) { + // TODO: Understand Cow + + // match socket.send(axum::extract::ws::Message::Close(Some(CloseFrame { code: 4000, reason: Cow::Owned("started".to_owned()) }))).await.map_err(WebolError::Axum) { + match socket.send(axum::extract::ws::Message::Text("started".to_string())).await.map_err(WebolError::Axum) { + Ok(..) => (), + Err(err) => { error!("Server Error: {:?}", err) } + }; +} -- cgit v1.2.3