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