diff --git a/src/commands.rs b/src/commands.rs index be5ea1f..fcd6fdd 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -5,6 +5,8 @@ use log::info; use ws::{listen, Message, Result as WsResult}; use lazy_static::lazy_static; +use crate::structs::{IntoMessage, LocationPayload}; + enum WsCommand { SendMessage(String), Stop, @@ -60,7 +62,8 @@ impl WsServer { }); } - fn send_message(&self, message: String) { + fn send_message(&self, payload: T) { + let message = payload.into_message(); // Convert the payload to a String self.tx.send(WsCommand::SendMessage(message)).unwrap(); } @@ -97,6 +100,15 @@ pub fn message(payload: String) -> &'static str { "Sending message to all WebSocket clients" } +pub fn location(payload: LocationPayload) -> &'static str { + if let Some(ref server) = *WEBSOCKET_SERVER.lock().unwrap() { + server.send_message(payload); + } else { + info!("WebSocket server is not running."); + } + "sending location to all WebSocket clients" +} + pub fn stop() -> &'static str { if let Some(ref server) = *WEBSOCKET_SERVER.lock().unwrap() { server.stop(); diff --git a/src/lib.rs b/src/lib.rs index b8ef2e3..9eff007 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,5 +30,6 @@ pub fn init() -> Extension { .command("start", commands::start) .command("stop", commands::stop) .command("message", commands::message) + .command("location", commands::location) .finish() } diff --git a/src/structs.rs b/src/structs.rs index bd8b95e..725434c 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -9,6 +9,22 @@ pub struct LocationPayload { pub bearing: f32, } +pub trait IntoMessage { + fn into_message(self) -> String; +} + +impl IntoMessage for String { + fn into_message(self) -> String { + self + } +} + +impl IntoMessage for LocationPayload { + fn into_message(self) -> String { + serde_json::to_string(&self).unwrap() // Convert struct to JSON + } +} + impl FromArma for LocationPayload { fn from_arma(data: String) -> Result { let (latitude, longitude, altitude, bearing) = <(f32, f32, f32, f32)>::from_arma(data)?;