use std::time::{Duration, Instant};
use embedded_hal::delay::DelayNs;
use spin_sleep::sleep;
use void::Void;
#[derive(Debug, Default)]
pub struct Delay;
impl Delay {
pub fn new() -> Delay {
Delay {}
}
}
impl embedded_hal_0::blocking::delay::DelayMs<u8> for Delay {
fn delay_ms(&mut self, ms: u8) {
DelayNs::delay_ms(self, ms as u32);
}
}
impl embedded_hal_0::blocking::delay::DelayMs<u16> for Delay {
fn delay_ms(&mut self, ms: u16) {
DelayNs::delay_ms(self, ms as u32);
}
}
impl embedded_hal_0::blocking::delay::DelayMs<u32> for Delay {
fn delay_ms(&mut self, ms: u32) {
DelayNs::delay_ms(self, ms);
}
}
impl embedded_hal_0::blocking::delay::DelayMs<u64> for Delay {
fn delay_ms(&mut self, mut ms: u64) {
while ms > (u32::MAX as u64) {
ms -= u32::MAX as u64;
DelayNs::delay_ms(self, u32::MAX);
}
DelayNs::delay_ms(self, ms as u32);
}
}
impl embedded_hal_0::blocking::delay::DelayUs<u8> for Delay {
fn delay_us(&mut self, us: u8) {
DelayNs::delay_us(self, us as u32);
}
}
impl embedded_hal_0::blocking::delay::DelayUs<u16> for Delay {
fn delay_us(&mut self, us: u16) {
DelayNs::delay_us(self, us as u32);
}
}
impl DelayNs for Delay {
fn delay_ns(&mut self, ns: u32) {
sleep(Duration::from_nanos(ns.into()));
}
fn delay_us(&mut self, us: u32) {
sleep(Duration::from_micros(us.into()));
}
fn delay_ms(&mut self, ms: u32) {
sleep(Duration::from_millis(ms.into()));
}
}
impl embedded_hal_0::blocking::delay::DelayUs<u32> for Delay {
fn delay_us(&mut self, us: u32) {
DelayNs::delay_us(self, us);
}
}
impl embedded_hal_0::blocking::delay::DelayUs<u64> for Delay {
fn delay_us(&mut self, mut us: u64) {
while us > (u32::MAX as u64) {
us -= u32::MAX as u64;
DelayNs::delay_us(self, u32::MAX);
}
DelayNs::delay_us(self, us as u32);
}
}
pub struct Hertz(pub f64);
const MICROS_PER_SEC: f64 = 1_000_000.0;
impl From<Hertz> for Duration {
fn from(item: Hertz) -> Self {
if item.0 > 0.0 && item.0.is_finite() {
Duration::from_micros(((1.0 / item.0) * MICROS_PER_SEC) as u64)
} else {
Duration::default()
}
}
}
#[derive(Debug, Copy, Clone)]
pub struct Timer {
start: Instant,
duration: Duration,
}
impl Timer {
pub fn new() -> Self {
Self {
start: Instant::now(),
duration: Duration::from_micros(0),
}
}
}
impl Default for Timer {
fn default() -> Self {
Timer::new()
}
}
impl embedded_hal_0::timer::CountDown for Timer {
type Time = Duration;
fn start<T>(&mut self, timeout: T)
where
T: Into<Self::Time>,
{
self.start = Instant::now();
self.duration = timeout.into();
}
fn wait(&mut self) -> nb::Result<(), Void> {
if self.start.elapsed() >= self.duration {
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
}