Created
October 19, 2018 09:32
-
-
Save ryankurte/7e2caec8dd2f59ab28983457daaab50b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
extern crate embedded_hal; | |
use embedded_hal::blocking::spi::{Write, Transfer}; | |
extern crate embedded_hal_mock; | |
use embedded_hal_mock::MockError; | |
use embedded_hal_mock::spi::{Mock as SpiMock, Transaction as SpiTransaction}; | |
enum Operation<'a> { | |
Write(&'a [u8]), | |
Transfer(&'a mut[u8]), | |
Handle(&'a Fn(&Option<&[u8]>) -> bool) | |
} | |
trait Transactional { | |
type Error; | |
fn transaction(&mut self, transaction: &mut [Operation])-> Result<(), Self::Error>; | |
} | |
impl Transactional for SpiMock { | |
type Error = MockError; | |
fn transaction<'a>(&mut self, transaction: &mut [Operation]) -> Result<(), Self::Error>{ | |
println!("Starting transaction"); | |
let mut last = None; | |
for o in transaction { | |
last = match o { | |
Operation::Write(ref w) => { self.write(w)?; None }, | |
Operation::Transfer(ref mut d) => Some(self.transfer(d)?), | |
Operation::Handle(ref mut f) => { | |
if f(&last) { | |
break; | |
} | |
None | |
} | |
}; | |
} | |
println!("Finalising transaction"); | |
Ok(()) | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn it_works() { | |
let mut m = SpiMock::new(); | |
m.expect(vec![ | |
SpiTransaction::write(vec![0xde, 0xad]), | |
SpiTransaction::transfer(vec![0u8; 2], vec![1u8; 2]), | |
]); | |
let mut values = vec![0u8; 2]; | |
m.transaction(&mut [ | |
Operation::Write(&[0xde, 0xad]), | |
Operation::Transfer(&mut values), | |
Operation::Handle(&|d: &Option<&[u8]>| { d.unwrap()[0] != 0 }), | |
Operation::Write(&[0xde, 0xad]), | |
]).unwrap(); | |
assert_eq!(2 + 2, 4); | |
m.done(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Neat! What does "Handle()" allow here?