rsiot_component_core/component/
multi_thread.rs1use async_trait::async_trait;
2
3use crate::{CmpInOut, ComponentError};
4
5pub struct Component<TConfig, TMsg> {
6 in_out: Option<CmpInOut<TMsg>>,
7 config: Option<TConfig>,
8}
9
10impl<TConfig, TMsg> Component<TConfig, TMsg> {
11 pub fn new(config: impl Into<TConfig>) -> Self {
12 Self {
13 config: Some(config.into()),
14 in_out: None,
15 }
16 }
17}
18
19#[async_trait]
20impl<TConfig, TMsg> IComponent<TMsg> for Component<TConfig, TMsg>
21where
22 TMsg: Send + Sync,
23 Self: IComponentProcess<TConfig, TMsg>,
24 TConfig: Send,
25{
26 fn set_interface(&mut self, in_out: CmpInOut<TMsg>) {
27 self.in_out = Some(in_out);
28 }
29
30 async fn spawn(&mut self) -> Result<(), ComponentError> {
31 let config = self
32 .config
33 .take()
34 .ok_or(ComponentError::Initialization("config not set".into()))?;
35
36 let in_out = self
37 .in_out
38 .take()
39 .ok_or(ComponentError::Initialization("in_out not set".into()))?;
40
41 self.process(config, in_out).await
42 }
43}
44
45#[async_trait]
46pub trait IComponentProcess<TConfig, TMsg> {
47 async fn process(&self, config: TConfig, in_out: CmpInOut<TMsg>) -> Result<(), ComponentError>;
48}
49
50#[async_trait]
51pub trait IComponent<TMsg> {
52 fn set_interface(&mut self, in_out: CmpInOut<TMsg>);
53
54 async fn spawn(&mut self) -> Result<(), ComponentError>;
55}