Skip to content

Added transactional SPI interface #191

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

Merged
merged 3 commits into from
Oct 28, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/blocking/spi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,52 @@ pub mod write_iter {
}
}
}

/// Operation for transactional SPI trait
///
/// This allows composition of SPI operations into a single bus transaction
#[derive(Debug, PartialEq)]
pub enum Operation<'a, W: 'static> {
/// Write data from the provided buffer, discarding read data
Write(&'a [W]),
/// Write data out while reading data into the provided buffer
Transfer(&'a mut [W]),
}

/// Transactional trait allows multiple actions to be executed
/// as part of a single SPI transaction
pub trait Transactional<W: 'static> {
/// Associated error type
type Error;

/// Execute the provided transactions
fn try_exec<'a>(&mut self, operations: &mut [Operation<'a, W>]) -> Result<(), Self::Error>;
}

/// Blocking transactional impl over spi::Write and spi::Transfer
pub mod transactional {
use super::{Operation, Transfer, Write};

/// Default implementation of `blocking::spi::Transactional<W>` for implementers of
/// `spi::Write<W>` and `spi::Transfer<W>`
pub trait Default<W>: Write<W> + Transfer<W> {}

impl<W: 'static, E, S> super::Transactional<W> for S
where
S: self::Default<W> + Write<W, Error = E> + Transfer<W, Error = E>,
W: Copy + Clone,
{
type Error = E;

fn try_exec<'a>(&mut self, operations: &mut [super::Operation<'a, W>]) -> Result<(), E> {
for op in operations {
match op {
Operation::Write(w) => self.try_write(w)?,
Operation::Transfer(t) => self.try_transfer(t).map(|_| ())?,
}
}

Ok(())
}
}
}