Skip to main content

iec61850_kit/common/
time.rs

1use core::fmt;
2
3/// The quality octet of an IEC 61850 `Timestamp` (IEC 61850-7-2 §6.2.3.7 / 8-1 §8.1.3.7).
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub struct TimeQuality {
6    /// Leap seconds are known (the clock is UTC, not TAI-offset-unknown).
7    pub leap_seconds_known: bool,
8    /// The clock has failed.
9    pub clock_failure: bool,
10    /// The clock is not synchronised to an external reference.
11    pub clock_not_synchronized: bool,
12    /// Number of significant bits in the fraction (0..=24); 31 = unspecified.
13    pub accuracy: u8,
14}
15
16impl TimeQuality {
17    /// Synchronised, leap seconds known, accuracy unspecified.
18    pub const SYNCHRONIZED: TimeQuality =
19        TimeQuality { leap_seconds_known: true, clock_failure: false, clock_not_synchronized: false, accuracy: TimeQuality::ACCURACY_UNSPECIFIED };
20    /// Not synchronised, leap seconds unknown.
21    pub const UNSYNCHRONIZED: TimeQuality =
22        TimeQuality { leap_seconds_known: false, clock_failure: false, clock_not_synchronized: true, accuracy: TimeQuality::ACCURACY_UNSPECIFIED };
23    /// The `accuracy` value meaning "unspecified".
24    pub const ACCURACY_UNSPECIFIED: u8 = 31;
25
26    /// Pack into the quality octet.
27    pub const fn to_octet(self) -> u8 {
28        (if self.leap_seconds_known { 0x80 } else { 0 })
29            | (if self.clock_failure { 0x40 } else { 0 })
30            | (if self.clock_not_synchronized { 0x20 } else { 0 })
31            | (self.accuracy & 0x1F)
32    }
33
34    /// Unpack from the quality octet.
35    pub const fn from_octet(b: u8) -> TimeQuality {
36        TimeQuality { leap_seconds_known: b & 0x80 != 0, clock_failure: b & 0x40 != 0, clock_not_synchronized: b & 0x20 != 0, accuracy: b & 0x1F }
37    }
38}
39
40impl Default for TimeQuality {
41    fn default() -> Self {
42        TimeQuality::UNSYNCHRONIZED
43    }
44}
45
46/// IEC 61850 `Timestamp` as encoded on the wire: 32-bit seconds since 1970-01-01 00:00:00
47/// UTC, a 24-bit binary fraction of a second, and a quality octet. Eight octets.
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
49pub struct UtcTime {
50    /// Seconds since the Unix epoch.
51    pub seconds: u32,
52    /// Fraction of a second in units of 2⁻²⁴ s (only the low 24 bits are significant).
53    pub fraction: u32,
54    /// Quality.
55    pub quality: TimeQuality,
56}
57
58impl UtcTime {
59    /// Build from Unix seconds and nanoseconds within the second.
60    ///
61    /// A `nanos` of a second or more carries into `seconds` rather than wrapping the
62    /// fraction: masking it off would turn a caller's off-by-one into a timestamp a whole
63    /// second wrong, silently, in the one field a protection engineer reads first.
64    pub const fn from_unix(seconds: u32, nanos: u32, quality: TimeQuality) -> UtcTime {
65        let seconds = seconds.saturating_add(nanos / 1_000_000_000);
66        // fraction = nanos / 1e9 * 2^24, computed in u64 without overflow.
67        let fraction = (((nanos % 1_000_000_000) as u64) << 24) / 1_000_000_000;
68        UtcTime { seconds, fraction: fraction as u32 & 0x00FF_FFFF, quality }
69    }
70
71    /// Build from whole Unix nanoseconds (saturating at the 32-bit second limit).
72    pub const fn from_unix_nanos(nanos: u64, quality: TimeQuality) -> UtcTime {
73        let s = nanos / 1_000_000_000;
74        let seconds = if s > u32::MAX as u64 { u32::MAX } else { s as u32 };
75        UtcTime::from_unix(seconds, (nanos % 1_000_000_000) as u32, quality)
76    }
77
78    /// Nanoseconds within the second (rounded down).
79    pub const fn nanos(self) -> u32 {
80        (((self.fraction & 0x00FF_FFFF) as u64 * 1_000_000_000) >> 24) as u32
81    }
82
83    /// Whole Unix nanoseconds.
84    pub const fn to_unix_nanos(self) -> u64 {
85        self.seconds as u64 * 1_000_000_000 + self.nanos() as u64
86    }
87
88    /// The eight wire octets.
89    pub const fn to_octets(self) -> [u8; 8] {
90        let s = self.seconds.to_be_bytes();
91        let f = self.fraction & 0x00FF_FFFF;
92        [s[0], s[1], s[2], s[3], (f >> 16) as u8, (f >> 8) as u8, f as u8, self.quality.to_octet()]
93    }
94
95    /// Decode from the eight wire octets.
96    pub const fn from_octets(o: [u8; 8]) -> UtcTime {
97        UtcTime {
98            seconds: u32::from_be_bytes([o[0], o[1], o[2], o[3]]),
99            fraction: ((o[4] as u32) << 16) | ((o[5] as u32) << 8) | o[6] as u32,
100            quality: TimeQuality::from_octet(o[7]),
101        }
102    }
103}
104
105/// IEC 61850 `EntryTime` — ISO 9506 `BinaryTime` in its six-octet form (`BTIME6`).
106///
107/// Four octets of milliseconds since midnight, then two of days since **1984-01-01**, which
108/// is MMS's epoch rather than Unix's. It is what a report's `TimeOfEntry` and a buffered
109/// report control block's `TimeOfEntry` carry, and it is a different type from [`UtcTime`]
110/// on the wire and here — one is 8 octets with a quality byte, the other is 6 with neither.
111#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
112pub struct EntryTime {
113    /// Milliseconds since midnight (`0..86_400_000`).
114    pub millis_of_day: u32,
115    /// Days since 1984-01-01.
116    pub days_since_1984: u16,
117}
118
119/// Days from the Unix epoch to MMS's 1984-01-01.
120const MMS_EPOCH_DAYS: u64 = 5113;
121
122impl EntryTime {
123    /// The last moment a six-octet `EntryTime` can express: 2163-04-24, end of day.
124    ///
125    /// The field has no "no upper bound", and neither has the ACSI `QueryLogByTime`, whose
126    /// range is two times and not one. A caller that wants everything from a moment onward
127    /// asks for everything up to here.
128    pub const MAX: EntryTime = EntryTime { millis_of_day: 86_399_999, days_since_1984: u16::MAX };
129
130    /// The six wire octets.
131    pub const fn to_octets(self) -> [u8; 6] {
132        let ms = self.millis_of_day.to_be_bytes();
133        let d = self.days_since_1984.to_be_bytes();
134        [ms[0], ms[1], ms[2], ms[3], d[0], d[1]]
135    }
136
137    /// Decode from the six wire octets.
138    pub const fn from_octets(o: [u8; 6]) -> EntryTime {
139        EntryTime { millis_of_day: u32::from_be_bytes([o[0], o[1], o[2], o[3]]), days_since_1984: u16::from_be_bytes([o[4], o[5]]) }
140    }
141
142    /// Build from Unix milliseconds. Saturates below 1984 and above the 16-bit day count,
143    /// because the field cannot say "before its own epoch" and silently wrapping would put
144    /// a report entry in the wrong century.
145    pub const fn from_unix_millis(millis: u64) -> EntryTime {
146        let day = millis / 86_400_000;
147        let ms = (millis % 86_400_000) as u32;
148        if day < MMS_EPOCH_DAYS {
149            return EntryTime { millis_of_day: 0, days_since_1984: 0 };
150        }
151        let days = day - MMS_EPOCH_DAYS;
152        if days > u16::MAX as u64 {
153            return EntryTime { millis_of_day: 86_399_999, days_since_1984: u16::MAX };
154        }
155        EntryTime { millis_of_day: ms, days_since_1984: days as u16 }
156    }
157
158    /// Unix milliseconds.
159    pub const fn to_unix_millis(self) -> u64 {
160        (self.days_since_1984 as u64 + MMS_EPOCH_DAYS) * 86_400_000 + self.millis_of_day as u64
161    }
162}
163
164impl fmt::Display for EntryTime {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        let millis = self.to_unix_millis();
167        let (y, m, d, hh, mm, ss) = civil_from_unix((millis / 1000).min(u64::from(u32::MAX)) as u32);
168        write!(f, "{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}.{:03}Z", millis % 1000)
169    }
170}
171
172impl fmt::Display for UtcTime {
173    /// ISO-8601-like `YYYY-MM-DDThh:mm:ss.nnnnnnnnnZ` plus a quality suffix.
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        let (y, m, d, hh, mm, ss) = civil_from_unix(self.seconds);
176        write!(f, "{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}.{:09}Z", self.nanos())?;
177        if self.quality.clock_not_synchronized {
178            f.write_str(" (unsynchronized)")?;
179        }
180        if self.quality.clock_failure {
181            f.write_str(" (clock failure)")?;
182        }
183        Ok(())
184    }
185}
186
187/// Days-from-civil inverse (Howard Hinnant's algorithm), valid for the u32 range.
188const fn civil_from_unix(secs: u32) -> (u32, u32, u32, u32, u32, u32) {
189    let days = secs / 86_400;
190    let rem = secs % 86_400;
191    let z = days as i64 + 719_468;
192    let era = z.div_euclid(146_097);
193    let doe = z.rem_euclid(146_097);
194    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
195    let y = yoe + era * 400;
196    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
197    let mp = (5 * doy + 2) / 153;
198    let d = doy - (153 * mp + 2) / 5 + 1;
199    let m = if mp < 10 { mp + 3 } else { mp - 9 };
200    let y = if m <= 2 { y + 1 } else { y };
201    (y as u32, m as u32, d as u32, rem / 3600, (rem / 60) % 60, rem % 60)
202}
203
204#[cfg(test)]
205mod tests {
206    extern crate alloc;
207    use super::*;
208    use alloc::string::ToString;
209
210    #[test]
211    fn octets_round_trip() {
212        let t = UtcTime::from_unix(1_700_000_000, 500_000_000, TimeQuality::SYNCHRONIZED);
213        assert_eq!(t.fraction, 0x0080_0000);
214        let o = t.to_octets();
215        assert_eq!(o[7], 0x80 | 31);
216        assert_eq!(UtcTime::from_octets(o), t);
217        assert_eq!(t.nanos(), 500_000_000);
218        assert_eq!(t.to_string(), "2023-11-14T22:13:20.500000000Z");
219    }
220
221    #[test]
222    fn a_nanosecond_field_that_overflows_carries_into_the_second() {
223        // Masking it into the 24-bit fraction would leave a timestamp a whole second wrong
224        // with nothing to say so, in the one field a protection engineer reads first.
225        let t = UtcTime::from_unix(10, 1_500_000_000, TimeQuality::SYNCHRONIZED);
226        assert_eq!(t.seconds, 11);
227        assert_eq!(t.nanos(), 500_000_000, "and the half second that is left is exactly representable");
228        assert_eq!(UtcTime::from_unix(0, 0, TimeQuality::SYNCHRONIZED), UtcTime::from_unix_nanos(0, TimeQuality::SYNCHRONIZED));
229    }
230
231    #[test]
232    fn nanos_precision_is_within_one_lsb() {
233        let t = UtcTime::from_unix(0, 999_999_999, TimeQuality::SYNCHRONIZED);
234        assert!(999_999_999 - t.nanos() < 60); // 2^-24 s ≈ 59.6 ns
235        assert_eq!(UtcTime::from_unix_nanos(1_000_000_001, TimeQuality::SYNCHRONIZED).seconds, 1);
236    }
237
238    #[test]
239    fn entry_time_counts_from_1984_not_from_1970() {
240        // MMS's BinaryTime epoch is 1984-01-01, which is 5113 days after Unix's. Getting
241        // that offset wrong puts every buffered report entry fourteen years out.
242        let t = EntryTime::from_unix_millis(441_763_200_000);
243        assert_eq!(t, EntryTime { millis_of_day: 0, days_since_1984: 0 }, "1984-01-01T00:00:00Z is day zero");
244        assert_eq!(t.to_string(), "1984-01-01T00:00:00.000Z");
245        let now = EntryTime::from_unix_millis(1_700_000_000_500);
246        assert_eq!(EntryTime::from_octets(now.to_octets()), now);
247        assert_eq!(now.to_unix_millis(), 1_700_000_000_500);
248        assert_eq!(now.to_string(), "2023-11-14T22:13:20.500Z");
249        // Before the epoch and past the 16-bit day count saturate rather than wrap.
250        assert_eq!(EntryTime::from_unix_millis(0), EntryTime::default());
251        assert_eq!(EntryTime::from_unix_millis(u64::MAX).days_since_1984, u16::MAX);
252    }
253
254    #[test]
255    fn epoch_display() {
256        assert_eq!(UtcTime::default().to_string(), "1970-01-01T00:00:00.000000000Z (unsynchronized)");
257    }
258}