stm32f1_hal/common/i2c/
i2c_device.rs

1use super::*;
2use crate::common::{bus_device::*, os_trait::Mutex};
3
4pub struct I2cBusDevice<OS, BUS>
5where
6    OS: OsInterface,
7    BUS: I2cBusInterface,
8{
9    slave_addr: Address,
10    speed: HertzU32,
11    bus: Arc<Mutex<OS, BUS>>,
12}
13
14unsafe impl<OS, BUS> Send for I2cBusDevice<OS, BUS>
15where
16    OS: OsInterface,
17    BUS: I2cBusInterface,
18{
19}
20
21impl<OS, BUS> I2cBusDevice<OS, BUS>
22where
23    OS: OsInterface,
24    BUS: I2cBusInterface,
25{
26    pub fn new(bus: Arc<Mutex<OS, BUS>>, slave_addr: Address, speed: HertzU32) -> Self {
27        Self {
28            slave_addr,
29            bus,
30            speed,
31        }
32    }
33}
34
35impl<OS, BUS> BusDevice<u8> for I2cBusDevice<OS, BUS>
36where
37    OS: OsInterface,
38    BUS: I2cBusInterface,
39{
40    #[inline]
41    fn transaction(&mut self, operations: &mut [Operation<'_, u8>]) -> Result<(), BusError> {
42        let mut bus = self.bus.lock();
43        Ok(bus.transaction(self.slave_addr, self.speed, operations)?)
44    }
45}
46
47impl<OS, BUS> BusDeviceWithAddress<u8> for I2cBusDevice<OS, BUS>
48where
49    OS: OsInterface,
50    BUS: I2cBusInterface,
51{
52    fn set_address(&mut self, address: Address) {
53        self.slave_addr = address;
54    }
55}
56
57// ------------------------------------------------------------------
58
59pub struct I2cSoleDevice<BUS>
60where
61    BUS: I2cBusInterface,
62{
63    slave_addr: Address,
64    bus: BUS,
65    speed: HertzU32,
66}
67
68impl<BUS> I2cSoleDevice<BUS>
69where
70    BUS: I2cBusInterface,
71{
72    pub fn new(bus: BUS, slave_addr: Address, speed: HertzU32) -> Self {
73        Self {
74            bus,
75            slave_addr,
76            speed,
77        }
78    }
79}
80
81unsafe impl<BUS> Send for I2cSoleDevice<BUS> where BUS: I2cBusInterface {}
82
83impl<BUS> BusDevice<u8> for I2cSoleDevice<BUS>
84where
85    BUS: I2cBusInterface,
86{
87    #[inline]
88    fn transaction(&mut self, operations: &mut [Operation<'_, u8>]) -> Result<(), BusError> {
89        Ok(self
90            .bus
91            .transaction(self.slave_addr, self.speed, operations)?)
92    }
93}
94
95impl<BUS> BusDeviceWithAddress<u8> for I2cSoleDevice<BUS>
96where
97    BUS: I2cBusInterface,
98{
99    fn set_address(&mut self, address: Address) {
100        self.slave_addr = address;
101    }
102}
103
104// ------------------------------------------------------------------
105
106impl From<Error> for BusError {
107    fn from(value: Error) -> Self {
108        match value {
109            Error::Busy => Self::Busy,
110            Error::ArbitrationLoss => Self::ArbitrationLoss,
111            Error::NoAcknowledge(_) => Self::NoAcknowledge,
112            Error::Timeout => Self::Timeout,
113            _ => Self::Other,
114        }
115    }
116}