1#[cfg(any(feature = "acquisition", test))]
3use dlms_cosem_kit::axdr::Data;
4
5use core::fmt;
6use dlms_cosem_kit::{axdr::DateTime, codec, cosem::RangeDescriptor, xdlms::SelectiveAccess};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum ClockError {
11 Encoding,
12 Calendar,
13 Deviation,
14 Status,
15 Fraction,
16 ReversedRange,
17}
18
19impl fmt::Display for ClockError {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 f.write_str(match self {
22 Self::Encoding => "expected a COSEM date-time or twelve clock octets",
23 Self::Calendar => "expected a concrete COSEM date and time with a consistent weekday",
24 Self::Deviation => "clock requires a known UTC deviation within 720 minutes",
25 Self::Status => {
26 "clock status must be valid with only the daylight-saving flag permitted"
27 }
28 Self::Fraction => "whole-second records require zero or unspecified hundredths",
29 Self::ReversedRange => "the clock range ends before it starts",
30 })
31 }
32}
33
34impl core::error::Error for ClockError {}
35
36fn checked_seconds(clock: DateTime) -> Result<i64, ClockError> {
37 if !(-720..=720).contains(&clock.deviation) {
38 return Err(ClockError::Deviation);
39 }
40 if !matches!(clock.status.0, 0 | 0x80) {
41 return Err(ClockError::Status);
42 }
43 if !matches!(clock.hundredths, 0 | 0xff) {
44 return Err(ClockError::Fraction);
45 }
46 let utc = clock.to_unix_seconds().ok_or(ClockError::Calendar)?;
47 let local = utc - i64::from(clock.deviation) * 60;
49 let weekday = (local.div_euclid(86_400) + 3).rem_euclid(7) + 1;
50 if clock.day_of_week != 0xff && i64::from(clock.day_of_week) != weekday {
51 return Err(ClockError::Calendar);
52 }
53 Ok(utc)
54}
55
56#[cfg(any(feature = "acquisition", test))]
57pub(super) fn utc_seconds(data: &Data<'_>) -> Result<i64, ClockError> {
58 let clock = match data {
59 Data::DateTime(clock) => *clock,
60 Data::OctetString(bytes) => {
61 DateTime::from_bytes((*bytes).try_into().map_err(|_| ClockError::Encoding)?)
62 }
63 _ => return Err(ClockError::Encoding),
64 };
65 checked_seconds(clock)
66}
67
68pub(crate) fn utc_clock(utc: i64) -> Result<DateTime, ClockError> {
70 DateTime::from_unix_seconds(utc).ok_or(ClockError::Calendar)
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct ClockRange {
76 from: DateTime,
77 to: DateTime,
78 start: i64,
79 end: i64,
80}
81
82impl ClockRange {
83 pub fn new(from: DateTime, to: DateTime) -> Result<Self, ClockError> {
85 let start = checked_seconds(from)?;
86 let end = checked_seconds(to)?;
87 if start > end {
88 return Err(ClockError::ReversedRange);
89 }
90 Ok(Self {
91 from,
92 to,
93 start,
94 end,
95 })
96 }
97
98 pub fn from_unix(first: i64, last: i64) -> Result<Self, ClockError> {
100 Self::new(utc_clock(first)?, utc_clock(last)?)
101 }
102
103 pub fn start(self) -> i64 {
105 self.start
106 }
107
108 pub fn end(self) -> i64 {
110 self.end
111 }
112
113 pub fn contains(self, utc: i64) -> bool {
115 (self.start..=self.end).contains(&utc)
116 }
117
118 pub fn selection(self, buf: &mut [u8]) -> codec::Result<SelectiveAccess<'_>> {
120 RangeDescriptor::by_clock(self.from, self.to).to_selective_access(buf)
121 }
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127 use dlms_cosem_kit::axdr::ClockStatus;
128
129 #[test]
130 fn normalizes_known_offset_without_applying_dst_twice() {
131 let mut clock = DateTime::from_civil(1970, 1, 1, 0, 59, 59, 60).unwrap();
132 clock.status = ClockStatus(0x80);
133 assert_eq!(utc_seconds(&Data::DateTime(clock)), Ok(-1));
134 assert_eq!(utc_seconds(&Data::OctetString(&clock.to_bytes())), Ok(-1));
135 clock.day_of_week = 0xff;
136 clock.hundredths = 0;
137 assert_eq!(checked_seconds(clock), Ok(-1));
138 }
139
140 #[test]
141 fn refuses_ambiguous_or_lossy_clocks() {
142 let clock = DateTime::from_civil(2024, 2, 29, 12, 0, 0, 0).unwrap();
143 for bad in [
144 DateTime {
145 year: 2023,
146 ..clock
147 },
148 DateTime {
149 month: 0xff,
150 ..clock
151 },
152 DateTime {
153 day_of_week: 3,
154 ..clock
155 },
156 DateTime {
157 day_of_week: 8,
158 ..clock
159 },
160 DateTime {
161 second: 60,
162 ..clock
163 },
164 DateTime {
165 hundredths: 1,
166 ..clock
167 },
168 DateTime {
169 deviation: i16::MIN,
170 ..clock
171 },
172 DateTime {
173 deviation: 721,
174 ..clock
175 },
176 DateTime {
177 deviation: -721,
178 ..clock
179 },
180 ] {
181 assert!(checked_seconds(bad).is_err(), "{bad:?}");
182 }
183 for status in [1, 2, 4, 8, 0x10, 0xff] {
184 assert_eq!(
185 checked_seconds(DateTime {
186 status: ClockStatus(status),
187 ..clock
188 }),
189 Err(ClockError::Status)
190 );
191 }
192 assert_eq!(
193 utc_seconds(&Data::OctetString(&[0; 11])),
194 Err(ClockError::Encoding)
195 );
196 assert_eq!(utc_seconds(&Data::Long64(0)), Err(ClockError::Encoding));
197 }
198
199 #[test]
200 fn range_selects_both_endpoints_and_checks_the_wire_calendar() {
201 for (year, month, day) in [
202 (0, 1, 1),
203 (1900, 3, 1),
204 (1969, 12, 31),
205 (2000, 2, 29),
206 (2024, 2, 29),
207 (65534, 12, 31),
208 ] {
209 let first = DateTime::from_civil(year, month, day, 0, 0, 0, 0).unwrap();
210 let last = DateTime::from_civil(year, month, day, 23, 59, 59, 0).unwrap();
211 let start = checked_seconds(first).unwrap();
212 let end = checked_seconds(last).unwrap();
213 let range = ClockRange::from_unix(start, end).unwrap();
214 assert_eq!((range.start(), range.end()), (start, end));
215 assert!(range.contains(start) && range.contains(end));
216 assert!(!range.contains(start - 1) && !range.contains(end + 1));
217 let mut bytes = [0; 64];
218 let selected = range.selection(&mut bytes).unwrap();
219 assert_eq!(selected.selector, 1);
220 let fields = selected.parameters.as_structure().unwrap();
221 let mut expected_start = first;
222 expected_start.hundredths = 0;
223 assert_eq!(
224 fields.get(1).unwrap(),
225 Data::OctetString(&expected_start.to_bytes())
226 );
227 assert_eq!(utc_seconds(&fields.get(2).unwrap()), Ok(end));
228 }
229 assert!(ClockRange::from_unix(0, 0).unwrap().contains(0));
230 assert_eq!(ClockRange::from_unix(1, 0), Err(ClockError::ReversedRange));
231 for outside in [i64::MIN, i64::MAX] {
232 assert!(ClockRange::from_unix(outside, outside).is_err());
233 }
234 }
235}