Skip to main content

mbus_kit/
time.rs

1//! Dates and times (EN 13757-3:2018, Annex A): data types G, J, F and I.
2//!
3//! | Type | Bytes | Content |
4//! |---|---|---|
5//! | G | 2 | date |
6//! | J | 3 | time of day with seconds |
7//! | F | 4 | date, hour, minute; invalid and summer-time flags |
8//! | I | 6 | type F plus seconds, day of week and week number |
9//!
10//! The meter's local time; no time zone is transmitted. A date the meter flags invalid,
11//! or one that cannot exist (month 13), is still returned: [`Date::is_valid`] and
12//! [`DateTime::invalid`] say so. Iteration never stops on a bad date.
13
14use core::fmt;
15
16/// A date, data type G.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct Date {
19    /// Year (EN 13757-3 Table A.5: a two-digit year up to 80 is 20xx, above is 19xx).
20    pub year: u16,
21    /// Month, 1–12 when valid.
22    pub month: u8,
23    /// Day, 1–31 when valid.
24    pub day: u8,
25}
26
27impl Date {
28    /// Decode type G: day in bits 0–4, month in bits 8–11, year in bits 5–7 and 12–15.
29    pub(crate) fn from_type_g(b0: u8, b1: u8) -> Self {
30        let year = ((b0 & 0xE0) >> 5) | ((b1 & 0xF0) >> 1);
31        Self { year: century(year, 0), month: b1 & 0x0F, day: b0 & 0x1F }
32    }
33
34    /// The date `months` later (or earlier, when negative), for monthly profiles and
35    /// billing dates. The last day of a month stays the last day: 2008-01-31 + 1 month is
36    /// 2008-02-29, + 2 months 2008-03-31 (OMS Vol. 2 Table G.5). Other days are clamped to
37    /// the month's length. `None` for an invalid date or a year outside 0–65535.
38    pub fn add_months(self, months: i32) -> Option<Self> {
39        if !self.is_valid() {
40            return None;
41        }
42        let last = self.day >= days_in(self.year, self.month);
43        let total = (i64::from(self.year) * 12 + i64::from(self.month) - 1).checked_add(i64::from(months))?;
44        let year = u16::try_from(total.div_euclid(12)).ok()?;
45        let month = u8::try_from(total.rem_euclid(12) + 1).ok()?;
46        let len = days_in(year, month);
47        let day = if last { len } else { self.day.min(len) };
48        Some(Self { year, month, day })
49    }
50
51    /// Whether the date can exist: month 1–12, day 1 to the month's length.
52    pub const fn is_valid(&self) -> bool {
53        let leap = (self.year % 4 == 0 && self.year % 100 != 0) || self.year % 400 == 0;
54        let days = match self.month {
55            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
56            4 | 6 | 9 | 11 => 30,
57            2 if leap => 29,
58            2 => 28,
59            _ => return false,
60        };
61        self.day >= 1 && self.day <= days
62    }
63}
64
65const fn days_in(year: u16, month: u8) -> u8 {
66    let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
67    match month {
68        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
69        4 | 6 | 9 | 11 => 30,
70        2 if leap => 29,
71        2 => 28,
72        _ => 0,
73    }
74}
75
76/// The full year for a 7-bit year field and the two "hundred year" bits of type F/I.
77///
78/// EN 13757-3:2018 Table A.5 (as reproduced by exmbus; libmbus agrees): with hundred-year
79/// bits 0 and a year up to 80, the year is 2000 + year (the compatibility rule for meters
80/// with a two-digit year); otherwise 1900 + 100 × hundred-year + year. OMS Annex N encodes
81/// 2008 with hundred-year 1.
82const fn century(year: u8, hundred: u8) -> u16 {
83    let y = year as u16;
84    if hundred == 0 && y <= 80 { 2000 + y } else { 1900 + 100 * hundred as u16 + y }
85}
86
87impl fmt::Display for Date {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)?;
90        if !self.is_valid() {
91            f.write_str(" (invalid)")?;
92        }
93        Ok(())
94    }
95}
96
97/// A time of day, data type J (and the time part of F and I).
98#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
99pub struct Time {
100    /// Hour, 0–23.
101    pub hour: u8,
102    /// Minute, 0–59.
103    pub minute: u8,
104    /// Second, 0–59 (0 for type F, which has no seconds).
105    pub second: u8,
106}
107
108impl Time {
109    /// Decode type J: seconds, minutes and hours in the low bits of three bytes.
110    pub(crate) const fn from_type_j(b0: u8, b1: u8, b2: u8) -> Self {
111        Self { second: b0 & 0x3F, minute: b1 & 0x3F, hour: b2 & 0x1F }
112    }
113
114    /// Whether every field is in range.
115    pub const fn is_valid(&self) -> bool {
116        self.hour < 24 && self.minute < 60 && self.second < 60
117    }
118}
119
120impl fmt::Display for Time {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
123    }
124}
125
126/// A date and time, data type F (minutes) or I (seconds). The meter's local time.
127#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
128#[allow(clippy::struct_excessive_bools)] // the flags are the wire format's
129pub struct DateTime {
130    /// The date.
131    pub date: Date,
132    /// The time of day.
133    pub time: Time,
134    /// Type I: the time has seconds. Type F: `time.second` is 0 and not meaningful.
135    pub has_seconds: bool,
136    /// The meter flags the time as invalid (IV bit).
137    pub invalid: bool,
138    /// The meter flags summer (daylight saving) time: SU bit (type F), DST bit (type I).
139    pub summer_time: bool,
140    /// Type I: the meter flags the year as a leap year.
141    pub leap_year: bool,
142    /// Type I: day of week, 1 = Monday … 7 = Sunday, 0 = not given.
143    pub weekday: u8,
144    /// Type I: week of the year, 1–53, 0 = not given.
145    pub week: u8,
146}
147
148impl DateTime {
149    /// Decode type F (4 bytes).
150    pub(crate) fn from_type_f(b: [u8; 4]) -> Self {
151        let [b0, b1, b2, b3] = b;
152        let mut date = Date::from_type_g(b2, b3);
153        date.year = century(((b2 & 0xE0) >> 5) | ((b3 & 0xF0) >> 1), (b1 >> 5) & 0x03);
154        Self {
155            date,
156            time: Time { hour: b1 & 0x1F, minute: b0 & 0x3F, second: 0 },
157            has_seconds: false,
158            invalid: b0 & 0x80 != 0,
159            summer_time: b1 & 0x80 != 0,
160            leap_year: false,
161            weekday: 0,
162            week: 0,
163        }
164    }
165
166    /// Decode type I (6 bytes, EN 13757-3:2018 Table A.8 as read by exmbus and libmbus):
167    /// byte 0 leap year (7), DST (6), second; byte 1 IV (7), DST sign (6), minute;
168    /// byte 2 day of week (7–5), hour; bytes 3–4 as type G; byte 5 DST deviation (7–6),
169    /// week number.
170    pub(crate) fn from_type_i(b: [u8; 6]) -> Self {
171        let [b0, b1, b2, b3, b4, b5] = b;
172        let date = Date::from_type_g(b3, b4);
173        Self {
174            date,
175            time: Time { hour: b2 & 0x1F, minute: b1 & 0x3F, second: b0 & 0x3F },
176            has_seconds: true,
177            invalid: b1 & 0x80 != 0,
178            summer_time: b0 & 0x40 != 0,
179            leap_year: b0 & 0x80 != 0,
180            weekday: b2 >> 5,
181            week: b5 & 0x3F,
182        }
183    }
184
185    /// A valid local date and time (to set a meter's clock with
186    /// [`master::set_time`](crate::master::set_time)). `None` if it cannot exist or lies
187    /// outside 1981–2299, the years type F can carry.
188    pub fn new(year: u16, month: u8, day: u8, hour: u8, minute: u8) -> Option<Self> {
189        let t = Self {
190            date: Date { year, month, day },
191            time: Time { hour, minute, second: 0 },
192            has_seconds: false,
193            invalid: false,
194            summer_time: false,
195            leap_year: false,
196            weekday: 0,
197            week: 0,
198        };
199        (t.is_valid() && (1981..=2299).contains(&year)).then_some(t)
200    }
201
202    /// Encode as type F (4 bytes), e.g. to set a meter's clock. Years 2000–2080 use
203    /// hundred-year bits 0 (what meters expect), others the hundred-year bits.
204    pub fn to_type_f(&self) -> [u8; 4] {
205        let (y, h) = match self.date.year {
206            2000..=2080 => (self.date.year - 2000, 0),
207            year => ((year.saturating_sub(1900)) % 100, (year.saturating_sub(1900) / 100).min(3)),
208        };
209        #[allow(clippy::cast_possible_truncation)] // y < 100, h ≤ 3
210        let (y, h) = (y as u8, h as u8);
211        let Time { hour, minute, .. } = self.time;
212        [
213            (minute & 0x3F) | if self.invalid { 0x80 } else { 0 },
214            (hour & 0x1F) | (h << 5) | if self.summer_time { 0x80 } else { 0 },
215            (self.date.day & 0x1F) | ((y & 0x07) << 5),
216            (self.date.month & 0x0F) | ((y & 0x78) << 1),
217        ]
218    }
219
220    /// Whether the meter marks the time valid and every field can exist.
221    pub const fn is_valid(&self) -> bool {
222        !self.invalid && self.date.is_valid() && self.time.is_valid()
223    }
224}
225
226impl fmt::Display for DateTime {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        let Date { year, month, day } = self.date;
229        let Time { hour, minute, second } = self.time;
230        write!(f, "{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}")?;
231        if self.has_seconds {
232            write!(f, ":{second:02}")?;
233        }
234        if self.summer_time {
235            f.write_str(" (summer time)")?;
236        }
237        if !self.is_valid() {
238            f.write_str(" (invalid)")?;
239        }
240        Ok(())
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    extern crate std;
247    use super::*;
248    use std::string::ToString;
249
250    #[test]
251    fn type_g() {
252        // 2026-11-27: year 26 = 0b001_1010 → b0 bits 7–5 = 010, b1 bits 7–4 = 0011.
253        let d = Date::from_type_g(0b0101_1011, 0b0011_1011);
254        assert_eq!(d.to_string(), "2026-11-27");
255        assert!(d.is_valid());
256        let bad = Date::from_type_g(0xFF, 0xFF);
257        assert!(!bad.is_valid());
258        assert!(bad.to_string().ends_with("(invalid)"));
259    }
260
261    #[test]
262    fn type_f_flags_and_century() {
263        let t = DateTime::from_type_f([30, 14, 0b0101_1011, 0b0011_1011]);
264        assert_eq!(t.to_string(), "2026-11-27 14:30");
265        let t = DateTime::from_type_f([0x1E | 0x80, 0x0E | 0x80, 0b0101_1011, 0b0011_1011]);
266        assert!(t.invalid && t.summer_time);
267        assert_eq!(t.to_string(), "2026-11-27 14:30 (summer time) (invalid)");
268        // Year 99 without hundred-year bits is 1999; OMS Annex N N.2.1 encodes 2008 as 8
269        // with hundred-year 1 (`04 6D 32 37 1F 15` = 2008-05-31 23:50).
270        assert_eq!(century(99, 0), 1999);
271        assert_eq!(century(80, 0), 2080);
272        let t = DateTime::from_type_f([0x32, 0x37, 0x1F, 0x15]);
273        assert_eq!(t.to_string(), "2008-05-31 23:50");
274    }
275
276    #[test]
277    fn month_steps_keep_the_month_end() {
278        let d = Date { year: 2008, month: 1, day: 31 };
279        let steps: std::vec::Vec<std::string::String> =
280            (1..=4).map(|k| d.add_months(k).unwrap().to_string()).collect();
281        assert_eq!(steps, ["2008-02-29", "2008-03-31", "2008-04-30", "2008-05-31"]);
282        assert_eq!(Date { year: 2008, month: 5, day: 31 }.add_months(-4).unwrap().to_string(), "2008-01-31");
283        assert_eq!(Date { year: 2020, month: 11, day: 15 }.add_months(3).unwrap().to_string(), "2021-02-15");
284        // A meter's invalid date, or a step past the representable years: no date.
285        assert_eq!(Date { year: 2020, month: 13, day: 1 }.add_months(1), None);
286        assert_eq!(d.add_months(i32::MAX), None);
287        assert_eq!(d.add_months(i32::MIN), None);
288        // Type F ends at 2299 (hundred-year bits 3): 2350 would encode as 2250.
289        assert!(DateTime::new(2299, 12, 31, 23, 59).is_some());
290        assert!(DateTime::new(2300, 1, 1, 0, 0).is_none());
291        let t = DateTime::new(2250, 6, 1, 12, 0).unwrap();
292        assert_eq!(DateTime::from_type_f(t.to_type_f()).date.year, 2250);
293    }
294
295    #[test]
296    fn type_f_round_trips() {
297        for bytes in [
298            [0x32, 0x37, 0x1F, 0x15],
299            [30, 14, 0b0101_1011, 0b0011_1011],
300            [0x1E | 0x80, 0x0E | 0x80, 0x5B, 0x3B],
301        ] {
302            let t = DateTime::from_type_f(bytes);
303            assert_eq!(DateTime::from_type_f(t.to_type_f()), t, "{bytes:02x?}");
304        }
305    }
306
307    #[test]
308    fn type_i_real_vector() {
309        // wmbusmeters ebeco500: `06 6D B2 36 0D 01 02 00` = 2000-02-01 13:54:50, leap year.
310        let t = DateTime::from_type_i([0xB2, 0x36, 0x0D, 0x01, 0x02, 0x00]);
311        assert_eq!(t.to_string(), "2000-02-01 13:54:50");
312        assert!(t.leap_year && !t.summer_time && !t.invalid);
313    }
314
315    #[test]
316    fn type_j_and_i() {
317        assert_eq!(Time::from_type_j(5, 4, 3).to_string(), "03:04:05");
318        let t = DateTime::from_type_i([59, 30, 0x0E | (5 << 5), 0b0101_1011, 0b0011_1011, 48]);
319        assert_eq!(t.to_string(), "2026-11-27 14:30:59");
320        assert_eq!((t.weekday, t.week), (5, 48));
321    }
322}