embedded_hal_bus/i2c/
mutex.rs

1use embedded_hal::i2c::{ErrorType, I2c};
2use std::sync::Mutex;
3
4/// `std` `Mutex`-based shared bus [`I2c`] implementation.
5///
6/// Sharing is implemented with an `std` [`Mutex`]. It allows a single bus across multiple threads,
7/// with finer-grained locking than [`CriticalSectionDevice`](super::CriticalSectionDevice). The downside is that
8/// it is only available in `std` targets.
9#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
10pub struct MutexDevice<'a, T> {
11    bus: &'a Mutex<T>,
12}
13
14impl<'a, T> MutexDevice<'a, T> {
15    /// Create a new `MutexDevice`.
16    #[inline]
17    pub fn new(bus: &'a Mutex<T>) -> Self {
18        Self { bus }
19    }
20}
21
22impl<T> ErrorType for MutexDevice<'_, T>
23where
24    T: I2c,
25{
26    type Error = T::Error;
27}
28
29impl<T> I2c for MutexDevice<'_, T>
30where
31    T: I2c,
32{
33    #[inline]
34    fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> {
35        let bus = &mut *self.bus.lock().unwrap();
36        bus.read(address, read)
37    }
38
39    #[inline]
40    fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Self::Error> {
41        let bus = &mut *self.bus.lock().unwrap();
42        bus.write(address, write)
43    }
44
45    #[inline]
46    fn write_read(
47        &mut self,
48        address: u8,
49        write: &[u8],
50        read: &mut [u8],
51    ) -> Result<(), Self::Error> {
52        let bus = &mut *self.bus.lock().unwrap();
53        bus.write_read(address, write, read)
54    }
55
56    #[inline]
57    fn transaction(
58        &mut self,
59        address: u8,
60        operations: &mut [embedded_hal::i2c::Operation<'_>],
61    ) -> Result<(), Self::Error> {
62        let bus = &mut *self.bus.lock().unwrap();
63        bus.transaction(address, operations)
64    }
65}