rsiot/drivers_i2c/general/
device.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::sync::Arc;
use std::time::Duration;

use tokio::sync::Mutex;
use tracing::warn;

use crate::{
    drivers_i2c::RsiotI2cDriverBase,
    executor::CmpInOut,
    message::{MsgDataBound, ServiceBound},
    serde_utils::postcard_serde,
};

use super::Config;

/// Устройство I2C
pub struct Device<TMsg, TService, TDriver>
where
    TMsg: MsgDataBound,
    TService: ServiceBound,
    TDriver: RsiotI2cDriverBase,
{
    /// Внутренняя шина сообщений
    pub msg_bus: CmpInOut<TMsg, TService>,

    /// Конфигурация
    pub config: Config<TMsg>,

    /// Драйвер I2C
    pub driver: Arc<Mutex<TDriver>>,
}

impl<TMsg, TService, TDriver> Device<TMsg, TService, TDriver>
where
    TMsg: MsgDataBound + 'static,
    TService: ServiceBound,
    TDriver: RsiotI2cDriverBase + 'static,
{
    /// Запуск на выполнение
    pub async fn spawn(mut self) {
        while let Ok(msg) = self.msg_bus.recv_input().await {
            let req = (self.config.fn_input)(&msg);
            let req = match req {
                Ok(val) => val,
                Err(err) => {
                    warn!("Error: {}", err);
                    continue;
                }
            };
            let Some(req) = req else { continue };
            let response;
            {
                let mut driver = self.driver.lock().await;
                response = driver
                    .write_read(
                        self.config.address,
                        &req,
                        postcard_serde::MESSAGE_LEN,
                        Duration::from_millis(500),
                    )
                    .await
            }
            let response = match response {
                Ok(val) => val,
                Err(err) => {
                    warn!("Error: {}", err);
                    continue;
                }
            };
            let _msg = (self.config.fn_output)(response);
        }
    }
}