fusb302b/timeout.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
use embassy_time::{Duration, Instant};
/// Timeout wrapper
pub struct Timeout {
now: Instant,
expiry: Option<Instant>,
}
impl Timeout {
/// Create a new empty timeout
pub fn new() -> Self {
Self {
now: Instant::from_ticks(0),
expiry: None,
}
}
/// Update the current time
pub fn update(&mut self) {
self.now = Instant::now();
}
/// Start a timeout some duration in the future
pub fn start(&mut self, duration: Duration) {
self.expiry = Some(self.now.checked_add(duration).unwrap());
}
/// Cancel a timeout
pub fn cancel(&mut self) {
self.expiry = None;
}
/// Test whether a timeout has expired
pub fn is_expired(&mut self) -> bool {
let Some(timeout) = self.expiry else {
return false;
};
// is "now" after the timeout?
let expired = timeout <= self.now;
if expired {
self.cancel();
}
expired
}
}