rsiot/components/cmp_raspberrypi_i2c_master/
rsiot_i2c_driver.rs

1use std::time::Duration;
2
3use async_trait::async_trait;
4use rppal::i2c::I2c;
5use tokio::time::sleep;
6
7use crate::drivers_i2c::RsiotI2cDriverBase;
8
9const DELAY_BETWEEN_REQUESTS: Duration = Duration::from_millis(10);
10
11pub struct RsiotI2cDriver {
12    i2c: I2c,
13}
14
15impl RsiotI2cDriver {
16    pub fn new() -> Result<Self, String> {
17        let i2c = I2c::new().map_err(|e| e.to_string())?;
18        let i2c = Self { i2c };
19        Ok(i2c)
20    }
21}
22
23#[async_trait]
24impl RsiotI2cDriverBase for RsiotI2cDriver {
25    async fn read_platform(
26        &mut self,
27        address: u8,
28        response_size: usize,
29        timeout: Duration,
30    ) -> Result<Vec<u8>, String> {
31        sleep(DELAY_BETWEEN_REQUESTS).await;
32        self.i2c
33            .set_slave_address(address as u16)
34            .map_err(|e| e.to_string())?;
35        self.i2c
36            .set_timeout(timeout.as_millis() as u32)
37            .map_err(|e| e.to_string())?;
38        let mut response = vec![0; response_size];
39        self.i2c.read(&mut response).map_err(|e| e.to_string())?;
40        Ok(response)
41    }
42
43    async fn write_platform(
44        &mut self,
45        address: u8,
46        request: &[u8],
47        timeout: Duration,
48    ) -> Result<(), String> {
49        sleep(DELAY_BETWEEN_REQUESTS).await;
50        self.i2c
51            .set_slave_address(address as u16)
52            .map_err(|e| e.to_string())?;
53        self.i2c
54            .set_timeout(timeout.as_millis() as u32)
55            .map_err(|e| e.to_string())?;
56        self.i2c.write(request).map_err(|e| e.to_string())?;
57        Ok(())
58    }
59
60    async fn write_read_platform(
61        &mut self,
62        address: u8,
63        request: &[u8],
64        response_size: usize,
65        timeout: Duration,
66    ) -> Result<Vec<u8>, String> {
67        sleep(DELAY_BETWEEN_REQUESTS).await;
68        self.i2c
69            .set_slave_address(address as u16)
70            .map_err(|e| e.to_string())?;
71        self.i2c
72            .set_timeout(timeout.as_millis() as u32)
73            .map_err(|e| e.to_string())?;
74        let mut response = vec![0; response_size];
75        self.i2c
76            .write_read(request, &mut response)
77            .map_err(|e| e.to_string())?;
78        Ok(response)
79    }
80}