rsiot/components/shared_tasks/cmp_websocket_client_general/tasks/
connection_state.rs1use tokio::sync::mpsc;
2
3use crate::{
4 executor::CmpInOut,
5 message::{Message, MsgDataBound},
6};
7
8pub struct ConnectionState<TMsg>
12where
13 TMsg: MsgDataBound,
14{
15 pub input: mpsc::Receiver<bool>,
17 pub output: CmpInOut<TMsg>,
19 pub fn_connection_state: fn(bool) -> Option<Message<TMsg>>,
21}
22
23impl<TMsg> ConnectionState<TMsg>
24where
25 TMsg: MsgDataBound,
26{
27 pub async fn spawn(mut self) -> super::Result<()> {
29 create_msg_and_send(false, self.fn_connection_state, &self.output).await?;
30 while let Some(state) = self.input.recv().await {
31 create_msg_and_send(state, self.fn_connection_state, &self.output).await?;
32 }
33 Err(super::Error::TaskConnectionState)
34 }
35}
36
37async fn create_msg_and_send<TMsg>(
38 state: bool,
39 fn_connection_state: fn(bool) -> Option<Message<TMsg>>,
40 output: &CmpInOut<TMsg>,
41) -> super::Result<()>
42where
43 TMsg: MsgDataBound,
44{
45 let msg = (fn_connection_state)(state);
46 let Some(msg) = msg else { return Ok(()) };
47 output
48 .send_output(msg)
49 .await
50 .map_err(|_| super::Error::TokioSyncMpsc)
51}