Skip to main content

nros_core/
clock.rs

1//! Clock API for nros
2//!
3//! This module provides clock abstraction for different time sources:
4//! - **SystemTime**: Wall clock time (affected by system time changes)
5//! - **SteadyTime**: Monotonic time (not affected by system time changes)
6//! - **RosTime**: Simulation time (can be paused/scaled)
7//!
8//! # Example
9//!
10//! ```text
11//! use nros::clock::{Clock, ClockType};
12//!
13//! // Create a system clock
14//! let clock = Clock::system();
15//! let now = clock.now();
16//! println!("Current time: {} sec", now.sec);
17//!
18//! // Create a steady clock for measuring durations
19//! let clock = Clock::steady();
20//! let start = clock.now();
21//! // ... do work ...
22//! let elapsed = clock.now() - start;
23//! ```
24//!
25//! # Where the time comes from
26//!
27//! With a platform port linked (the `platform-clock` feature), every clock
28//! reads the PORT: `nros_platform_time_now_ns` for the wall, and
29//! `nros_platform_clock_ns` for the monotonic. Without one there is no clock
30//! to read, and all three types fall back to an internal counter the caller
31//! advances with `update_steady_time()` — suitable for a bare-metal RTIC or
32//! polling loop, which is the only build where that counter has an owner.
33
34use crate::time::Time;
35
36// AtomicI64 is not available on all platforms (e.g., thumbv7em-none-eabihf)
37// Use AtomicI64 when available, otherwise use a simpler approach
38#[cfg(target_has_atomic = "64")]
39use core::sync::atomic::{AtomicI64, Ordering};
40
41// For platforms without 64-bit atomics, use two 32-bit values
42#[cfg(not(target_has_atomic = "64"))]
43use core::sync::atomic::{AtomicI32, Ordering};
44
45/// Type of clock to use for time queries
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47pub enum ClockType {
48    /// System time (wall clock)
49    ///
50    /// This clock reflects the system's real-time clock and may be
51    /// affected by NTP adjustments, user changes, or daylight saving time.
52    /// Use for timestamps that need to correlate with real-world time.
53    #[default]
54    SystemTime,
55
56    /// Steady/monotonic time
57    ///
58    /// This clock is guaranteed to be monotonically increasing and is
59    /// not affected by system time changes. Use for measuring durations
60    /// and timeouts. Reads the port's `nros_platform_clock_ns` where one is
61    /// linked, and the caller-advanced counter where none is.
62    SteadyTime,
63
64    /// ROS time (simulation time)
65    ///
66    /// This clock can be overridden for simulation purposes. When a
67    /// ROS time override is active — a simulator's or a bag player's
68    /// `/clock` — `now()` returns the overridden time. Otherwise it IS
69    /// [`SystemTime`](Self::SystemTime), which is what `rclcpp`'s
70    /// `ClockType::ROS_TIME` reads with `use_sim_time` false, so a node
71    /// written for simulation still runs standalone.
72    RosTime,
73}
74
75// On platforms with 64-bit atomics, use AtomicI64 directly
76#[cfg(target_has_atomic = "64")]
77mod atomic_time {
78    use super::*;
79
80    /// Global ROS time override (nanoseconds since epoch)
81    /// When set to a non-negative value, `Clock::now()` for `RosTime` clocks
82    /// will return this value instead of system time.
83    pub(super) static ROS_TIME_OVERRIDE_NANOS: AtomicI64 = AtomicI64::new(-1);
84
85    /// Global steady time counter (nanoseconds)
86    /// For `no_std` environments, this counter must be updated manually.
87    pub(super) static STEADY_TIME_NANOS: AtomicI64 = AtomicI64::new(0);
88
89    pub(super) fn get_ros_override() -> i64 {
90        ROS_TIME_OVERRIDE_NANOS.load(Ordering::Relaxed)
91    }
92
93    pub(super) fn set_ros_override(nanos: i64) {
94        ROS_TIME_OVERRIDE_NANOS.store(nanos, Ordering::Relaxed);
95    }
96
97    pub(super) fn get_steady() -> i64 {
98        STEADY_TIME_NANOS.load(Ordering::Relaxed)
99    }
100
101    pub(super) fn set_steady(nanos: i64) {
102        STEADY_TIME_NANOS.store(nanos, Ordering::Relaxed);
103    }
104
105    pub(super) fn add_steady(delta: i64) {
106        STEADY_TIME_NANOS.fetch_add(delta, Ordering::Relaxed);
107    }
108}
109
110// On platforms without 64-bit atomics, use split 32-bit values
111// Note: This is not fully atomic but works for single-threaded embedded contexts
112#[cfg(not(target_has_atomic = "64"))]
113mod atomic_time {
114    use super::*;
115
116    // Split into high and low 32-bit parts
117    static ROS_TIME_OVERRIDE_LOW: AtomicI32 = AtomicI32::new(-1);
118    static ROS_TIME_OVERRIDE_HIGH: AtomicI32 = AtomicI32::new(-1);
119    static STEADY_TIME_LOW: AtomicI32 = AtomicI32::new(0);
120    static STEADY_TIME_HIGH: AtomicI32 = AtomicI32::new(0);
121
122    pub(super) fn get_ros_override() -> i64 {
123        let high = ROS_TIME_OVERRIDE_HIGH.load(Ordering::Relaxed);
124        let low = ROS_TIME_OVERRIDE_LOW.load(Ordering::Relaxed);
125        if high < 0 {
126            -1
127        } else {
128            ((high as i64) << 32) | (low as u32 as i64)
129        }
130    }
131
132    pub(super) fn set_ros_override(nanos: i64) {
133        if nanos < 0 {
134            ROS_TIME_OVERRIDE_HIGH.store(-1, Ordering::Relaxed);
135            ROS_TIME_OVERRIDE_LOW.store(-1, Ordering::Relaxed);
136        } else {
137            ROS_TIME_OVERRIDE_HIGH.store((nanos >> 32) as i32, Ordering::Relaxed);
138            ROS_TIME_OVERRIDE_LOW.store(nanos as i32, Ordering::Relaxed);
139        }
140    }
141
142    pub(super) fn get_steady() -> i64 {
143        let high = STEADY_TIME_HIGH.load(Ordering::Relaxed);
144        let low = STEADY_TIME_LOW.load(Ordering::Relaxed);
145        ((high as i64) << 32) | (low as u32 as i64)
146    }
147
148    pub(super) fn set_steady(nanos: i64) {
149        STEADY_TIME_HIGH.store((nanos >> 32) as i32, Ordering::Relaxed);
150        STEADY_TIME_LOW.store(nanos as i32, Ordering::Relaxed);
151    }
152
153    pub(super) fn add_steady(delta: i64) {
154        let current = get_steady();
155        set_steady(current.saturating_add(delta));
156    }
157}
158
159/// A clock for querying time
160///
161/// Clocks provide access to different time sources. Each node typically
162/// has an associated clock, but you can also create standalone clocks.
163#[derive(Debug, Clone, Copy)]
164pub struct Clock {
165    clock_type: ClockType,
166}
167
168impl Default for Clock {
169    fn default() -> Self {
170        Self::system()
171    }
172}
173
174/// The platform's wall clock, or `None` when this build has no port to ask.
175///
176/// phase-359 W10 (backend sched task). `nros-core` sits BELOW `nros-platform`, so it
177/// cannot depend on it — it declares the two ABI symbols directly, exactly as
178/// `nros-node` already does for `nros_platform_clock_ns` ("every platform port
179/// exports it through the same linkage contract"). The feature is what promises
180/// a port is linked; without it this is `None` and the caller keeps the counter
181/// it had.
182///
183/// ONE symbol since issue 0532 item 5 collapsed the wall clock; this function
184/// was named there as the one place that would change, and it was.
185// phase-359 W10 follow-up — NOT `not(std)`. This used to be gated away on a
186// `std` build, so an image with a port linked read `SystemTime` from
187// `Clock::system()` and `nros_platform_time_now_ns` from the executor's epoch
188// source: two wall clocks, one image. They agree on POSIX by coincidence (both
189// are CLOCK_REALTIME) and stop agreeing the moment a port has an opinion — an
190// RTC-backed or simulated one — because only the port is authoritative and only
191// one of the two readers asked it. The rule W10 set in `nros-node` applies
192// here: when a port is linked it IS the clock, and `std` is what a build
193// without one falls back to.
194#[cfg(feature = "platform-clock")]
195fn platform_wall_clock() -> Option<Time> {
196    unsafe extern "C" {
197        fn nros_platform_time_now_ns() -> u64;
198    }
199    // SAFETY: a bare wall-clock read, no pointer arguments, guaranteed by
200    // whichever port linked the binary — the same contract `nros-node` relies
201    // on for `nros_platform_clock_ns`.
202    //
203    // ONE symbol, so one sample: issue 0532 collapsed the former
204    // `time_since_epoch_{secs,nanos}` pair, which this was written against and
205    // which needed a bounded re-read to survive a second boundary landing
206    // between the two calls. That loop is what the collapse deletes.
207    let ns = unsafe { nros_platform_time_now_ns() };
208    // A port with no RTC returns 0. Reporting the Unix epoch as "now" would be
209    // a wrong answer stated confidently, so say nothing and let the caller's
210    // counter fallback stand.
211    if ns == 0 {
212        return None;
213    }
214    Some(Time::new(
215        (ns / 1_000_000_000) as i32,
216        (ns % 1_000_000_000) as u32,
217    ))
218}
219
220#[cfg(not(feature = "platform-clock"))]
221fn platform_wall_clock() -> Option<Time> {
222    None
223}
224
225/// The platform's MONOTONIC clock, or `None` when this build has no port to ask.
226///
227/// issue 1334 — the sibling of [`platform_wall_clock`], declared the same way
228/// and under the same feature, because it is the same promise: `platform-clock`
229/// means a port is linked, and every port exports both halves
230/// (`nros/platform.h` "Wall clock" and RFC-0073's monotonic export are
231/// MANDATORY, not optional). `nros-node`, `nros-log`, `nros-c` and the `nros`
232/// umbrella already hand-declare this symbol under exactly this contract.
233///
234/// Unlike the wall clock there is no "port with no RTC" case to detect: a
235/// monotonic counter reading 0 is a legitimate answer at boot, so a zero is
236/// passed through rather than read as "no clock".
237#[cfg(feature = "platform-clock")]
238fn platform_steady_clock() -> Option<Time> {
239    unsafe extern "C" {
240        fn nros_platform_clock_ns() -> u64;
241    }
242    // SAFETY: a bare counter read, no pointer arguments, guaranteed by
243    // whichever port linked the binary — the same contract `platform_wall_clock`
244    // above relies on for `nros_platform_time_now_ns`.
245    let ns = unsafe { nros_platform_clock_ns() };
246    Some(Time::new(
247        (ns / 1_000_000_000) as i32,
248        (ns % 1_000_000_000) as u32,
249    ))
250}
251
252#[cfg(not(feature = "platform-clock"))]
253fn platform_steady_clock() -> Option<Time> {
254    None
255}
256
257/// Which source answers the wall clock ([`WallClockState::source`]); the
258/// values of `NROS_WALL_CLOCK_SOURCE_*` in `nros/platform.h`.
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260pub enum WallClockSource {
261    /// The port's own clock (POSIX `CLOCK_REALTIME`; none on FreeRTOS/ThreadX).
262    Platform,
263    /// An SNTP exchange set the offset.
264    Sntp,
265    /// Zenoh HLC timestamps on received samples set the offset.
266    ZenohHlc,
267    /// The board's clock hook.
268    Board,
269    /// A value this crate does not know, from a newer port.
270    Unknown(u8),
271}
272
273/// What the wall-clock stamps mean right now: the answer to
274/// `nros_platform_wall_clock_state()`, field for field.
275///
276/// An application that must not publish unstamped data asks
277/// [`wall_clock_state`] before publishing. While `synced` is false the wall
278/// clock reads 0, so every `header.stamp` is ROS's "unset" time.
279#[repr(C)]
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub struct WallClockState {
282    /// `true`: the wall clock answers real UNIX time.
283    pub synced: bool,
284    /// The raw `NROS_WALL_CLOCK_SOURCE_*` value; [`WallClockState::source`]
285    /// names it.
286    pub source_id: u8,
287    /// How many times the answering source has changed since boot.
288    pub steps: u32,
289}
290
291// The C struct is `{ bool; uint8_t; uint32_t; }`: 8 bytes, `steps` at 4, on
292// every ABI nano-ros targets. A field added on one side only fails here.
293const _: () = {
294    assert!(core::mem::size_of::<WallClockState>() == 8);
295    assert!(core::mem::offset_of!(WallClockState, source_id) == 1);
296    assert!(core::mem::offset_of!(WallClockState, steps) == 4);
297};
298
299impl WallClockState {
300    /// The source answering, or the one that will once it syncs.
301    pub const fn source(&self) -> WallClockSource {
302        match self.source_id {
303            0 => WallClockSource::Platform,
304            1 => WallClockSource::Sntp,
305            2 => WallClockSource::ZenohHlc,
306            3 => WallClockSource::Board,
307            other => WallClockSource::Unknown(other),
308        }
309    }
310}
311
312/// The wall clock's state from the linked port, or `None` when this build has
313/// no port to ask (no `platform-clock`), the same condition under which
314/// [`Clock::system`] falls back to its counter.
315///
316/// Every port DEFINES `nros_platform_wall_clock_state`; a port that does not
317/// fails to link, naming the symbol.
318#[cfg(feature = "platform-clock")]
319pub fn wall_clock_state() -> Option<WallClockState> {
320    // The C ABI's name for the struct, so this declaration reads as the
321    // header's prototype.
322    #[allow(non_camel_case_types)]
323    type nros_wall_clock_state_t = WallClockState;
324    unsafe extern "C" {
325        fn nros_platform_wall_clock_state() -> nros_wall_clock_state_t;
326    }
327    // SAFETY: no arguments; returns a `repr(C)` struct whose layout is
328    // asserted above against the C declaration.
329    Some(unsafe { nros_platform_wall_clock_state() })
330}
331
332/// See the `platform-clock` variant: no port is linked, so there is no state.
333#[cfg(not(feature = "platform-clock"))]
334pub fn wall_clock_state() -> Option<WallClockState> {
335    None
336}
337
338impl Clock {
339    /// Create a new clock of the specified type
340    ///
341    /// ADOPT-BOUNDED: rclrs's `Clock::new` returns `(Self, Option<ClockSource>)`,
342    /// handing back the source that drives a ROS-time clock. This returns the clock
343    /// alone. Simulated time is ONE process-wide override, set with the associated
344    /// [`Clock::set_ros_time_override`], not a per-clock source: a per-clock source
345    /// is a shared owner (`Arc`) the `core` targets do not have, and `const fn` is
346    /// what lets a `Clock` be a `static`.
347    pub const fn new(clock_type: ClockType) -> Self {
348        Self { clock_type }
349    }
350
351    /// Create a system time clock
352    ///
353    /// System time reflects the real-world wall clock time.
354    pub const fn system() -> Self {
355        Self {
356            clock_type: ClockType::SystemTime,
357        }
358    }
359
360    /// Create a steady (monotonic) time clock
361    ///
362    /// Steady time is guaranteed to only increase and is not affected
363    /// by system time changes.
364    pub const fn steady() -> Self {
365        Self {
366            clock_type: ClockType::SteadyTime,
367        }
368    }
369
370    /// Create a ROS time clock
371    ///
372    /// ROS time can be overridden for simulation. When no override is
373    /// active, it returns system time — the identical expression
374    /// [`Clock::system`] evaluates, so the two cannot drift.
375    pub const fn ros_time() -> Self {
376        Self {
377            clock_type: ClockType::RosTime,
378        }
379    }
380
381    /// Get the clock type
382    pub const fn clock_type(&self) -> ClockType {
383        self.clock_type
384    }
385
386    /// The wall clock, in ONE place — issue 1334.
387    ///
388    /// Two clock types answer "what is the wall time", and they must answer it
389    /// identically: `SystemTime` always, and `RosTime` whenever no `/clock`
390    /// override is installed. Before this they were two expressions, and only
391    /// the first was ever moved onto the port (phase-359 W10), so `RosTime`'s
392    /// fallback was left reading the counter — a value nothing in the tree
393    /// advances. One expression is what keeps the next move from splitting
394    /// them again.
395    ///
396    /// - **A platform port linked** (`platform-clock`): the port's wall clock.
397    ///   It is the authority, and an image must not hold two answers to "what
398    ///   time is it".
399    /// - **No port**: the internal counter, which the caller advances with
400    ///   `update_steady_time()`. A build with no port has no clock to read, so
401    ///   this is the honest answer rather than a fallback with an opinion.
402    fn wall_now() -> Time {
403        // phase-359 W10 (backend tier) — a wall clock that does not need the
404        // `std` FEATURE. Before this, `SystemTime` fell back to the STEADY
405        // counter unconditionally: the same value a monotonic clock returns,
406        // presented as time since the Unix epoch. That is not a degraded wall
407        // clock, it is a different quantity, and the only thing standing
408        // between a build and it was whether some crate in the graph happened
409        // to name `std`.
410        if let Some(t) = platform_wall_clock() {
411            return t;
412        }
413        // phase-518 (issue 2071) -- a port with no RTC (FreeRTOS, ThreadX)
414        // answers 0, and the counter below is the constant 0 on every image
415        // with a port linked, because nothing advances it. So a `RosTime`
416        // timer with no `/clock` source never fired on those ports: the
417        // stock `rclcpp::create_timer(this, get_clock(), ...)` of every
418        // Autoware node was dead. Boot-relative time is what issue 0758
419        // already says those images stamp with, and it ADVANCES, which is the
420        // property a timer needs. A port that can state an epoch still wins.
421        if let Some(t) = platform_steady_clock() {
422            return t;
423        }
424        Time::from_nanos(atomic_time::get_steady())
425    }
426
427    /// The monotonic clock, in ONE place — issue 1334's sibling site.
428    ///
429    /// Same rule as `Self::wall_now`, one clock over: a linked port IS the
430    /// monotonic clock, and the counter is what a build with no port was
431    /// given.
432    ///
433    /// This overturns half of phase-359 W10, which moved `SystemTime` onto the
434    /// port and left this line reading "`SteadyTime` is the counter on every
435    /// flavour, deliberately: it is advanced by its owner … and the port's
436    /// monotonic export is the executor's business, not this type's". The
437    /// owner never arrived — nothing outside this file's own tests has ever
438    /// called `update_steady_time` — so on every shipped image
439    /// `Clock::steady().now()` was the constant 0, while the C surface
440    /// answered the SAME question (`RCL_STEADY_TIME`) with
441    /// `nros_platform_clock_ns`. That is issue 1334's complaint exactly, one
442    /// clock over: two surfaces, one image, different answers, and the Rust
443    /// one is not a clock. W10's own rule settles it — when a port is linked
444    /// it IS the clock — and the counter keeps its documented RTIC meaning in
445    /// the one build where it is the only source.
446    fn steady_now() -> Time {
447        if let Some(t) = platform_steady_clock() {
448            return t;
449        }
450        Time::from_nanos(atomic_time::get_steady())
451    }
452
453    /// Get the current time from this clock
454    ///
455    /// # Platform behavior
456    ///
457    /// - **A platform port linked** (`platform-clock`): the port's clocks —
458    ///   `nros_platform_time_now_ns` for the wall, `nros_platform_clock_ns`
459    ///   for the monotonic. The port is the authority, and an image must not
460    ///   hold two answers to "what time is it".
461    /// - **No port**: the internal counter, which the caller advances with
462    ///   `update_steady_time()`.
463    ///
464    /// There is no `std::time` arm. The platform API IS the
465    /// clock: a build with a port reads it, a build without one has no clock to
466    /// read and says so with the counter it was given. `SystemTime` used to sit
467    /// here as a third answer for hosted builds, which made "what time is it"
468    /// depend on whether some crate in the graph happened to name `std`.
469    ///
470    /// `RosTime` with no override is `SystemTime`, in EVERY build shape and by
471    /// construction — both arms call `Self::wall_now`. That is rclcpp's
472    /// contract (`ClockType::ROS_TIME` with `use_sim_time` false reads the
473    /// system clock), what five doc sites across three languages already
474    /// promised, and what the C surface already did; the Rust arm once said
475    /// something else.
476    pub fn now(&self) -> Time {
477        match self.clock_type {
478            ClockType::SystemTime => Self::wall_now(),
479            ClockType::SteadyTime => Self::steady_now(),
480            ClockType::RosTime => {
481                let override_nanos = atomic_time::get_ros_override();
482                if override_nanos >= 0 {
483                    // A `/clock` source is driving simulated time.
484                    Time::from_nanos(override_nanos)
485                } else {
486                    // None is. rclcpp reads the system clock here and so do we
487                    // — the same expression `Clock::system()` evaluates, not a
488                    // copy of it (issue 1334).
489                    Self::wall_now()
490                }
491            }
492        }
493    }
494
495    /// Set a ROS time override
496    ///
497    /// When set, all `RosTime` clocks will return this time instead of
498    /// system time. This is useful for simulation.
499    ///
500    /// # Arguments
501    /// * `nanos` - Nanoseconds since epoch
502    pub fn set_ros_time_override(nanos: i64) {
503        atomic_time::set_ros_override(nanos);
504    }
505
506    /// Set a ROS time override from a Time value
507    pub fn set_ros_time_override_time(time: Time) {
508        Self::set_ros_time_override(time.to_nanos());
509    }
510
511    /// Clear the ROS time override
512    ///
513    /// After clearing, `RosTime` clocks will return system time again.
514    pub fn clear_ros_time_override() {
515        atomic_time::set_ros_override(-1);
516    }
517
518    /// Check if a ROS time override is active
519    pub fn is_ros_time_override_active() -> bool {
520        atomic_time::get_ros_override() >= 0
521    }
522
523    /// Get the current ROS time override value (if active)
524    pub fn get_ros_time_override() -> Option<Time> {
525        let nanos = atomic_time::get_ros_override();
526        if nanos >= 0 {
527            Some(Time::from_nanos(nanos))
528        } else {
529            None
530        }
531    }
532
533    /// Update the steady time counter
534    ///
535    /// For environments with NO platform port, call this periodically from
536    /// your main loop or RTIC task to advance the clocks. With a port linked
537    /// this counter is not what any clock reads — the port is —
538    /// and advancing it has no observable effect.
539    ///
540    /// # Arguments
541    /// * `delta_nanos` - Nanoseconds elapsed since last call
542    pub fn update_steady_time(delta_nanos: i64) {
543        atomic_time::add_steady(delta_nanos);
544    }
545
546    /// Update the steady time counter (milliseconds version)
547    ///
548    /// Convenience method for RTIC tasks using millisecond intervals.
549    ///
550    /// # Arguments
551    /// * `delta_ms` - Milliseconds elapsed since last call
552    pub fn update_steady_time_ms(delta_ms: u64) {
553        let delta_nanos = delta_ms as i64 * 1_000_000;
554        Self::update_steady_time(delta_nanos);
555    }
556
557    /// Set the steady time counter to a specific value
558    ///
559    /// Use this to initialize the clock or synchronize with an external
560    /// time source.
561    pub fn set_steady_time(nanos: i64) {
562        atomic_time::set_steady(nanos);
563    }
564
565    /// Get the current steady time counter value
566    pub fn get_steady_time_nanos() -> i64 {
567        atomic_time::get_steady()
568    }
569}
570
571#[cfg(test)]
572mod tests {
573    use super::*;
574
575    /// Serialises every test that touches the process-global clock state —
576    /// issue 1334.
577    ///
578    /// The override, the counter and (below) the fake port are all statics, and
579    /// `cargo test` runs these in parallel threads: a test that SETS one and
580    /// reads it back is racing every sibling that writes the same static. That
581    /// was already true before this guard existed (`test_ros_time_override` and
582    /// `test_steady_time_update` write two different globals that `Clock::now`
583    /// reads together) and it becomes load-bearing here, because the new tests
584    /// move the fake port's hands while another test asserts where they point.
585    ///
586    /// A spin lock rather than `std::sync::Mutex`: this crate is `#![no_std]`
587    /// and `std` is a FEATURE, so a `Mutex` here would confine the guard — and
588    /// therefore every test using it — to the `std` flavour, which is not where
589    /// the `platform-clock` tests need to live.
590    struct ClockGuard;
591
592    static CLOCK_LOCK: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
593
594    impl ClockGuard {
595        fn acquire() -> Self {
596            while CLOCK_LOCK
597                .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
598                .is_err()
599            {
600                core::hint::spin_loop();
601            }
602            Self
603        }
604    }
605
606    impl Drop for ClockGuard {
607        fn drop(&mut self) {
608            // Leave the globals as a fresh process has them, so a test that
609            // does NOT take the guard still sees the documented defaults.
610            Clock::clear_ros_time_override();
611            Clock::set_steady_time(0);
612            #[cfg(feature = "platform-clock")]
613            fake_port::reset();
614            CLOCK_LOCK.store(false, Ordering::Release);
615        }
616    }
617
618    /// The stand-in platform port for the `platform-clock` flavour.
619    ///
620    /// One definition of each symbol, at module level, because a linker sees
621    /// one test binary: the wall symbol used to be defined INSIDE the single
622    /// test that needed it, which works exactly until a second test needs it
623    /// too. Both hands MOVE (they are atomics, not constants), which is what
624    /// lets a test assert that a clock ADVANCES rather than merely that it
625    /// reads a magic number.
626    #[cfg(feature = "platform-clock")]
627    mod fake_port {
628        use core::sync::atomic::{AtomicU64, Ordering};
629
630        /// 2001-09-09T01:46:40Z — a fixed instant no real clock will return.
631        pub(super) const WALL_BASE_NS: u64 = 1_000_000_000 * 1_000_000_000;
632        /// 42 s of uptime — no relation to `WALL_BASE_NS`, deliberately: the
633        /// two clocks are different quantities and a test must not be able to
634        /// pass by reading the wrong one.
635        pub(super) const STEADY_BASE_NS: u64 = 42_000_000_000;
636
637        pub(super) static WALL_NS: AtomicU64 = AtomicU64::new(WALL_BASE_NS);
638        pub(super) static STEADY_NS: AtomicU64 = AtomicU64::new(STEADY_BASE_NS);
639
640        pub(super) fn reset() {
641            WALL_NS.store(WALL_BASE_NS, Ordering::Relaxed);
642            STEADY_NS.store(STEADY_BASE_NS, Ordering::Relaxed);
643        }
644
645        #[unsafe(no_mangle)]
646        extern "C" fn nros_platform_time_now_ns() -> u64 {
647            WALL_NS.load(Ordering::Relaxed)
648        }
649
650        #[unsafe(no_mangle)]
651        extern "C" fn nros_platform_clock_ns() -> u64 {
652            STEADY_NS.load(Ordering::Relaxed)
653        }
654
655        /// The state the fake port reports: synced on SNTP after 3 steps, a
656        /// combination no default could produce, so a test reading it sees
657        /// the PORT's answer and not a constant on this side.
658        pub(super) const STATE: super::WallClockState = super::WallClockState {
659            synced: true,
660            source_id: 1,
661            steps: 3,
662        };
663
664        #[unsafe(no_mangle)]
665        extern "C" fn nros_platform_wall_clock_state() -> super::WallClockState {
666            STATE
667        }
668    }
669
670    /// The state query returns the linked port's answer, field for field.
671    #[test]
672    #[cfg(feature = "platform-clock")]
673    fn wall_clock_state_reads_the_linked_port() {
674        let st = wall_clock_state().expect("a port is linked");
675        assert_eq!(st, fake_port::STATE);
676        assert!(st.synced);
677        assert_eq!(st.source(), WallClockSource::Sntp);
678        assert_eq!(st.steps, 3);
679    }
680
681    /// With no port there is no state, rather than an invented one.
682    #[test]
683    #[cfg(not(feature = "platform-clock"))]
684    fn wall_clock_state_is_none_without_a_port() {
685        assert_eq!(wall_clock_state(), None);
686    }
687
688    /// Every C source value has a name, and an unknown one is kept.
689    #[test]
690    fn wall_clock_source_names_each_c_value() {
691        let named = |id| {
692            WallClockState {
693                synced: false,
694                source_id: id,
695                steps: 0,
696            }
697            .source()
698        };
699        assert_eq!(named(0), WallClockSource::Platform);
700        assert_eq!(named(1), WallClockSource::Sntp);
701        assert_eq!(named(2), WallClockSource::ZenohHlc);
702        assert_eq!(named(3), WallClockSource::Board);
703        assert_eq!(named(9), WallClockSource::Unknown(9));
704    }
705
706    #[test]
707    fn test_clock_type_default() {
708        let clock_type = ClockType::default();
709        assert_eq!(clock_type, ClockType::SystemTime);
710    }
711
712    #[test]
713    fn test_clock_constructors() {
714        let system = Clock::system();
715        assert_eq!(system.clock_type(), ClockType::SystemTime);
716
717        let steady = Clock::steady();
718        assert_eq!(steady.clock_type(), ClockType::SteadyTime);
719
720        let ros = Clock::ros_time();
721        assert_eq!(ros.clock_type(), ClockType::RosTime);
722
723        let custom = Clock::new(ClockType::SteadyTime);
724        assert_eq!(custom.clock_type(), ClockType::SteadyTime);
725    }
726
727    #[test]
728    fn test_clock_default() {
729        let clock = Clock::default();
730        assert_eq!(clock.clock_type(), ClockType::SystemTime);
731    }
732
733    #[test]
734    fn test_ros_time_override() {
735        let _guard = ClockGuard::acquire();
736        // Clear any existing override
737        Clock::clear_ros_time_override();
738        assert!(!Clock::is_ros_time_override_active());
739        assert!(Clock::get_ros_time_override().is_none());
740
741        // Set override
742        let override_time = Time::new(1234567890, 123456789);
743        Clock::set_ros_time_override_time(override_time);
744        assert!(Clock::is_ros_time_override_active());
745        assert_eq!(Clock::get_ros_time_override(), Some(override_time));
746
747        // ROS clock should return override time
748        let ros_clock = Clock::ros_time();
749        let now = ros_clock.now();
750        assert_eq!(now, override_time);
751
752        // Clear override
753        Clock::clear_ros_time_override();
754        assert!(!Clock::is_ros_time_override_active());
755    }
756
757    #[test]
758    fn test_steady_time_update() {
759        let _guard = ClockGuard::acquire();
760        // Reset steady time
761        Clock::set_steady_time(0);
762        assert_eq!(Clock::get_steady_time_nanos(), 0);
763
764        // Update by milliseconds
765        Clock::update_steady_time_ms(100);
766        assert_eq!(Clock::get_steady_time_nanos(), 100_000_000);
767
768        // Update by nanoseconds
769        Clock::update_steady_time(500_000_000);
770        assert_eq!(Clock::get_steady_time_nanos(), 600_000_000);
771
772        // Steady clock should return updated time -- in the build where the
773        // counter is the only clock there is. With a port linked the port
774        // outranks it (issue 1334), which is the test below.
775        #[cfg(not(feature = "platform-clock"))]
776        {
777            let steady_clock = Clock::steady();
778            let now = steady_clock.now();
779            assert_eq!(now.to_nanos(), 600_000_000);
780        }
781    }
782
783    /// With NO port linked there is no clock, and all three types say so with
784    /// the one counter they were given — issue 1334.
785    ///
786    /// This replaces ~~`test_system_clock_returns_nonzero`~~, which asserted
787    /// `now.sec > 0` for `Clock::system()` in exactly this shape. That claim
788    /// was false from the day phase-359 W10 removed the `std::time` arm — a
789    /// portless build reads the counter, which is 0 — and nobody saw it,
790    /// because its `all(std, not(platform-clock))` gate put it in no lane at
791    /// all: the one nros-core feature lane is `std,platform-clock`, and the
792    /// default lane has no `std`. A test in no lane is the shape CLAUDE.md's
793    /// `required-features` rule names, one cfg over.
794    ///
795    /// What it asserts instead is the property that IS true here, and it is the
796    /// portless half of this issue's fix: `RosTime` with no override reads
797    /// whatever `SystemTime` reads, whatever that turns out to be.
798    #[test]
799    #[cfg(not(feature = "platform-clock"))]
800    fn without_a_port_every_clock_is_the_counter() {
801        let _guard = ClockGuard::acquire();
802        Clock::clear_ros_time_override();
803        Clock::set_steady_time(7_500_000_000);
804
805        assert_eq!(Clock::system().now().to_nanos(), 7_500_000_000);
806        assert_eq!(Clock::steady().now().to_nanos(), 7_500_000_000);
807        assert_eq!(
808            Clock::ros_time().now().to_nanos(),
809            7_500_000_000,
810            "with no override and no port, ROS time is what system time is"
811        );
812    }
813
814    /// phase-359 W10 follow-up — a linked port OUTRANKS `std` for the wall
815    /// clock, on a `std` build too.
816    ///
817    /// This is the one configuration where the two disagree observably, and it
818    /// is why the test image defines the port symbol itself (`fake_port`): the
819    /// value returned is nothing like a real `SystemTime`, so a
820    /// `Clock::system()` that answered with `SystemTime::now()` — which is what
821    /// this file did before, because `platform_wall_clock` was gated
822    /// `not(std)` — fails loudly rather than coincidentally passing. On POSIX
823    /// both sources are CLOCK_REALTIME, so nothing short of a port with an
824    /// opinion can tell them apart.
825    #[test]
826    #[cfg(feature = "platform-clock")]
827    fn platform_port_outranks_std_for_the_wall_clock() {
828        let _guard = ClockGuard::acquire();
829        let now = Clock::system().now();
830        assert_eq!(
831            now.sec, 1_000_000_000,
832            "Clock::system() must read the linked port, not SystemTime"
833        );
834        assert_eq!(now.nanosec, 0);
835    }
836
837    /// ROS time with no `/clock` source is the WALL clock, and it RUNS — issue
838    /// 1334, and the negative control for the whole fix.
839    ///
840    /// Before the fix this arm read `STEADY_TIME_NANOS`, a counter whose own
841    /// doc says it is "advanced by its owner" and which nothing outside this
842    /// file's tests has ever advanced. So the assertion that fails on the
843    /// pre-fix tree is the first one (the reading was 0, not the port's wall
844    /// clock) and the one after it (a clock that does not move is not a
845    /// clock).
846    ///
847    /// `rclcpp`'s `ClockType::ROS_TIME` with `use_sim_time` false reads the
848    /// system clock; five doc sites in this tree across Rust, C and C++ said we
849    /// did too; and the C surface (`rclc_clock_get_now_time(RCL_ROS_TIME)`)
850    /// always did. This is the arm that disagreed with all of them.
851    #[test]
852    #[cfg(feature = "platform-clock")]
853    fn ros_time_with_no_override_reads_the_port_wall_clock() {
854        let _guard = ClockGuard::acquire();
855        Clock::clear_ros_time_override();
856        // A counter reading that is nothing like the wall clock, so reading the
857        // wrong source cannot pass by coincidence.
858        Clock::set_steady_time(1_234);
859
860        let ros = Clock::ros_time().now();
861        assert_eq!(
862            ros,
863            Clock::system().now(),
864            "with no override, ROS time IS system time"
865        );
866        assert_eq!(ros.sec, 1_000_000_000, "it must be the PORT's wall clock");
867
868        // ...and it advances with it. Two seconds on the port's hand.
869        fake_port::WALL_NS.fetch_add(2_000_000_000, core::sync::atomic::Ordering::Relaxed);
870        let later = Clock::ros_time().now();
871        assert_eq!(
872            later.to_nanos() - ros.to_nanos(),
873            2_000_000_000,
874            "ROS time with no source must ADVANCE with the wall clock"
875        );
876    }
877
878    /// A `/clock` override still wins over the wall clock — the sim-time path
879    /// this fix must not touch.
880    #[test]
881    #[cfg(feature = "platform-clock")]
882    fn an_override_still_outranks_the_wall_clock() {
883        let _guard = ClockGuard::acquire();
884        Clock::set_ros_time_override(5_000_000_000);
885        assert_eq!(Clock::ros_time().now().to_nanos(), 5_000_000_000);
886        assert_ne!(
887            Clock::ros_time().now(),
888            Clock::system().now(),
889            "a simulated clock must not be shadowed by the wall clock"
890        );
891        Clock::clear_ros_time_override();
892        assert_eq!(Clock::ros_time().now(), Clock::system().now());
893    }
894
895    /// The sibling site: a linked port outranks the counter for the MONOTONIC
896    /// clock too — issue 1334's sweep.
897    ///
898    /// Fails on the pre-fix tree, where `SteadyTime` read the counter on every
899    /// flavour and therefore returned 0 in every shipped image, while the C
900    /// surface answered `RCL_STEADY_TIME` with `nros_platform_clock_ns`.
901    #[test]
902    #[cfg(feature = "platform-clock")]
903    fn platform_port_outranks_the_counter_for_the_steady_clock() {
904        let _guard = ClockGuard::acquire();
905        Clock::set_steady_time(1_234);
906
907        let now = Clock::steady().now();
908        assert_eq!(
909            now.to_nanos(),
910            fake_port::STEADY_BASE_NS as i64,
911            "Clock::steady() must read the linked port, not the counter"
912        );
913        assert_ne!(
914            now.to_nanos(),
915            Clock::system().now().to_nanos(),
916            "the monotonic clock is a different quantity from the wall clock"
917        );
918
919        fake_port::STEADY_NS.fetch_add(250_000_000, core::sync::atomic::Ordering::Relaxed);
920        assert_eq!(
921            Clock::steady().now().to_nanos() - now.to_nanos(),
922            250_000_000
923        );
924    }
925}