Skip to main content

mme/
display.rs

1//! Historical import consumption on a free-running, whole-day meter clock.
2use core::ops::RangeInclusive;
3
4/// The four display periods in the May 2018 FNN Basiszähler profile.
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum DisplayPeriod {
7    Day,
8    Week,
9    Month,
10    Year,
11}
12
13impl DisplayPeriod {
14    /// Number of powered 24-hour intervals in one value.
15    pub const fn days(self) -> u16 {
16        match self {
17            Self::Day => 1,
18            Self::Week => 7,
19            Self::Month => 30,
20            Self::Year => 365,
21        }
22    }
23
24    /// Number of historical values exposed by this display.
25    pub const fn depth(self) -> u16 {
26        match self {
27            Self::Day => 730,
28            Self::Week => 104,
29            Self::Month => 24,
30            Self::Year => 2,
31        }
32    }
33
34    /// Endpoints of the cumulative registers to subtract. Age 1 is the most
35    /// recent complete period. The display refreshes once per powered day
36    /// after commissioning. Returns None for an unavailable period or invalid age.
37    pub fn window(self, opening: i64, current: i64, age: u16) -> Option<RangeInclusive<i64>> {
38        if !(1..=self.depth()).contains(&age) || current < opening {
39            return None;
40        }
41        let elapsed = i128::from(current) - i128::from(opening);
42        let day = elapsed / 86_400;
43        let first = day - i128::from(age) * i128::from(self.days());
44        if first < 0 {
45            return None;
46        }
47        let start = i128::from(opening) + first * 86_400;
48        let end = start + i128::from(self.days()) * 86_400;
49        // Both endpoints lie within opening..=current.
50        Some(start as i64..=end as i64)
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::DisplayPeriod::*;
57    #[test]
58    fn windows_refresh_daily_from_commissioning() {
59        let origin = -517;
60        let d = 86_400;
61        assert_eq!(Week.window(origin, origin + 7 * d - 1, 1), None);
62        assert_eq!(
63            Week.window(origin, origin + 8 * d + 60, 1),
64            Some(origin + d..=origin + 8 * d)
65        );
66        for period in [Day, Week, Month, Year] {
67            assert!(period.window(0, 730 * d, period.depth()).is_some());
68            assert_eq!(period.window(0, 731 * d, period.depth() + 1), None);
69            assert_eq!(period.window(0, 731 * d, 0), None);
70        }
71        assert_eq!(Year.window(0, 730 * d - 1, 2), None);
72        assert_eq!(Year.window(0, 731 * d, 2), Some(d..=366 * d));
73        assert_eq!(Day.window(i64::MAX, i64::MIN, 1), None);
74        assert!(Year.window(i64::MIN, i64::MAX, 2).is_some());
75    }
76}