veecle_telemetry/
time.rs

1//! Time utilities for telemetry timestamping.
2//!
3//! This module provides time-related functionality for telemetry data collection.
4//! It abstracts over different time sources depending on the platform and
5//! feature configuration.
6//!
7//! # Platform Support
8//!
9//! - `std`: Uses system time with high precision
10//! - `freertos`: Uses FreeRTOS time utilities
11//! - `no_std`: Uses monotonic time sources
12//!
13//! # Timestamp Format
14//!
15//! All timestamps are represented as nanoseconds since an epoch.
16//! The specific epoch depends on the platform and configuration:
17//!
18//! - With `system_time` feature: Unix epoch (1970-01-01 00:00:00 UTC)
19//! - Without `system_time` feature: Arbitrary system start time
20
21#[cfg(all(feature = "enable", feature = "freertos", not(feature = "std")))]
22pub(crate) use veecle_osal_freertos::time::*;
23#[cfg(all(feature = "enable", feature = "std"))]
24pub(crate) use veecle_osal_std::time::*;
25
26/// A timestamp with nanosecond resolution.
27///
28/// The value might be relative to the UNIX epoch or an arbitrary moment in time if the system time has not been synced
29/// yet.
30#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
31pub struct Timestamp(pub u64);
32
33impl Timestamp {
34    pub fn as_nanos(&self) -> u64 {
35        self.0
36    }
37}
38
39impl core::fmt::Display for Timestamp {
40    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
41        core::fmt::Display::fmt(&self.0, f)
42    }
43}
44
45#[cfg(feature = "enable")]
46pub(crate) fn now() -> Timestamp {
47    #[cfg(feature = "system_time")]
48    let timestamp_micros = match Time::duration_since_epoch() {
49        Ok(duration) => duration.as_micros(),
50        Err(SystemTimeError::Unsynchronized) => Time::now()
51            .duration_since(Instant::MIN)
52            .expect("should be able to get a duration since the MIN value")
53            .as_micros(),
54        Err(SystemTimeError::EpochIsLaterThanStartTime) => {
55            panic!(
56                "Failed to get duration since epoch: {:?}",
57                SystemTimeError::EpochIsLaterThanStartTime
58            );
59        }
60    };
61
62    #[cfg(not(feature = "system_time"))]
63    let timestamp_micros = Time::now()
64        .duration_since(Instant::MIN)
65        .expect("should be able to get a duration since the MIN value")
66        .as_micros();
67
68    Timestamp(timestamp_micros * 1000)
69}