Skip to content

Commit 987fc68

Browse files
committed
can: Add blocking API with default implementation
1 parent 7c2b810 commit 987fc68

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/blocking/can.rs

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//! Blocking CAN API
2+
3+
/// A blocking CAN interface that is able to transmit and receive frames.
4+
pub trait Can {
5+
/// Associated frame type.
6+
type Frame: crate::can::Frame;
7+
8+
/// Associated error type.
9+
type Error;
10+
11+
/// Puts a frame in the transmit buffer. Blocks until space is available in
12+
/// the transmit buffer.
13+
fn try_transmit(&mut self, frame: &Self::Frame) -> Result<(), Self::Error>;
14+
15+
/// Blocks until a frame was received or an error occured.
16+
fn try_receive(&mut self) -> Result<Self::Frame, Self::Error>;
17+
}
18+
19+
/// Default implementation of `blocking::can::Can` for implementers of `can::Can`
20+
pub trait Default: crate::can::Can {}
21+
22+
impl<S> crate::blocking::can::Can for S
23+
where
24+
S: Default,
25+
{
26+
type Frame = S::Frame;
27+
type Error = S::Error;
28+
29+
fn try_transmit(&mut self, frame: &Self::Frame) -> Result<(), Self::Error> {
30+
let mut replaced_frame;
31+
let mut frame_to_transmit = frame;
32+
while let Some(f) = nb::block!(self.try_transmit(&frame_to_transmit))? {
33+
replaced_frame = f;
34+
frame_to_transmit = &replaced_frame;
35+
}
36+
Ok(())
37+
}
38+
39+
fn try_receive(&mut self) -> Result<Self::Frame, Self::Error> {
40+
nb::block!(self.try_receive())
41+
}
42+
}

src/blocking/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
//! traits. To save boilerplate when that's the case a `Default` marker trait may be provided.
55
//! Implementing that marker trait will opt in your type into a blanket implementation.
66
7+
pub mod can;
78
pub mod delay;
89
pub mod i2c;
910
pub mod rng;

0 commit comments

Comments
 (0)