ocpp_kit/engine/time.rs
1//! Monotonic time for the sans-I/O engine.
2//!
3//! The engine never reads a clock. The driver supplies the current instant to every
4//! [`Engine::handle`](super::Engine::handle) — and to every application call it makes — which
5//! is what makes timeouts, retry schedules and boot back-off testable in microseconds instead
6//! of minutes, and what stops a deadline from ever being computed against a clock that has
7//! not moved since the last timer fired.
8
9use core::fmt;
10use core::ops::Add;
11use core::time::Duration;
12
13/// A point on a monotonic clock, in milliseconds since an arbitrary origin.
14///
15/// Only differences are meaningful. The origin is whatever the driver chose.
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct Instant {
18 millis: u64,
19}
20
21impl Instant {
22 /// The origin of the driver's clock.
23 pub const ZERO: Instant = Instant { millis: 0 };
24
25 /// An instant `millis` milliseconds after the origin.
26 #[must_use]
27 pub const fn from_millis(millis: u64) -> Self {
28 Self { millis }
29 }
30
31 /// Milliseconds since the origin.
32 #[must_use]
33 pub const fn as_millis(self) -> u64 {
34 self.millis
35 }
36
37 /// How long ago `earlier` was; zero if `earlier` is in the future.
38 #[must_use]
39 pub const fn saturating_duration_since(self, earlier: Instant) -> Duration {
40 Duration::from_millis(self.millis.saturating_sub(earlier.millis))
41 }
42
43 /// This instant advanced by `duration`, saturating at the end of the clock.
44 #[must_use]
45 pub fn saturating_add(self, duration: Duration) -> Self {
46 let millis = u64::try_from(duration.as_millis()).unwrap_or(u64::MAX);
47 Self {
48 millis: self.millis.saturating_add(millis),
49 }
50 }
51}
52
53impl Add<Duration> for Instant {
54 type Output = Instant;
55
56 fn add(self, duration: Duration) -> Instant {
57 self.saturating_add(duration)
58 }
59}
60
61impl fmt::Display for Instant {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 write!(f, "+{}ms", self.millis)
64 }
65}
66
67/// The timers the engine asks the driver to run.
68///
69/// The driver only has to keep one deadline per variant; the engine re-arms and clears them
70/// explicitly, and a spurious [`Input::Timeout`](super::Input::Timeout) is always harmless.
71#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
72#[non_exhaustive]
73pub enum Timer {
74 /// The outstanding `CALL` must be answered before this deadline.
75 CallTimeout,
76 /// Time to send a `Heartbeat`.
77 Heartbeat,
78 /// Time to re-send `BootNotification` (B02.FR.04 / FR.07 / FR.08).
79 BootRetry,
80 /// Time to retry the transaction message at the head of the queue.
81 TransactionRetry,
82 /// A graceful shutdown must complete by this deadline.
83 DrainDeadline,
84}