rs_matter_node_core/rtc.rs
1/*
2 *
3 * Copyright (c) 2026 Project CHIP Authors
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18//! The clock of the node: its Last-Known-Good UTC Time, the current UTC time
19//! when it is known, and the Trusted Time Source.
20
21use core::num::NonZeroU8;
22
23use crate::dm::{
24 AttrChangeNotifier, AttrId, ClusterId, EndptId, EventEmitter, EventId, NodeId, EVENT_DATA_TAG,
25 ROOT_ENDPOINT_ID,
26};
27use crate::error::Error;
28use crate::im::EventPriority;
29use crate::persist::{
30 KvBlobStore, KvBlobStoreAccess, Persist, LKG_UTC_KEY, TRUSTED_TIME_SOURCE_KEY,
31};
32use crate::tlv::{FromTLV, TLVWrite, ToTLV};
33use crate::utils::epoch::{UtcTime, FIRMWARE_BUILD_MATTER_US};
34use crate::utils::init::{init, Init};
35use crate::utils::timers::Instant;
36
37// The IDs of the Time Synchronization cluster, of the attributes the clock
38// changes, and of its `MissingTrustedTimeSource` event
39const TIME_SYNC_CLUSTER_ID: ClusterId = 0x0038;
40const UTC_TIME_ATTR_ID: AttrId = 0x00;
41const GRANULARITY_ATTR_ID: AttrId = 0x01;
42const TIME_SOURCE_ATTR_ID: AttrId = 0x02;
43const TRUSTED_TIME_SOURCE_ATTR_ID: AttrId = 0x03;
44const MISSING_TRUSTED_TIME_SOURCE_EVENT_ID: EventId = 0x04;
45
46/// The granularity of the current UTC time.
47///
48/// The variants are the ones of the Time Synchronization cluster.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50#[cfg_attr(feature = "defmt", derive(defmt::Format))]
51pub enum TimeGranularity {
52 NoTime,
53 Minutes,
54 Seconds,
55 Milliseconds,
56 Microseconds,
57}
58
59/// The source of the current UTC time.
60///
61/// The variants are the ones of the Time Synchronization cluster.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63#[cfg_attr(feature = "defmt", derive(defmt::Format))]
64pub enum TimeSource {
65 None,
66 Unknown,
67 Admin,
68 NodeTimeCluster,
69 NonMatterSNTP,
70 NonMatterNTP,
71 MatterSNTP,
72 MatterNTP,
73 MixedNTP,
74 NonMatterSNTPNTS,
75 NonMatterNTPNTS,
76 MatterSNTPNTS,
77 MatterNTPNTS,
78 MixedNTPNTS,
79 CloudSource,
80 PTP,
81 GNSS,
82}
83
84/// Last-Known-Good UTC Time tracking for the device (Matter Core spec).
85///
86/// The persisted `utc_us` field is the spec-mandated stored
87/// fallback used by cert path validation when no live time
88/// synchronization is available; it is seeded from
89/// [`crate::utils::epoch::FIRMWARE_BUILD_MATTER_US`] on a
90/// freshly-flashed device.
91///
92/// `anchor`, `granularity`, and `source` are **volatile** — they
93/// describe the current monotonic-clock anchoring around the most
94/// recent `set_utc_time` call. After reboot, `anchor` is
95/// `None` (no live current-time tracking is active), so the TimeSync
96/// cluster reports `UTCTime = Null`, `Granularity = NoTimeGranularity`
97/// and `TimeSource = None` (per spec) — while
98/// `utc_us` still carries the persisted LKG value for cert validity.
99pub struct Rtc {
100 /// Last-Known-Good UTC time, Matter-epoch microseconds.
101 utc_us: u64,
102 /// Same as `utc_us` except always equal to the last persisted value.
103 utc_us_persisted: u64,
104 /// Granularity at the time of the last `set_utc_time` call, with
105 /// the "one level lower than supplied" step-down already
106 /// applied and floored at `MinutesGranularity`.
107 /// **Not persisted** — resets to `NoTimeGranularity` at boot,
108 /// matching the `anchor = None` post-reboot state.
109 granularity: TimeGranularity,
110 /// Authority that last called `set_utc_time`. **Not persisted** —
111 /// resets to `None` at boot.
112 source: TimeSource,
113 /// `Instant::now()` captured at the last `set_utc_time` call.
114 /// Volatile — `None` after reboot until next set.
115 anchor: Option<Instant>,
116 /// Configured Trusted Time Source for the device (Matter Core spec).
117 /// At most one entry; the fabric that
118 /// installed it owns it and is cleared on fabric removal.
119 /// Persisted under [`crate::persist::TRUSTED_TIME_SOURCE_KEY`].
120 trusted_time_source: Option<TrustedTimeSource>,
121}
122
123impl Default for Rtc {
124 fn default() -> Self {
125 Self::new()
126 }
127}
128
129impl Rtc {
130 #[inline(always)]
131 pub const fn new() -> Self {
132 Self {
133 utc_us: FIRMWARE_BUILD_MATTER_US,
134 utc_us_persisted: FIRMWARE_BUILD_MATTER_US,
135 granularity: TimeGranularity::NoTime,
136 source: TimeSource::None,
137 anchor: None,
138 trusted_time_source: None,
139 }
140 }
141
142 /// Return an in-place initializer for `LkgUtc`.
143 pub fn init() -> impl Init<Self> {
144 init!(Self {
145 utc_us: FIRMWARE_BUILD_MATTER_US,
146 utc_us_persisted: FIRMWARE_BUILD_MATTER_US,
147 granularity: TimeGranularity::NoTime,
148 source: TimeSource::None,
149 anchor: None,
150 trusted_time_source: None,
151 })
152 }
153
154 fn reset(&mut self) {
155 self.utc_us = FIRMWARE_BUILD_MATTER_US;
156 self.utc_us_persisted = FIRMWARE_BUILD_MATTER_US;
157 self.granularity = TimeGranularity::NoTime;
158 self.source = TimeSource::None;
159 self.anchor = None;
160 self.trusted_time_source = None;
161 }
162
163 /// Reset the clock and remove what is persisted for it from `store`
164 pub fn reset_persist<S: KvBlobStore>(
165 &mut self,
166 mut store: S,
167 buf: &mut [u8],
168 ) -> Result<(), Error> {
169 self.reset();
170
171 let result = store.remove(LKG_UTC_KEY, buf);
172
173 result.and(store.remove(TRUSTED_TIME_SOURCE_KEY, buf))
174 }
175
176 /// Load the Last-Known-Good UTC Time and the Trusted Time Source from `kv`
177 pub fn load_persist<S: KvBlobStoreAccess>(&mut self, kv: S) -> Result<(), Error> {
178 self.reset();
179
180 let mut persist = Persist::new(kv);
181
182 // Load the persisted Last-Known-Good UTC Time, if any.
183 // Floor at `FIRMWARE_BUILD_MATTER_US` per Matter Core spec -
184 // the on-disk value must never regress us
185 // below the build timestamp (the documented lower bound
186 // we never adjust backwards past).
187 if let Some(stored) = persist.load_tlv::<u64>(LKG_UTC_KEY)? {
188 let floor = FIRMWARE_BUILD_MATTER_US;
189
190 self.utc_us_persisted = stored;
191 self.utc_us = stored.max(floor);
192 }
193
194 // Load the persisted Trusted Time Source, if any.
195 self.trusted_time_source = persist.load_tlv(TRUSTED_TIME_SOURCE_KEY)?;
196
197 Ok(())
198 }
199
200 /// Return the configured Trusted Time Source, or `None` if unset
201 /// (Matter Core spec).
202 pub fn trusted_time_source(&self) -> Option<TrustedTimeSource> {
203 self.trusted_time_source
204 }
205
206 /// Install or clear the Trusted Time Source (Matter Core spec).
207 /// `fab_idx` is the fabric performing the change —
208 /// recorded so that fabric removal can clear an entry it owns.
209 pub fn set_trusted_time_source<E: EventEmitter>(
210 &mut self,
211 source: Option<TrustedTimeSource>,
212 change_notifier: &dyn AttrChangeNotifier,
213 event_emitter: E,
214 ) -> Result<(), Error> {
215 if self.trusted_time_source != source {
216 let previous = self.trusted_time_source;
217
218 self.trusted_time_source = source;
219
220 change_notifier.notify_attr_changed(
221 ROOT_ENDPOINT_ID,
222 TIME_SYNC_CLUSTER_ID,
223 TRUSTED_TIME_SOURCE_ATTR_ID,
224 );
225
226 // Matter Core spec: emit `MissingTrustedTimeSource`
227 // when SetTrustedTimeSource clears a previously-set entry (null
228 // request payload, transitioning from `Some(..)` → `None`).
229 if self.trusted_time_source.is_none() && previous.is_some() {
230 // The event has no fields
231 event_emitter.emit_event(
232 ROOT_ENDPOINT_ID,
233 TIME_SYNC_CLUSTER_ID,
234 MISSING_TRUSTED_TIME_SOURCE_EVENT_ID,
235 EventPriority::Info,
236 |mut tw| {
237 tw.start_struct(&EVENT_DATA_TAG)?;
238 Ok(tw.end_container()?)
239 },
240 )?;
241 }
242 }
243
244 Ok(())
245 }
246
247 /// Install or clear the Trusted Time Source (Matter Core spec).
248 /// `fab_idx` is the fabric performing the change —
249 /// recorded so that fabric removal can clear an entry it owns.
250 /// `source = None` clears any existing entry.
251 ///
252 /// Updates in-memory state, persists under
253 /// [`crate::persist::TRUSTED_TIME_SOURCE_KEY`], and notifies
254 /// subscribers of the `TrustedTimeSource` attribute change.
255 pub fn set_trusted_time_source_persist<S: KvBlobStoreAccess, E: EventEmitter>(
256 &mut self,
257 source: Option<TrustedTimeSource>,
258 persist: &mut Persist<S>,
259 change_notifier: &dyn AttrChangeNotifier,
260 event_emitter: E,
261 ) -> Result<(), Error> {
262 if self.trusted_time_source != source {
263 self.set_trusted_time_source(source, change_notifier, event_emitter)?;
264
265 match source {
266 Some(source) => {
267 persist.store_tlv(TRUSTED_TIME_SOURCE_KEY, source)?;
268 }
269 None => {
270 persist.remove(TRUSTED_TIME_SOURCE_KEY)?;
271 }
272 }
273 }
274
275 Ok(())
276 }
277
278 /// Return the current UTC time if available, or the persisted Last-Known-Good UTC Time otherwise.
279 pub fn utc_time(&self) -> UtcTime {
280 if let Some(anchor) = self.anchor {
281 let elapsed_us = Instant::now()
282 .checked_duration_since(anchor)
283 .map(|d| d.as_micros())
284 .unwrap_or(0);
285
286 UtcTime::Reliable(self.utc_us.saturating_add(elapsed_us))
287 } else {
288 UtcTime::LastKnown(self.utc_us)
289 }
290 }
291
292 /// Return the Granularity reported on the wire for the TimeSync
293 /// cluster's `Granularity` attribute, derived from the most
294 /// recent [`Self::set_utc_time`] (with the spec-required
295 /// step-down and floor already applied) — or `NoTimeGranularity`
296 /// if no `set_utc_time` has been called since boot (per
297 /// the spec, which forbids `NoTimeGranularity` only while
298 /// `UTCTime ≠ Null`).
299 pub fn utc_time_granularity(&self) -> TimeGranularity {
300 if self.anchor.is_some() {
301 self.granularity
302 } else {
303 TimeGranularity::NoTime
304 }
305 }
306
307 /// Return the TimeSource reported on the wire for the TimeSync
308 /// cluster's `TimeSource` attribute — `None` until the first
309 /// [`Self::set_utc_time`] (per spec).
310 pub fn utc_time_source(&self) -> TimeSource {
311 if self.anchor.is_some() {
312 self.source
313 } else {
314 TimeSource::None
315 }
316 }
317
318 /// Update the Last-Known-Good UTC Time (Matter Core spec),
319 /// capturing a fresh monotonic anchor so subsequent
320 /// [`Self::utc_time`] reads advance from the supplied value.
321 ///
322 /// Per the spec: the supplied `granularity` is recorded
323 /// stepped-down by one level (with a floor of
324 /// `Minutes` per spec); the supplied `source`
325 /// is recorded verbatim.
326 ///
327 /// The new value is written to the in-memory state only. Callers that
328 /// need it persisted to `LKG_UTC_KEY` use [`Self::set_utc_time_persist`].
329 pub fn set_utc_time(
330 &mut self,
331 utc_us: u64,
332 granularity: TimeGranularity,
333 source: TimeSource,
334 change_notifier: &dyn AttrChangeNotifier,
335 ) -> bool {
336 let stepped = match granularity {
337 TimeGranularity::Microseconds => TimeGranularity::Milliseconds,
338 TimeGranularity::Milliseconds => TimeGranularity::Seconds,
339 TimeGranularity::Seconds => TimeGranularity::Minutes,
340 // Minutes / NoTime → floor at Minutes
341 // (spec forbids NoTime while UTCTime is non-null).
342 _ => TimeGranularity::Minutes,
343 };
344
345 let changed = self.utc_us != utc_us || self.granularity != stepped || self.source != source;
346
347 if changed || self.anchor.is_none() {
348 self.utc_us = utc_us;
349 self.granularity = stepped;
350 self.source = source;
351 self.anchor = Some(Instant::now());
352
353 change_notifier.notify_attr_changed(
354 ROOT_ENDPOINT_ID,
355 TIME_SYNC_CLUSTER_ID,
356 UTC_TIME_ATTR_ID,
357 );
358 change_notifier.notify_attr_changed(
359 ROOT_ENDPOINT_ID,
360 TIME_SYNC_CLUSTER_ID,
361 GRANULARITY_ATTR_ID,
362 );
363 change_notifier.notify_attr_changed(
364 ROOT_ENDPOINT_ID,
365 TIME_SYNC_CLUSTER_ID,
366 TIME_SOURCE_ATTR_ID,
367 );
368 }
369
370 changed
371 }
372
373 /// Like [`Self::set_utc_time`], and persist the new Last-Known-Good UTC
374 /// Time when it moved by a day or more since it was last persisted
375 pub fn set_utc_time_persist<S: KvBlobStoreAccess>(
376 &mut self,
377 utc_us: u64,
378 granularity: TimeGranularity,
379 source: TimeSource,
380 persist: &mut Persist<S>,
381 change_notifier: &dyn AttrChangeNotifier,
382 ) -> Result<(), Error> {
383 const DELTA: u64 = 24 * 60 * 60 * 1_000_000; // 1 day in microseconds
384
385 let delta = self.utc_us_persisted.abs_diff(utc_us);
386
387 self.set_utc_time(utc_us, granularity, source, change_notifier);
388
389 if delta >= DELTA {
390 // As per the Matter Core spec, we have to persist the new LKG UTC at least once per month
391 // Since this would be an involved math, we instead persist if the new LKG UTC is different
392 // by more than a day than the previous one, which should be good enough to cover the requirement
393 // without needing a separate timer for periodic persistence.
394
395 info!("TimeSync: UTC time changed by more than a day, persisting");
396
397 persist.store_tlv(LKG_UTC_KEY, utc_us)?;
398 self.utc_us_persisted = utc_us;
399 }
400
401 Ok(())
402 }
403}
404
405/// Persisted Trusted Time Source descriptor (Matter Core spec).
406/// Records which fabric configured the source so that fabric removal can
407/// clear it and emit `MissingTrustedTimeSource`.
408#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, FromTLV, ToTLV)]
409#[cfg_attr(feature = "defmt", derive(defmt::Format))]
410pub struct TrustedTimeSource {
411 /// Fabric that installed the source (the `FabricIndex` injected by
412 /// the IM dispatcher into the `SetTrustedTimeSource` invoke).
413 pub fab_idx: NonZeroU8,
414 /// Node ID of the trusted source on that fabric.
415 pub node_id: NodeId,
416 /// Endpoint on the trusted source's node that hosts the TimeSync
417 /// cluster server.
418 pub endpoint: EndptId,
419}
420
421#[cfg(test)]
422#[cfg_attr(coverage_nightly, coverage(off))]
423mod tests {
424 use crate::persist::{MemKv, MemKvBlobStore};
425
426 use super::*;
427
428 #[test]
429 fn persisted_utc_time_loads_back() {
430 let kv = MemKv::new(MemKvBlobStore::default());
431 let utc_us = FIRMWARE_BUILD_MATTER_US + 7 * 24 * 60 * 60 * 1_000_000;
432
433 let mut rtc = Rtc::new();
434 rtc.set_utc_time_persist(
435 utc_us,
436 TimeGranularity::Seconds,
437 TimeSource::Admin,
438 &mut Persist::new(&kv),
439 &(),
440 )
441 .unwrap();
442
443 let mut rtc = Rtc::new();
444 rtc.load_persist(&kv).unwrap();
445
446 assert_eq!(rtc.utc_time(), UtcTime::LastKnown(utc_us));
447 }
448}