rsiot/drivers_i2c/pcf8575/
task_read_inputs.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
use std::{sync::Arc, time::Duration};

use bitvec::prelude::*;
use tokio::{sync::Mutex, time::sleep};

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

use super::{state::State, TPinFnOutput};

/// Чтение и обработка входов
pub struct TaskReadInputs<TMsg, TService, Driver>
where
    TMsg: MsgDataBound,
    TService: ServiceBound,
{
    pub in_out: CmpInOut<TMsg, TService>,
    pub driver: Arc<Mutex<Driver>>,
    pub address: I2cSlaveAddress,
    pub pin_and_fn_output: TPinFnOutput<TMsg>,
    pub state: State,
}

impl<TMsg, TService, Driver> TaskReadInputs<TMsg, TService, Driver>
where
    TMsg: MsgDataBound,
    TService: ServiceBound,
    Driver: RsiotI2cDriverBase,
{
    pub async fn spawn(&self) -> Result<(), String> {
        let mut status_saved = 0u16;
        let status_saved_bits = status_saved.view_bits_mut::<Lsb0>();
        let mut first_cycle = true;

        loop {
            let state = self.state.to_bytes().await;
            let status_current = {
                let mut driver = self.driver.lock().await;
                driver
                    .write_read(self.address, &state, 2, Duration::from_secs(2))
                    .await
                    .map_err(String::from)?
            };
            let status_current_bits = status_current.view_bits::<Lsb0>();
            for (pin, fn_output) in &self.pin_and_fn_output {
                if (status_current_bits[*pin] != status_saved_bits[*pin]) || first_cycle {
                    let msg = fn_output(!status_current_bits[*pin]);
                    status_saved_bits.set(*pin, status_current_bits[*pin]);
                    let Some(msg) = msg else { continue };
                    self.in_out
                        .send_output(msg)
                        .await
                        .map_err(|e| e.to_string())?;
                }
            }
            first_cycle = false;

            sleep(Duration::from_millis(100)).await;
        }
    }
}