time/manager.rs
1use crate::{
2 Error, RealtimeSample, RealtimeSource, RealtimeStatus, Result, Synchronization, Timestamp,
3};
4use core::cell::{Cell, RefCell};
5use core::time::Duration;
6use synchronization::blocking_mutex::{Mutex, raw::CriticalSectionRawMutex};
7use synchronization::signal::Signal;
8
9/// Nominal resolution of the default monotonic source, rounded up to nanoseconds.
10/// Actual precision can be coarser (for example, browser privacy restrictions).
11pub const MONOTONIC_RESOLUTION: Duration =
12 Duration::from_nanos(1_000_000_000u64.div_ceil(embassy_time::TICK_HZ));
13
14/// An elapsed-time source with a stable, arbitrary epoch.
15///
16/// Values must never decrease or wrap during a boot, including across concurrent
17/// reads. UTC corrections must not affect this source. Suspend accounting is a
18/// platform property; callers must not assume suspended time is included.
19pub trait MonotonicClock: Send + Sync {
20 fn now(&self) -> Duration;
21
22 /// Nominal source quantization; override for custom platform clocks.
23 fn resolution(&self) -> Duration {
24 MONOTONIC_RESOLUTION
25 }
26}
27
28/// The executor's Embassy clock, shared with task timers and WASI deadlines.
29///
30/// Native uses `std::time::Instant`; browsers use `performance.now()` through
31/// Embassy's wasm driver. Both currently use 1 MHz ticks (1 microsecond nominal
32/// resolution). Suspend behavior follows the OS/browser and is not portable;
33/// browser throttling can delay wakeups independently of clock readings.
34///
35/// Embedded platforms must supply an Embassy hardware time driver and tick rate.
36/// If its counter stops in low-power sleep, this clock excludes that interval.
37/// Deep sleep/reset starts a new epoch; instants must never be persisted.
38/// Embassy's u64 tick counter must not wrap within a boot (at 1 MHz its range is
39/// about 584,000 years). Hardware drivers must extend narrower counters.
40pub struct EmbassyClock;
41
42impl MonotonicClock for EmbassyClock {
43 fn now(&self) -> Duration {
44 duration_from_ticks(embassy_time::Instant::now().as_ticks())
45 }
46}
47
48static EMBASSY_CLOCK: EmbassyClock = EmbassyClock;
49
50fn duration_from_ticks(ticks: u64) -> Duration {
51 // Split before scaling: Instant::as_nanos() can overflow a u64 even though
52 // the timestamp still fits in a core Duration.
53 Duration::new(
54 ticks / embassy_time::TICK_HZ,
55 ((ticks % embassy_time::TICK_HZ) as u128 * 1_000_000_000 / embassy_time::TICK_HZ as u128)
56 as u32,
57 )
58}
59
60/// System-owned UTC clock anchored to monotonic time, independent of shell lifetime.
61///
62/// `with_clock`/`unsynchronized` boot with zero correction and invalid UTC. Targets
63/// without an RTC use these until manual or network initialization. `new` bootstraps
64/// once from a trusted source (native/browser use the host clock); source failure is
65/// returned so the runtime may explicitly fall back to an unsynchronized manager.
66/// Nothing survives reset: persistence and source selection are runtime policy.
67///
68/// Corrections step immediately, in either direction; there is no slew. Monotonic
69/// deadlines and uptime are unchanged. UTC subsequently advances at the monotonic
70/// source's rate, including its suspend behavior; resynchronize after suspend when
71/// that source stops during sleep. Nominal resolution is the coarser of the epoch
72/// sample and monotonic clock. Accuracy is unknown unless supplied by the source,
73/// and is not maintained as a bound as time elapses. No timezone or DST is applied.
74///
75/// State updates and reads are serialized with a short critical section, without
76/// allocation or I/O while locked. Custom monotonic sources must be nonblocking
77/// and safe to call in that critical section.
78///
79/// Every successful `set_realtime` and every `invalidate` also bumps
80/// [`Manager::change_generation`] and signals [`Manager::wait_for_change`] after
81/// the critical section is released, so a runtime service (for example the
82/// real-time clock write-back task) can react to UTC changes without polling and
83/// without holding the clock lock. The signal has a single consumer.
84pub struct Manager<'a> {
85 monotonic_clock: &'a dyn MonotonicClock,
86 start_time: Duration,
87 realtime: Mutex<CriticalSectionRawMutex, RefCell<RealtimeStatus>>,
88 changes: Mutex<CriticalSectionRawMutex, Cell<u64>>,
89 change_signal: Signal<CriticalSectionRawMutex, u64>,
90}
91
92impl<'a> Manager<'a> {
93 pub fn new(source: &dyn RealtimeSource) -> Result<Self> {
94 Self::with_monotonic_clock(source, &EMBASSY_CLOCK)
95 }
96
97 /// Construct a manager and initialize UTC once from a trusted epoch source.
98 /// Its monotonic epoch must agree with the executor for absolute deadlines.
99 pub fn with_monotonic_clock(
100 source: &dyn RealtimeSource,
101 monotonic_clock: &'a dyn MonotonicClock,
102 ) -> Result<Self> {
103 let manager = Self::with_clock(monotonic_clock);
104 manager.synchronize(source)?;
105 Ok(manager)
106 }
107
108 /// Start with invalid UTC; elapsed time is available immediately.
109 pub fn unsynchronized() -> Self {
110 Self::with_clock(&EMBASSY_CLOCK)
111 }
112
113 /// Start with invalid UTC and a platform-specific monotonic source.
114 /// The default resolution constant describes Embassy; custom implementations
115 /// must report their own resolution through `MonotonicClock::resolution`.
116 pub fn with_clock(monotonic_clock: &'a dyn MonotonicClock) -> Self {
117 Self {
118 monotonic_clock,
119 start_time: monotonic_clock.now(),
120 realtime: Mutex::new(RefCell::new(RealtimeStatus {
121 correction_nanoseconds: 0,
122 synchronization: None,
123 })),
124 changes: Mutex::new(Cell::new(0)),
125 change_signal: Signal::new(),
126 }
127 }
128
129 /// Monotonic time since the source's arbitrary epoch, independent of UTC.
130 /// Use this epoch for absolute deadlines; use `uptime` for manager lifetime.
131 pub fn monotonic_now(&self) -> Duration {
132 self.monotonic_clock.now()
133 }
134
135 pub fn monotonic_resolution(&self) -> Duration {
136 self.monotonic_clock.resolution()
137 }
138
139 /// Elapsed time since this manager was initialized, independent of UTC.
140 pub fn uptime(&self) -> Duration {
141 self.monotonic_now() - self.start_time
142 }
143
144 /// Milliseconds modulo 2^32, for wrapping tick consumers such as LVGL.
145 /// Wraps every ~49.7 days; compute differences with wrapping subtraction
146 /// and sample at intervals shorter than one complete wrap.
147 pub fn monotonic_milliseconds_wrapping(&self) -> u32 {
148 self.monotonic_now().as_millis() as u32
149 }
150
151 /// Signed Unix UTC, or Unsynchronized until an epoch has been supplied.
152 /// May jump in either direction; never use for elapsed time. Overflow is an
153 /// error rather than a wrapped timestamp; a later set can recover the clock.
154 pub fn realtime_now(&self) -> Result<Timestamp> {
155 self.realtime.lock(|state| {
156 let state = state.borrow();
157 if state.synchronization.is_none() {
158 return Err(Error::Unsynchronized);
159 }
160 (self.monotonic_now().as_nanos() as i128)
161 .checked_add(state.correction_nanoseconds)
162 .map(Timestamp::from_nanos)
163 .ok_or(Error::Overflow)
164 })
165 }
166
167 /// Replace UTC and its provenance atomically at the current monotonic instant.
168 /// Invalid samples or correction overflow leave all prior state untouched.
169 /// This runtime-owned API does not grant guest users permission to change time.
170 pub fn set_realtime(&self, sample: RealtimeSample) -> Result<()> {
171 if sample.resolution.is_zero() {
172 return Err(Error::InvalidResolution);
173 }
174 let result = self.realtime.lock(|state| {
175 let now = self.monotonic_now();
176 let correction = sample
177 .timestamp
178 .as_nanos()
179 .checked_sub(now.as_nanos() as i128)
180 .ok_or(Error::Overflow)?;
181 *state.borrow_mut() = RealtimeStatus {
182 correction_nanoseconds: correction,
183 synchronization: Some(Synchronization {
184 source: sample.source,
185 at_monotonic: now,
186 resolution: sample.resolution,
187 accuracy: sample.accuracy,
188 }),
189 };
190 Ok(())
191 });
192 // Notify after the clock lock is released: waiters must never run
193 // inside the critical section.
194 if result.is_ok() {
195 self.notify_change();
196 }
197 result
198 }
199
200 /// Sample a trusted source explicitly; failed reads leave existing UTC intact.
201 pub fn synchronize(&self, source: &dyn RealtimeSource) -> Result<()> {
202 self.set_realtime(source.read()?)
203 }
204
205 pub fn status(&self) -> RealtimeStatus {
206 self.realtime.lock(|state| *state.borrow())
207 }
208
209 /// The current synchronization, or `None` while UTC is invalid.
210 pub fn synchronization(&self) -> Option<Synchronization> {
211 self.status().synchronization
212 }
213
214 /// Generation of the UTC state. Increases on every successful
215 /// [`Manager::set_realtime`] and every [`Manager::invalidate`]; read it to
216 /// then wait for the next change with [`Manager::wait_for_change`].
217 pub fn change_generation(&self) -> u64 {
218 self.changes.lock(|changes| changes.get())
219 }
220
221 /// Waits until the UTC state changed after `generation` and returns the new
222 /// generation. The signal has a single consumer: one waiter at a time.
223 pub async fn wait_for_change(&self, generation: u64) -> u64 {
224 loop {
225 let signaled = self.change_signal.wait().await;
226 if signaled > generation {
227 return signaled;
228 }
229 }
230 }
231
232 /// Bumps the generation and signals waiters. Called after the clock lock is
233 /// released, never inside it.
234 fn notify_change(&self) {
235 let generation = self.changes.lock(|changes| {
236 let next = changes.get().wrapping_add(1);
237 changes.set(next);
238 next
239 });
240 self.change_signal.signal(generation);
241 }
242
243 /// Mark UTC invalid without disturbing the monotonic clock or its deadlines.
244 pub fn invalidate(&self) {
245 self.realtime.lock(|state| {
246 *state.borrow_mut() = RealtimeStatus {
247 correction_nanoseconds: 0,
248 synchronization: None,
249 };
250 });
251 self.notify_change();
252 }
253
254 /// Nominal quantization; this remains queryable while UTC is invalid.
255 pub fn realtime_resolution(&self) -> Duration {
256 self.status()
257 .synchronization
258 .map_or(self.monotonic_resolution(), |sync| {
259 sync.resolution.max(self.monotonic_resolution())
260 })
261 }
262}
263
264pub fn initialize(source: &dyn RealtimeSource) -> Result<Manager<'static>> {
265 Manager::new(source)
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271
272 #[test]
273 fn tick_conversion_does_not_overflow_at_counter_limit() {
274 assert_eq!(
275 duration_from_ticks(u64::MAX),
276 Duration::new(18_446_744_073_709, 551_615_000)
277 );
278 assert_eq!(duration_from_ticks(0), Duration::ZERO);
279 assert_eq!(
280 duration_from_ticks(embassy_time::TICK_HZ),
281 Duration::from_secs(1)
282 );
283 }
284}