aboutsummaryrefslogtreecommitdiff
path: root/src/services/ping.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/services/ping.rs')
-rw-r--r--src/services/ping.rs53
1 files changed, 53 insertions, 0 deletions
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 @@
1use std::sync::Arc;
2
3use axum::{extract::{WebSocketUpgrade, ws::WebSocket, State}, response::Response};
4use tokio::sync::mpsc::Sender;
5use tracing::{debug, error};
6
7use crate::{error::WebolError, AppState};
8
9pub async fn spawn(tx: Sender<String>) -> Result<(), WebolError> {
10 let payload = [0; 8];
11
12 let mut cont = true;
13 while cont {
14 let ping = surge_ping::ping(
15 "192.168.178.28".parse().map_err(WebolError::IpParse)?,
16 &payload
17 ).await;
18
19 if let Err(ping) = ping {
20 cont = matches!(ping, surge_ping::SurgeError::Timeout { .. });
21
22 debug!("{}", cont);
23
24 if !cont {
25 return Err(ping).map_err(WebolError::Ping)
26 }
27
28 } else {
29 let (_, duration) = ping.unwrap();
30 debug!("Ping took {:?}", duration);
31 cont = false;
32 // FIXME: remove unwrap
33 tx.send("Got ping".to_string()).await.unwrap();
34 };
35 }
36
37 Ok(())
38}
39
40pub async fn ws_ping(ws: WebSocketUpgrade, State(_state): State<Arc<AppState>>) -> Response {
41 ws.on_upgrade(handle_socket)
42}
43
44// FIXME: Handle commands through enum
45async fn handle_socket(mut socket: WebSocket) {
46 // TODO: Understand Cow
47
48 // match socket.send(axum::extract::ws::Message::Close(Some(CloseFrame { code: 4000, reason: Cow::Owned("started".to_owned()) }))).await.map_err(WebolError::Axum) {
49 match socket.send(axum::extract::ws::Message::Text("started".to_string())).await.map_err(WebolError::Axum) {
50 Ok(..) => (),
51 Err(err) => { error!("Server Error: {:?}", err) }
52 };
53}