rsiot/components/cmp_esp_i2c_slave/tasks/
output.rs1use std::{sync::Arc, time::Duration};
2
3use tokio::{
4 sync::{mpsc, Mutex},
5 time::sleep,
6};
7
8use crate::message::{Message, MsgDataBound};
9
10use super::super::FnOutput;
11
12pub struct Output<TMsg, TBufferData>
13where
14 TMsg: MsgDataBound,
15{
16 pub output: mpsc::Sender<Message<TMsg>>,
17 pub fn_output: FnOutput<TMsg, TBufferData>,
18 pub fn_output_period: Duration,
19 pub buffer_data: Arc<Mutex<TBufferData>>,
20}
21
22impl<TMsg, TBufferData> Output<TMsg, TBufferData>
23where
24 TMsg: MsgDataBound,
25{
26 pub async fn spawn(self) -> super::Result<()> {
27 loop {
28 let msgs;
29 {
30 let buffer_data = self.buffer_data.lock().await;
31 msgs = (self.fn_output)(&buffer_data);
32 }
33 for msg in msgs {
34 self.output
35 .send(msg)
36 .await
37 .map_err(|e| super::Error::TaskOutput(e.to_string()))?;
38 }
39 sleep(self.fn_output_period).await;
40 }
41 }
42}