Skip to content

Commit

Permalink
feat(rng): add fake async driver
Browse files Browse the repository at this point in the history
  • Loading branch information
andelf committed Oct 2, 2024
1 parent 1a1fc94 commit a03e270
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ This crate is a working-in-progress and not ready for production use.
- [x] Device
- [ ] Host
- [x] XPI NOR flash driver using embedded-storage
- [x] RNG, in blocking mode
- [ ] power domain handling

### Related Crates
Expand Down
15 changes: 14 additions & 1 deletion examples/hpm5300evk/src/bin/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#![feature(impl_trait_in_assoc_type)]
#![feature(abi_riscv_interrupt)]

use embassy_time::Timer;
use rand_core::RngCore;
use {defmt_rtt as _, hpm_hal as hal};

Expand All @@ -14,10 +15,22 @@ async fn main(_spawner: embassy_executor::Spawner) -> ! {
let mut rng = hal::rng::Rng::new(p.RNG).unwrap();
let mut buf = [0u8; 20];

defmt::println!("Async mode");

for _ in 0..5 {
rng.async_fill_bytes(&mut buf).await.unwrap();

defmt::println!("out: {:?}", buf);
}

Timer::after_millis(1000).await;

defmt::println!("Blocking mode(Notice about 0.3s delay when new seed is not ready");

loop {
rng.fill_bytes(&mut buf);

defmt::println!("buf: {:?}", buf);
defmt::println!("out: {:?}", buf);
}
}

Expand Down
21 changes: 21 additions & 0 deletions src/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//! - FIFO underflow
//!
use embassy_futures::yield_now;
use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef};
use rand_core::{CryptoRng, RngCore};

Expand Down Expand Up @@ -67,6 +68,26 @@ impl<'d, T: Instance> Rng<'d, T> {
Ok(())
}

#[inline]
async fn async_next_u32(&mut self) -> Result<u32, Error> {
while T::regs().sta().read().busy() {
yield_now().await;
}
Ok(T::regs().fo2b().read().0)
}

// NOTE: RNG interrupt is non-functional.
// See-also: https://github.com/hpmicro/hpm-hal/issues/37
pub async fn async_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
for chunk in dest.chunks_mut(4) {
let rand = self.async_next_u32().await?;
for (slot, num) in chunk.iter_mut().zip(rand.to_ne_bytes().iter()) {
*slot = *num
}
}
Ok(())
}

/// Run self-test
pub fn run_selftest(&mut self) -> Result<(), Error> {
let r = T::regs();
Expand Down

0 comments on commit a03e270

Please sign in to comment.