-
Notifications
You must be signed in to change notification settings - Fork 185
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
e-h-bus: Adding AtomicDevice
for I2C and SPI bus sharing in multiple interrupt contexts
#579
Closed
Closed
Changes from 6 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
ac2ec22
Adding AtomicDevice for I2C bus sharing
ryan-summers 91b31f2
fixing format
ryan-summers b0cd0c3
Fixing test
ryan-summers 219fcaf
Fixing clippy, docs
ryan-summers 7218137
Cleaning up and fixing bounds
ryan-summers a3d01e1
Fixing implementation
ryan-summers 735b635
Adding SPI atomic implementation
ryan-summers 6c0cbad
Fixing docs in SPI
ryan-summers cf6db34
Fixing unrelated async feature issues
ryan-summers 034df2d
Merge remote-tracking branch 'origin/master' into feature/hal-bus-mutex
ryan-summers 5a2846b
Updating CHANGELOG
ryan-summers File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
use core::cell::UnsafeCell; | ||
use embedded_hal::i2c::{Error, ErrorKind, ErrorType, I2c}; | ||
|
||
/// `UnsafeCell`-based shared bus [`I2c`] implementation. | ||
/// | ||
/// Sharing is implemented with a `UnsafeCell`. This means it has low overhead, similar to [`crate::i2c::RefCellDevice`] instances, but they are `Send`. | ||
/// so it only allows sharing across multiple threads (interrupt priority levels). When attempting | ||
/// to preempt usage of the bus, a `AtomicError::Busy` error is returned. | ||
/// | ||
/// This primitive is particularly well-suited for applications that have external arbitration | ||
/// rules, such as the RTIC framework. | ||
/// | ||
/// # Examples | ||
/// | ||
/// Assuming there is a pressure sensor with address `0x42` on the same bus as a temperature sensor | ||
/// with address `0x20`; [`AtomicDevice`] can be used to give access to both of these sensors | ||
/// from a single `i2c` instance. | ||
/// | ||
/// ``` | ||
/// use embedded_hal_bus::i2c; | ||
/// use core::cell::UnsafeCell; | ||
/// # use embedded_hal::i2c::{self as hali2c, SevenBitAddress, TenBitAddress, I2c, Operation, ErrorKind}; | ||
/// # pub struct Sensor<I2C> { | ||
/// # i2c: I2C, | ||
/// # address: u8, | ||
/// # } | ||
/// # impl<I2C: I2c> Sensor<I2C> { | ||
/// # pub fn new(i2c: I2C, address: u8) -> Self { | ||
/// # Self { i2c, address } | ||
/// # } | ||
/// # } | ||
/// # type PressureSensor<I2C> = Sensor<I2C>; | ||
/// # type TemperatureSensor<I2C> = Sensor<I2C>; | ||
/// # pub struct I2c0; | ||
/// # #[derive(Debug, Copy, Clone, Eq, PartialEq)] | ||
/// # pub enum Error { } | ||
/// # impl hali2c::Error for Error { | ||
/// # fn kind(&self) -> hali2c::ErrorKind { | ||
/// # ErrorKind::Other | ||
/// # } | ||
/// # } | ||
/// # impl hali2c::ErrorType for I2c0 { | ||
/// # type Error = Error; | ||
/// # } | ||
/// # impl I2c<SevenBitAddress> for I2c0 { | ||
/// # fn transaction(&mut self, address: u8, operations: &mut [Operation<'_>]) -> Result<(), Self::Error> { | ||
/// # Ok(()) | ||
/// # } | ||
/// # } | ||
/// # struct Hal; | ||
/// # impl Hal { | ||
/// # fn i2c(&self) -> I2c0 { | ||
/// # I2c0 | ||
/// # } | ||
/// # } | ||
/// # let hal = Hal; | ||
/// | ||
/// let i2c = hal.i2c(); | ||
/// let i2c_unsafe_cell = UnsafeCell::new(i2c); | ||
/// let mut temperature_sensor = TemperatureSensor::new( | ||
/// i2c::AtomicDevice::new(&i2c_unsafe_cell), | ||
/// 0x20, | ||
/// ); | ||
/// let mut pressure_sensor = PressureSensor::new( | ||
/// i2c::AtomicDevice::new(&i2c_unsafe_cell), | ||
/// 0x42, | ||
/// ); | ||
/// ``` | ||
pub struct AtomicDevice<'a, T> { | ||
bus: &'a UnsafeCell<T>, | ||
busy: portable_atomic::AtomicBool, | ||
} | ||
|
||
#[derive(Debug, Copy, Clone)] | ||
/// Wrapper type for errors originating from the atomically-checked I2C bus manager. | ||
pub enum AtomicError<T: Error> { | ||
/// This error is returned if the I2C bus was already in use when an operation was attempted, | ||
/// which indicates that the driver requirements are not being met with regard to | ||
/// synchronization. | ||
Busy, | ||
|
||
/// An I2C-related error occurred, and the internal error should be inspected. | ||
Other(T), | ||
} | ||
|
||
impl<T: Error> Error for AtomicError<T> { | ||
fn kind(&self) -> ErrorKind { | ||
match self { | ||
AtomicError::Other(e) => e.kind(), | ||
_ => ErrorKind::Other, | ||
} | ||
} | ||
} | ||
|
||
unsafe impl<'a, T> Send for AtomicDevice<'a, T> {} | ||
|
||
impl<'a, T> AtomicDevice<'a, T> | ||
where | ||
T: I2c, | ||
{ | ||
/// Create a new `AtomicDevice`. | ||
#[inline] | ||
pub fn new(bus: &'a UnsafeCell<T>) -> Self { | ||
Self { | ||
bus, | ||
busy: portable_atomic::AtomicBool::from(false), | ||
} | ||
} | ||
|
||
fn lock<R, F>(&self, f: F) -> Result<R, AtomicError<T::Error>> | ||
where | ||
F: FnOnce(&mut T) -> Result<R, <T as ErrorType>::Error>, | ||
{ | ||
self.busy | ||
.compare_exchange( | ||
false, | ||
true, | ||
core::sync::atomic::Ordering::SeqCst, | ||
core::sync::atomic::Ordering::SeqCst, | ||
) | ||
.map_err(|_| AtomicError::<T::Error>::Busy)?; | ||
|
||
let result = f(unsafe { &mut *self.bus.get() }); | ||
|
||
self.busy.store(false, core::sync::atomic::Ordering::SeqCst); | ||
|
||
result.map_err(AtomicError::Other) | ||
} | ||
} | ||
|
||
impl<'a, T> ErrorType for AtomicDevice<'a, T> | ||
where | ||
T: I2c, | ||
{ | ||
type Error = AtomicError<T::Error>; | ||
} | ||
|
||
impl<'a, T> I2c for AtomicDevice<'a, T> | ||
where | ||
T: I2c, | ||
{ | ||
#[inline] | ||
fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> { | ||
self.lock(|bus| bus.read(address, read)) | ||
} | ||
|
||
#[inline] | ||
fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Self::Error> { | ||
self.lock(|bus| bus.write(address, write)) | ||
} | ||
|
||
#[inline] | ||
fn write_read( | ||
&mut self, | ||
address: u8, | ||
write: &[u8], | ||
read: &mut [u8], | ||
) -> Result<(), Self::Error> { | ||
self.lock(|bus| bus.write_read(address, write, read)) | ||
} | ||
|
||
#[inline] | ||
fn transaction( | ||
&mut self, | ||
address: u8, | ||
operations: &mut [embedded_hal::i2c::Operation<'_>], | ||
) -> Result<(), Self::Error> { | ||
self.lock(|bus| bus.transaction(address, operations)) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would expect this to be
impl Sync
, but for some reason if I only do Sync, my test application complains that theAtomicDevice
cannot be shared across threads safely.