Skip to content

Commit

Permalink
feat: Avoid using nb in uart and twai. Udpate examples and tests to a…
Browse files Browse the repository at this point in the history
…void using block!
  • Loading branch information
SergioGasquez committed Jan 3, 2025
1 parent e8c9dc3 commit 5c0ad5b
Show file tree
Hide file tree
Showing 23 changed files with 221 additions and 145 deletions.
1 change: 0 additions & 1 deletion esp-hal/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ esp-synopsys-usb-otg = { version = "0.4.2", optional = true, features = ["fs
fugit = "0.3.7"
instability = "0.3"
log = { version = "0.4.22", optional = true }
nb = "1.1.0"
paste = "1.0.15"
portable-atomic = { version = "1.9.0", default-features = false }
procmacros = { version = "0.15.0", package = "esp-hal-procmacros", path = "../esp-hal-procmacros" }
Expand Down
6 changes: 5 additions & 1 deletion esp-hal/src/analog/adc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@
//! let mut delay = Delay::new();
//!
//! loop {
//! let pin_value: u16 = nb::block!(adc1.read_oneshot(&mut pin)).unwrap();
//! let pin_value: u16 = loop {
//! if let Some(value) = adc1.read_oneshot(&mut pin) {
//! break value;
//! }
//! };
//!
//! delay.delay_millis(1500);
//! }
Expand Down
10 changes: 6 additions & 4 deletions esp-hal/src/hmac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@
//!
//! [HMAC]: https://github.com/esp-rs/esp-hal/blob/main/examples/src/bin/hmac.rs
use core::convert::Infallible;

use crate::{
peripheral::{Peripheral, PeripheralRef},
peripherals::HMAC,
Expand Down Expand Up @@ -175,8 +173,12 @@ impl<'d> Hmac<'d> {

let msg_len = self.byte_written as u64;

nb::block!(self.write_data(&[0x80])).unwrap();
nb::block!(self.flush_data()).unwrap();
if self.write_data(&[0x80]).is_none() {
return None;
}
if self.flush_data().is_none() {
return None;
}
self.next_command();
debug_assert!(self.byte_written % 4 == 0);

Expand Down
7 changes: 5 additions & 2 deletions esp-hal/src/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,13 @@
/// Attenuation::Attenuation11dB
/// );
/// let mut adc1 = Adc::<ADC1>::new(peripherals.ADC1, adc1_config);
/// let pin_value: u16 = nb::block!(adc1.read_oneshot(&mut adc1_pin)).unwrap();
/// let pin_value: u16 = loop {
/// if let Some(value) adc1.read_oneshot(&mut adc1_pin) {
/// break value;
/// }
/// };
/// rng.read(&mut buf);
/// true_rand = rng.random();
/// let pin_value: u16 = nb::block!(adc1.read_oneshot(&mut adc1_pin)).unwrap();
/// # }
/// ```
use core::marker::PhantomData;
Expand Down
2 changes: 0 additions & 2 deletions esp-hal/src/rsa/esp32cX.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use core::convert::Infallible;

use crate::rsa::{
implement_op,
Multi,
Expand Down
21 changes: 10 additions & 11 deletions esp-hal/src/sha.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,22 +41,21 @@
//! // desired length
//! let mut output = [0u8; 32];
//!
//! while !source_data.is_empty() {
//! // All the HW Sha functions are infallible so unwrap is fine to use if
//! // you use block!
//! source_data = block!(hasher.update(source_data)).unwrap();
//! }
//! let source_data = loop {
//! if let Some(data) = hasher.finish(&mut output) {
//! break data;
//! }
//! };
//!
//! // Finish can be called as many times as desired to get multiple copies of
//! // the output.
//! block!(hasher.finish(output.as_mut_slice())).unwrap();
//!
//! while self.finish(output.as_mut_slice()).is_none() {}
//! # }
//! ```
//! ## Implementation State
//! - DMA-SHA Mode is not supported.
use core::{borrow::BorrowMut, convert::Infallible, marker::PhantomData, mem::size_of};
use core::{borrow::BorrowMut, marker::PhantomData, mem::size_of};

/// Re-export digest for convenience
#[cfg(feature = "digest")]
Expand Down Expand Up @@ -540,16 +539,16 @@ impl<'d, A: ShaAlgorithm, S: BorrowMut<Sha<'d>>> digest::OutputSizeUser for ShaD
impl<'d, A: ShaAlgorithm, S: BorrowMut<Sha<'d>>> digest::Update for ShaDigest<'d, A, S> {
fn update(&mut self, data: &[u8]) {
let mut remaining = data.as_ref();
while !remaining.is_empty() {
remaining = nb::block!(Self::update(self, remaining)).unwrap();
while let Some(rem) = Self::update(self, remaining) {
remaining = rem;
}
}
}

#[cfg(feature = "digest")]
impl<'d, A: ShaAlgorithm, S: BorrowMut<Sha<'d>>> digest::FixedOutput for ShaDigest<'d, A, S> {
fn finalize_into(mut self, out: &mut digest::Output<Self>) {
nb::block!(self.finish(out)).unwrap();
while self.finish(out).is_none() {}
}
}

Expand Down
10 changes: 6 additions & 4 deletions esp-hal/src/spi/master.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2211,14 +2211,16 @@ mod ehal1 {
T: Instance,
Dm: DriverMode,
{
fn read(&mut self) -> nb::Result<u8, Self::Error> {
self.driver().read_byte().ok_or(nb::Error::WouldBlock)
fn read(&mut self) -> embedded_hal_nb::nb::Result<u8, Self::Error> {
self.driver()
.read_byte()
.ok_or(embedded_hal_nb::nb::Error::WouldBlock)
}

fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
fn write(&mut self, word: u8) -> embedded_hal_nb::nb::Result<(), Self::Error> {
self.driver()
.write_byte(word)
.map_or_else(|| Err(nb::Error::WouldBlock), |_| Ok(()))
.map_or_else(|| Err(embedded_hal_nb::nb::Error::WouldBlock), |_| Ok(()))
}
}

Expand Down
2 changes: 1 addition & 1 deletion esp-hal/src/timer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
//!
//! periodic.start(1.secs());
//! loop {
//! nb::block!(periodic.wait());
//! while periodic.wait().is_none() {}
//! }
//! # }
//! ```
Expand Down
48 changes: 30 additions & 18 deletions esp-hal/src/twai/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,14 @@
//!
//! loop {
//! // Wait for a frame to be received.
//! let frame = block!(twai.receive()).unwrap();
//! let frame = loop {
//! if let Ok(frame) = twai.receive() {
//! break frame;
//! }
//! };
//!
//! // Transmit the frame back.
//! let _result = block!(twai.transmit(&frame)).unwrap();
//! while twai.transmit(&frame).is_err() {}
//! }
//! # }
//! ```
Expand Down Expand Up @@ -111,7 +115,11 @@
//!
//! let frame = EspTwaiFrame::new_self_reception(StandardId::ZERO,
//! &[1, 2, 3]).unwrap(); // Wait for a frame to be received.
//! let frame = block!(can.receive()).unwrap();
//! let frame = loop {
//! if let Ok(frame) = can.receive() {
//! break frame;
//! }
//! };
//!
//! # loop {}
//! # }
Expand Down Expand Up @@ -1179,12 +1187,12 @@ where
}

/// Sends the specified `EspTwaiFrame` over the TWAI bus.
pub fn transmit(&mut self, frame: &EspTwaiFrame) -> nb::Result<(), EspTwaiError> {
pub fn transmit(&mut self, frame: &EspTwaiFrame) -> Result<(), EspTwaiError> {
self.tx.transmit(frame)
}

/// Receives a TWAI frame from the TWAI bus.
pub fn receive(&mut self) -> nb::Result<EspTwaiFrame, EspTwaiError> {
pub fn receive(&mut self) -> Result<EspTwaiFrame, EspTwaiError> {
self.rx.receive()
}

Expand Down Expand Up @@ -1219,17 +1227,18 @@ where
/// NOTE: TODO: This may not work if using the self reception/self test
/// functionality. See notes 1 and 2 in the "Frame Identifier" section
/// of the reference manual.
pub fn transmit(&mut self, frame: &EspTwaiFrame) -> nb::Result<(), EspTwaiError> {
pub fn transmit(&mut self, frame: &EspTwaiFrame) -> Result<(), EspTwaiError> {
let register_block = self.twai.register_block();
let status = register_block.status().read();

// Check that the peripheral is not in a bus off state.
if status.bus_off_st().bit_is_set() {
return nb::Result::Err(nb::Error::Other(EspTwaiError::BusOff));
return Err(EspTwaiError::BusOff);
}
// Check that the peripheral is not already transmitting a packet.
if !status.tx_buf_st().bit_is_set() {
return nb::Result::Err(nb::Error::WouldBlock);
return Err(EspTwaiError::WouldBlock); // TODO: Is this the right
// error?
}

write_frame(register_block, frame);
Expand All @@ -1251,25 +1260,23 @@ where
Dm: crate::DriverMode,
{
/// Receive a frame
pub fn receive(&mut self) -> nb::Result<EspTwaiFrame, EspTwaiError> {
pub fn receive(&mut self) -> Result<EspTwaiFrame, EspTwaiError> {
let register_block = self.twai.register_block();
let status = register_block.status().read();

// Check that the peripheral is not in a bus off state.
if status.bus_off_st().bit_is_set() {
return nb::Result::Err(nb::Error::Other(EspTwaiError::BusOff));
return Err(EspTwaiError::BusOff);
}

// Check that we actually have packets to receive.
if !status.rx_buf_st().bit_is_set() {
return nb::Result::Err(nb::Error::WouldBlock);
return Err(EspTwaiError::WouldBlock);
}

// Check if the packet in the receive buffer is valid or overrun.
if status.miss_st().bit_is_set() {
return nb::Result::Err(nb::Error::Other(EspTwaiError::EmbeddedHAL(
ErrorKind::Overrun,
)));
return Err(EspTwaiError::EmbeddedHAL(ErrorKind::Overrun));
}

Ok(read_frame(register_block)?)
Expand All @@ -1288,6 +1295,8 @@ pub enum EspTwaiError {
NonCompliantDlc(u8),
/// Encapsulates errors defined by the embedded-hal crate.
EmbeddedHAL(ErrorKind),
/// This operation requires blocking behavior to complete
WouldBlock,
}

#[cfg(any(doc, feature = "unstable"))]
Expand Down Expand Up @@ -1344,18 +1353,21 @@ where
type Error = EspTwaiError;

/// Transmit a frame.
fn transmit(&mut self, frame: &Self::Frame) -> nb::Result<Option<Self::Frame>, Self::Error> {
fn transmit(
&mut self,
frame: &Self::Frame,
) -> embedded_hal_nb::nb::Result<Option<Self::Frame>, Self::Error> {
self.tx.transmit(frame)?;

// Success in readying packet for transmit. No packets can be replaced in the
// transmit buffer so return None in accordance with the
// embedded-can/embedded-hal trait.
nb::Result::Ok(None)
embedded_hal_nb::nb::Result::Ok(None)
}

/// Return a received frame if there are any available.
fn receive(&mut self) -> nb::Result<Self::Frame, Self::Error> {
self.rx.receive()
fn receive(&mut self) -> embedded_hal_nb::nb::Result<Self::Frame, Self::Error> {
Ok(self.rx.receive()?)
}
}

Expand Down
Loading

0 comments on commit 5c0ad5b

Please sign in to comment.