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 8bf7839
Show file tree
Hide file tree
Showing 26 changed files with 227 additions and 167 deletions.
2 changes: 0 additions & 2 deletions esp-hal/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,10 @@ 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" }
strum = { version = "0.26.3", default-features = false, features = ["derive"] }
void = { version = "1.0.2", default-features = false }
usb-device = { version = "0.3.2", optional = true }
rand_core = "0.6.4"
ufmt-write = "0.1.0"
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
6 changes: 2 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,8 @@ 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();
self.write_data(&[0x80])?;
self.flush_data()?;
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/esp32.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
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
2 changes: 0 additions & 2 deletions esp-hal/src/rsa/esp32sX.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
26 changes: 11 additions & 15 deletions esp-hal/src/sha.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,30 +33,28 @@
#![doc = crate::before_snippet!()]
//! # use esp_hal::sha::Sha;
//! # use esp_hal::sha::Sha256;
//! # use nb::block;
//! let mut source_data = "HELLO, ESPRESSIF!".as_bytes();
//! let mut sha = Sha::new(peripherals.SHA);
//! let mut hasher = sha.start::<Sha256>();
//! // Short hashes can be created by decreasing the output buffer to the
//! // 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 hasher.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 @@ -225,9 +223,7 @@ impl<'d, A: ShaAlgorithm, S: BorrowMut<Sha<'d>>> ShaDigest<'d, A, S> {
// Store message length for padding
let length = (self.cursor as u64 * 8).to_be_bytes();
// Append "1" bit
if self.update(&[0x80]).is_none() {
return None;
}
self.update(&[0x80])?;

// Flush partial data, ensures aligned cursor
{
Expand Down Expand Up @@ -540,16 +536,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
52 changes: 31 additions & 21 deletions esp-hal/src/twai/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
//! # use esp_hal::twai::TwaiConfiguration;
//! # use esp_hal::twai::BaudRate;
//! # use esp_hal::twai::TwaiMode;
//! # use nb::block;
//! // Use GPIO pins 2 and 3 to connect to the respective pins on the TWAI
//! // transceiver.
//! let twai_rx_pin = peripherals.GPIO3;
Expand Down Expand Up @@ -62,10 +61,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 All @@ -81,7 +84,6 @@
//! # use esp_hal::twai::EspTwaiFrame;
//! # use esp_hal::twai::StandardId;
//! # use esp_hal::twai::TwaiMode;
//! # use nb::block;
//! // Use GPIO pins 2 and 3 to connect to the respective pins on the TWAI
//! // transceiver.
//! let can_rx_pin = peripherals.GPIO3;
Expand Down Expand Up @@ -111,7 +113,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 +1185,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 +1225,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,28 +1258,26 @@ 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)?)
read_frame(register_block)
}
}

Expand All @@ -1288,6 +1293,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 +1351,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 8bf7839

Please sign in to comment.