use core::time::Duration;
use core::ffi::{c_int, c_void};
use embedded_timers::{clock::Clock, timer::Timer, timer::TimerError};
pub(crate) extern "C" fn set_timer<CLOCK: Clock>(ctx: *mut c_void, int_ms: u32, fin_ms: u32) {
let timer_ctx = unsafe { (ctx as *mut MbedtlsTimer<'_, CLOCK>).as_mut().unwrap() };
if fin_ms == 0 {
if timer_ctx
.int
.cancel()
.is_err_and(|e| e != TimerError::NotRunning)
{
panic!("Clock error")
};
if timer_ctx
.fin
.cancel()
.is_err_and(|e| e != TimerError::NotRunning)
{
panic!("Clock error")
};
return;
}
timer_ctx
.int
.try_start(Duration::from_millis(int_ms as u64))
.unwrap();
timer_ctx
.fin
.try_start(Duration::from_millis(fin_ms as u64))
.unwrap();
}
pub(crate) extern "C" fn get_timer<CLOCK: Clock>(ctx: *mut c_void) -> c_int {
let timer_ctx = unsafe { (ctx as *mut MbedtlsTimer<'_, CLOCK>).as_mut().unwrap() };
match timer_ctx.fin.is_expired() {
Ok(true) => {
return 2;
}
Ok(false) => {}
Err(TimerError::NotRunning) => {
return -1;
}
Err(e) => {
log::error!("Error querying timer: {:?}", e);
return -2;
}
}
match timer_ctx.int.is_expired() {
Ok(true) => 1,
Ok(false) => 0,
Err(TimerError::NotRunning) => -1,
Err(e) => {
log::error!("Error querying timer: {:?}", e);
-2
}
}
}
pub(crate) struct MbedtlsTimer<'a, CLOCK: Clock> {
int: Timer<'a, CLOCK>,
fin: Timer<'a, CLOCK>,
}
impl<'a, CLOCK: Clock> MbedtlsTimer<'a, CLOCK> {
pub(crate) fn new(clock: &'a CLOCK) -> Self {
MbedtlsTimer {
int: Timer::new(clock),
fin: Timer::new(clock),
}
}
}