Skip to content
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

Make examples less dependent on embedded-hal where able #1342

Merged
merged 3 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
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
41 changes: 22 additions & 19 deletions esp-hal/src/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,6 @@
//! rng.read(&mut buffer).unwrap();
//! ```

#[cfg(feature = "embedded-hal-02")]
use core::convert::Infallible;
use core::marker::PhantomData;

use crate::{peripheral::Peripheral, peripherals::RNG};
Expand Down Expand Up @@ -95,48 +93,53 @@ impl Rng {
.read()
.bits()
}
}

#[cfg(feature = "embedded-hal-02")]
impl embedded_hal_02::blocking::rng::Read for Rng {
type Error = Infallible;

fn read(&mut self, buffer: &mut [u8]) -> Result<(), Self::Error> {
#[inline]
/// Reads enough bytes from hardware random number generator to fill
/// `buffer`.
///
/// If any error is encountered then this function immediately returns. The
/// contents of buf are unspecified in this case.
///
/// If this function returns an error, it is unspecified how many bytes it
/// has read, but it will never read more than would be necessary to
/// completely fill the buffer.
pub fn read(&mut self, buffer: &mut [u8]) {
for chunk in buffer.chunks_mut(4) {
let bytes = self.random().to_le_bytes();
chunk.copy_from_slice(&bytes[..chunk.len()]);
}
}
}

#[cfg(feature = "embedded-hal-02")]
impl embedded_hal_02::blocking::rng::Read for Rng {
type Error = core::convert::Infallible;

fn read(&mut self, buffer: &mut [u8]) -> Result<(), Self::Error> {
self.read(buffer);
Ok(())
}
}

impl rand_core::RngCore for Rng {
fn next_u32(&mut self) -> u32 {
// Directly use the existing random method to get a u32 random number
self.random()
}

fn next_u64(&mut self) -> u64 {
// Call random() twice to generate a u64 random number (сombine two u32)
let upper = self.random() as u64;
let lower = self.random() as u64;

(upper << 32) | lower
}

fn fill_bytes(&mut self, dest: &mut [u8]) {
// Fill the destination buffer with random bytes
for chunk in dest.chunks_mut(4) {
let rand_bytes = self.random().to_le_bytes();
for (dest_byte, rand_byte) in chunk.iter_mut().zip(&rand_bytes) {
*dest_byte = *rand_byte;
}
}
self.read(dest);
}

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
// Similar implementation as fill_bytes, but encapsulated in a Result
self.fill_bytes(dest);
self.read(dest);
Ok(())
}
}
Expand Down
11 changes: 3 additions & 8 deletions examples/src/bin/crc.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,29 @@
//! This shows example usage of the CRC functions in ROM

//% CHIPS: esp32 esp32c2 esp32c3 esp32c6 esp32h2 esp32s2 esp32s3
//% FEATURES: embedded-hal-02

#![no_std]
#![no_main]

use core::fmt::Write;

use embedded_hal_02::timer::CountDown;
use esp_backtrace as _;
use esp_hal::{
clock::ClockControl,
delay::Delay,
peripherals::Peripherals,
prelude::*,
rom::{crc, md5},
timer::TimerGroup,
uart::Uart,
};
use nb::block;

#[entry]
fn main() -> ! {
let peripherals = Peripherals::take();
let system = peripherals.SYSTEM.split();
let clocks = ClockControl::boot_defaults(system.clock_control).freeze();

let timg0 = TimerGroup::new(peripherals.TIMG0, &clocks);
let mut timer0 = timg0.timer0;
timer0.start(1u64.secs());
let delay = Delay::new(&clocks);

let mut uart0 = Uart::new(peripherals.UART0, &clocks);

Expand Down Expand Up @@ -95,6 +90,6 @@ fn main() -> ! {
)
.unwrap();

block!(timer0.wait()).unwrap();
delay.delay(1.secs());
}
}
24 changes: 12 additions & 12 deletions examples/src/bin/ecc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
//! hardware-accelerated and pure software ECC.

//% CHIPS: esp32c2 esp32c6 esp32h2
//% FEATURES: embedded-hal-02

#![no_std]
#![no_main]
Expand All @@ -16,10 +15,11 @@ use crypto_bigint::{
U256,
};
use elliptic_curve::sec1::ToEncodedPoint;
use embedded_hal_02::blocking::rng::Read;
use esp_backtrace as _;
#[cfg(feature = "esp32h2")]
use esp_hal::ecc::WorkMode;
use esp_hal::{
ecc::{Ecc, EllipticCurve, Error, WorkMode},
ecc::{Ecc, EllipticCurve, Error},
peripherals::Peripherals,
prelude::*,
rng::Rng,
Expand Down Expand Up @@ -89,7 +89,7 @@ fn test_affine_point_multiplication(ecc: &mut Ecc, rng: &mut Rng) {
let mut delta_time = 0;
for _ in 0..TEST_PARAMS_VECTOR.nb_loop_mul {
loop {
rng.read(k).unwrap();
rng.read(k);
let is_zero = k.iter().all(|&elt| elt == 0);
let is_modulus = k.iter().zip(prime_field).all(|(&a, &b)| a == b);
if is_zero == false && is_modulus == false {
Expand Down Expand Up @@ -202,7 +202,7 @@ fn test_affine_point_verification(ecc: &mut Ecc, rng: &mut Rng) {
let mut delta_time = 0;
for _ in 0..TEST_PARAMS_VECTOR.nb_loop_mul {
loop {
rng.read(k).unwrap();
rng.read(k);
let is_zero = k.iter().all(|&elt| elt == 0);
let is_modulus = k.iter().zip(prime_field).all(|(&a, &b)| a == b);
if is_zero == false && is_modulus == false {
Expand Down Expand Up @@ -278,7 +278,7 @@ fn test_afine_point_verification_multiplication(ecc: &mut Ecc, rng: &mut Rng) {
let qz = &mut [0u8; 8];
for _ in 0..TEST_PARAMS_VECTOR.nb_loop_mul {
loop {
rng.read(k).unwrap();
rng.read(k);
let is_zero = k.iter().all(|&elt| elt == 0);
let is_modulus = k.iter().zip(prime_field).all(|(&a, &b)| a == b);
if is_zero == false && is_modulus == false {
Expand Down Expand Up @@ -407,7 +407,7 @@ fn test_jacobian_point_multiplication(ecc: &mut Ecc, rng: &mut Rng) {
let (sw_k, _) = sw_k.split_at_mut(prime_field.len());

loop {
rng.read(k).unwrap();
rng.read(k);
let is_zero = k.iter().all(|&elt| elt == 0);
let is_modulus = k.iter().zip(prime_field).all(|(&a, &b)| a == b);
if is_zero == false && is_modulus == false {
Expand Down Expand Up @@ -535,8 +535,8 @@ fn test_jacobian_point_verification(ecc: &mut Ecc, rng: &mut Rng) {
let mut delta_time = 0;
for _ in 0..TEST_PARAMS_VECTOR.nb_loop_mul {
loop {
rng.read(k).unwrap();
rng.read(z).unwrap();
rng.read(k);
rng.read(z);
let is_zero = k.iter().all(|&elt| elt == 0) || z.iter().all(|&elt| elt == 0);
let is_modulus = k.iter().zip(prime_field).all(|(&a, &b)| a == b)
|| z.iter().zip(prime_field).all(|(&a, &b)| a == b);
Expand Down Expand Up @@ -629,7 +629,7 @@ fn test_afine_point_verification_jacobian_multiplication(ecc: &mut Ecc, rng: &mu
let (sw_k, _) = sw_k.split_at_mut(prime_field.len());

loop {
rng.read(k).unwrap();
rng.read(k);
let is_zero = k.iter().all(|&elt| elt == 0);
let is_modulus = k.iter().zip(prime_field).all(|(&a, &b)| a == b);
if is_zero == false && is_modulus == false {
Expand Down Expand Up @@ -763,8 +763,8 @@ fn test_finite_field_division(ecc: &mut Ecc, rng: &mut Rng) {
let mut delta_time = 0;
for _ in 0..TEST_PARAMS_VECTOR.nb_loop_inv {
loop {
rng.read(k).unwrap();
rng.read(y).unwrap();
rng.read(k);
rng.read(y);
let is_zero = k.iter().all(|&elt| elt == 0) || y.iter().all(|&elt| elt == 0);
let is_modulus = k.iter().zip(prime_field).all(|(&a, &b)| a == b)
|| y.iter().zip(prime_field).all(|(&a, &b)| a == b);
Expand Down
20 changes: 8 additions & 12 deletions examples/src/bin/hello_world.rs
Original file line number Diff line number Diff line change
@@ -1,44 +1,40 @@
//! This shows how to write text to UART0.
//!
//! You can see the output with `espflash` if you provide the `--monitor`
//! option. Depending on the chip, you will need to ensure that you are
//! connected to the UART USB port, and not the USB-SERIAL-JTAG port.
//! If you want to test printing over USB-SERIAL-JTAG, try the usb_serial_jtag
//! example instead.
//! option.
//!
//! Depending on the chip, you will need to ensure that you are connected to
//! the UART USB port, and not the USB-SERIAL-JTAG port. If you want to test
//! printing over USB-SERIAL-JTAG, try the usb_serial_jtag example instead.

//% CHIPS: esp32 esp32c2 esp32c3 esp32c6 esp32h2 esp32s2 esp32s3
//% FEATURES: embedded-hal-02

#![no_std]
#![no_main]

use core::fmt::Write;

use embedded_hal_02::timer::CountDown;
use esp_backtrace as _;
use esp_hal::{
clock::ClockControl,
delay::Delay,
peripherals::Peripherals,
prelude::*,
timer::TimerGroup,
uart::Uart,
};
use nb::block;

#[entry]
fn main() -> ! {
let peripherals = Peripherals::take();
let system = peripherals.SYSTEM.split();
let clocks = ClockControl::boot_defaults(system.clock_control).freeze();

let timg0 = TimerGroup::new(peripherals.TIMG0, &clocks);
let mut timer0 = timg0.timer0;
timer0.start(1u64.secs());
let delay = Delay::new(&clocks);

let mut uart0 = Uart::new(peripherals.UART0, &clocks);

loop {
writeln!(uart0, "Hello world!").unwrap();
block!(timer0.wait()).unwrap();
delay.delay(1.secs());
}
}
4 changes: 1 addition & 3 deletions examples/src/bin/hmac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,10 @@
//! ```

//% CHIPS: esp32c3 esp32c6 esp32h2 esp32s2 esp32s3
//% FEATURES: embedded-hal-02

#![no_std]
#![no_main]

use embedded_hal_02::blocking::rng::Read;
use esp_backtrace as _;
use esp_hal::{
clock::ClockControl,
Expand Down Expand Up @@ -89,7 +87,7 @@ fn main() -> ! {
let mut hw_hmac = Hmac::new(peripherals.HMAC);

let mut src = [0_u8; 1024];
rng.read(src.as_mut_slice()).unwrap();
rng.read(src.as_mut_slice());
// println!("HMAC input {:02X?}", src);

let mut output = [0u8; 32];
Expand Down
15 changes: 4 additions & 11 deletions examples/src/bin/i2c_display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,15 @@ use embedded_graphics::{
prelude::*,
text::{Alignment, Text},
};
use embedded_hal_02::timer::CountDown;
use esp_backtrace as _;
use esp_hal::{
clock::ClockControl,
delay::Delay,
gpio::IO,
i2c::I2C,
peripherals::Peripherals,
prelude::*,
timer::TimerGroup,
};
use nb::block;
use ssd1306::{prelude::*, I2CDisplayInterface, Ssd1306};

#[entry]
Expand All @@ -41,9 +39,7 @@ fn main() -> ! {
let system = peripherals.SYSTEM.split();
let clocks = ClockControl::boot_defaults(system.clock_control).freeze();

let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks);
let mut timer0 = timer_group0.timer0;

let delay = Delay::new(&clocks);
let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);

// Create a new peripheral object with the described wiring
Expand All @@ -56,9 +52,6 @@ fn main() -> ! {
&clocks,
);

// Start timer (5 second interval)
timer0.start(5u64.secs());

// Initialize display
let interface = I2CDisplayInterface::new(i2c);
let mut display = Ssd1306::new(interface, DisplaySize128x64, DisplayRotation::Rotate0)
Expand Down Expand Up @@ -102,7 +95,7 @@ fn main() -> ! {
display.clear(BinaryColor::Off).unwrap();

// Wait 5 seconds
block!(timer0.wait()).unwrap();
delay.delay(5.secs());

// Write single-line centered text "Hello World" to buffer
Text::with_alignment(
Expand All @@ -120,6 +113,6 @@ fn main() -> ! {
display.clear(BinaryColor::Off).unwrap();

// Wait 5 seconds
block!(timer0.wait()).unwrap();
delay.delay(5.secs());
}
}
Loading
Loading