|
| 1 | +use core::cell::RefCell; |
| 2 | +use critical_section::Mutex; |
| 3 | +use embedded_hal::i2c::{ErrorType, I2c}; |
| 4 | + |
| 5 | +/// `critical-section`-based shared bus [`I2c`] implementation. |
| 6 | +/// |
| 7 | +/// Sharing is implemented with a `critical-section` [`Mutex`](critical_section::Mutex). A critical section is taken for |
| 8 | +/// the entire duration of a transaction. This allows sharing a single bus across multiple threads (interrupt priority levels). |
| 9 | +/// The downside is critical sections typically require globally disabling interrupts, so `CriticalSectionDevice` will likely |
| 10 | +/// negatively impact real-time properties, such as interrupt latency. If you can, prefer using |
| 11 | +/// [`RefCellDevice`](super::RefCellDevice) instead, which does not require taking critical sections. |
| 12 | +pub struct CriticalSectionDevice<'a, T> { |
| 13 | + bus: &'a Mutex<RefCell<T>>, |
| 14 | +} |
| 15 | + |
| 16 | +impl<'a, T> CriticalSectionDevice<'a, T> { |
| 17 | + /// Create a new Mutexdevice |
| 18 | + pub fn new(bus: &'a Mutex<RefCell<T>>) -> Self { |
| 19 | + Self { bus } |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +impl<'a, T> ErrorType for CriticalSectionDevice<'a, T> |
| 24 | +where |
| 25 | + T: I2c, |
| 26 | +{ |
| 27 | + type Error = T::Error; |
| 28 | +} |
| 29 | + |
| 30 | +impl<'a, T> I2c for CriticalSectionDevice<'a, T> |
| 31 | +where |
| 32 | + T: I2c, |
| 33 | +{ |
| 34 | + fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> { |
| 35 | + critical_section::with(|cs| { |
| 36 | + let bus = &mut *self.bus.borrow_ref_mut(cs); |
| 37 | + bus.read(address, read) |
| 38 | + }) |
| 39 | + } |
| 40 | + |
| 41 | + fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Self::Error> { |
| 42 | + critical_section::with(|cs| { |
| 43 | + let bus = &mut *self.bus.borrow_ref_mut(cs); |
| 44 | + bus.write(address, write) |
| 45 | + }) |
| 46 | + } |
| 47 | + |
| 48 | + fn write_read( |
| 49 | + &mut self, |
| 50 | + address: u8, |
| 51 | + write: &[u8], |
| 52 | + read: &mut [u8], |
| 53 | + ) -> Result<(), Self::Error> { |
| 54 | + critical_section::with(|cs| { |
| 55 | + let bus = &mut *self.bus.borrow_ref_mut(cs); |
| 56 | + bus.write_read(address, write, read) |
| 57 | + }) |
| 58 | + } |
| 59 | + |
| 60 | + fn transaction( |
| 61 | + &mut self, |
| 62 | + address: u8, |
| 63 | + operations: &mut [embedded_hal::i2c::Operation<'_>], |
| 64 | + ) -> Result<(), Self::Error> { |
| 65 | + critical_section::with(|cs| { |
| 66 | + let bus = &mut *self.bus.borrow_ref_mut(cs); |
| 67 | + bus.transaction(address, operations) |
| 68 | + }) |
| 69 | + } |
| 70 | +} |
0 commit comments