1use core::fmt;
2
3use crate::message::ParseOptions;
4use crate::tl::{Kind, Reader, Writer};
5use crate::{Error, Result};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum SmlValue<'a> {
10 Bool(bool),
12 Bytes(&'a [u8]),
14 Int(i64),
16 Uint(u64),
18 Time(Time),
20}
21
22impl<'a> SmlValue<'a> {
23 pub(crate) fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<(Self, usize)> {
26 let tl = r.clone().read_tl()?;
27 Ok(match tl.kind {
28 Kind::Boolean => (Self::Bool(r.boolean()?), 0),
29 Kind::OctetString => (Self::Bytes(r.octet_string()?), 0),
30 Kind::Integer => (Self::Int(r.integer()?), tl.len),
31 Kind::Unsigned => (Self::Uint(r.unsigned()?), tl.len),
32 Kind::List => {
33 r.list(2)?;
34 match r.unsigned()? {
35 1 => (Self::Time(Time::read(r, options)?), 0),
36 choice => return Err(Error::UnknownChoice { what: "SML_Value", choice }),
37 }
38 }
39 })
40 }
41
42 pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
44 match *self {
45 Self::Bool(b) => w.boolean(b),
46 Self::Bytes(b) => w.octet_string(b),
47 Self::Int(v) => w.integer_min(v),
48 Self::Uint(v) => w.unsigned_min(v),
49 Self::Time(t) => {
50 w.list(2)?;
51 w.unsigned(1, 1)?;
52 t.write(w)
53 }
54 }
55 }
56}
57
58#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
60pub struct Unit(pub u8);
61
62impl Unit {
63 pub const CELSIUS: Self = Self(9);
65 pub const M3: Self = Self(13);
67 pub const M3_PER_H: Self = Self(15);
69 pub const W: Self = Self(27);
71 pub const VA: Self = Self(28);
73 pub const VAR: Self = Self(29);
75 pub const WH: Self = Self(30);
77 pub const VAH: Self = Self(31);
79 pub const VARH: Self = Self(32);
81 pub const A: Self = Self(33);
83 pub const V: Self = Self(35);
85 pub const HZ: Self = Self(44);
87 pub const PERCENT: Self = Self(56);
89 pub const COUNT: Self = Self(255);
91
92 pub const fn symbol(self) -> Option<&'static str> {
95 Some(match self.0 {
96 1 => "a",
97 2 => "mo",
98 3 => "wk",
99 4 => "d",
100 5 => "h",
101 6 => "min",
102 7 => "s",
103 8 => "°",
104 9 => "°C",
105 10 => "currency",
106 11 => "m",
107 12 => "m/s",
108 13 | 14 => "m³",
109 15 | 16 => "m³/h",
110 17 | 18 => "m³/d",
111 19 => "l",
112 20 => "kg",
113 21 => "N",
114 22 => "Nm",
115 23 => "Pa",
116 24 => "bar",
117 25 => "J",
118 26 => "J/h",
119 27 => "W",
120 28 => "VA",
121 29 => "var",
122 30 => "Wh",
123 31 => "VAh",
124 32 => "varh",
125 33 => "A",
126 34 => "C",
127 35 => "V",
128 36 => "V/m",
129 37 => "F",
130 38 => "Ω",
131 39 => "Ωm²/m",
132 40 => "Wb",
133 41 => "T",
134 42 => "A/m",
135 43 => "H",
136 44 => "Hz",
137 45 => "1/(Wh)",
138 46 => "1/(varh)",
139 47 => "1/(VAh)",
140 48 => "V²h",
141 49 => "A²h",
142 50 => "kg/s",
143 51 => "S",
144 52 => "K",
145 53 => "1/(V²h)",
146 54 => "1/(A²h)",
147 55 => "1/m³",
148 56 => "%",
149 255 => "",
150 _ => return None,
151 })
152 }
153}
154
155impl fmt::Display for Unit {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 match self.symbol() {
158 Some(s) => f.write_str(s),
159 None => write!(f, "unit({})", self.0),
160 }
161 }
162}
163
164#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
170pub struct Quantity {
171 pub mantissa: i128,
173 pub exponent: i8,
175 pub unit: Option<Unit>,
177}
178
179impl Quantity {
180 pub fn to_scale(self, exponent: i8) -> Option<i128> {
183 let diff = i32::from(self.exponent) - i32::from(exponent);
184 if diff >= 0 {
185 10i128.checked_pow(diff.unsigned_abs()).and_then(|p| self.mantissa.checked_mul(p))
186 } else {
187 let p = 10i128.checked_pow(diff.unsigned_abs())?;
188 (self.mantissa % p == 0).then(|| self.mantissa / p)
189 }
190 }
191}
192
193impl fmt::Display for Quantity {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 let mut digits = [0u8; 40];
197 let mut n = self.mantissa.unsigned_abs();
198 let mut len = 0usize;
199 loop {
200 if let Some(slot) = digits.get_mut(len) {
201 *slot = b'0' + (n % 10) as u8;
202 }
203 len += 1;
204 n /= 10;
205 if n == 0 || len >= digits.len() {
206 break;
207 }
208 }
209 let digits = digits.get(..len).unwrap_or(&[]);
210 if self.mantissa < 0 {
211 f.write_str("-")?;
212 }
213 let exp = i32::from(self.exponent);
214 if exp >= 0 {
215 for d in digits.iter().rev() {
216 write!(f, "{}", char::from(*d))?;
217 }
218 for _ in 0..exp {
219 f.write_str("0")?;
220 }
221 } else {
222 let frac = exp.unsigned_abs() as usize;
223 if len <= frac {
224 f.write_str("0.")?;
225 for _ in len..frac {
226 f.write_str("0")?;
227 }
228 for d in digits.iter().rev() {
229 write!(f, "{}", char::from(*d))?;
230 }
231 } else {
232 for (i, d) in digits.iter().rev().enumerate() {
233 if i == len - frac {
234 f.write_str(".")?;
235 }
236 write!(f, "{}", char::from(*d))?;
237 }
238 }
239 }
240 if let Some(unit) = self.unit.filter(|u| u.symbol() != Some("")) {
241 write!(f, " {unit}")?;
242 }
243 Ok(())
244 }
245}
246
247#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
249pub enum Time {
250 SecIndex(u32),
252 Timestamp(u32),
254 LocalTimestamp {
256 timestamp: u32,
258 local_offset_minutes: i16,
260 season_offset_minutes: i16,
262 },
263}
264
265impl Time {
266 pub const fn unix_seconds(self) -> Option<u32> {
269 match self {
270 Self::SecIndex(_) => None,
271 Self::Timestamp(t) | Self::LocalTimestamp { timestamp: t, .. } => Some(t),
272 }
273 }
274
275 pub(crate) fn read(r: &mut Reader<'_>, options: ParseOptions) -> Result<Self> {
276 let u32_of = |v: u64| u32::try_from(v).map_err(|_| Error::ValueOutOfRange);
277 if options.bare_time && r.clone().read_tl().is_ok_and(|tl| tl.kind == Kind::Unsigned) {
279 return Ok(Self::SecIndex(u32_of(r.unsigned()?)?));
280 }
281 r.list(2)?;
282 let choice = r.unsigned()?;
283 let i16_of = |v: i64| i16::try_from(v).map_err(|_| Error::ValueOutOfRange);
284 match choice {
285 1 => Ok(Self::SecIndex(u32_of(r.unsigned()?)?)),
286 2 => Ok(Self::Timestamp(u32_of(r.unsigned()?)?)),
287 3 => {
288 r.list(3)?;
289 Ok(Self::LocalTimestamp {
290 timestamp: u32_of(r.unsigned()?)?,
291 local_offset_minutes: i16_of(r.integer()?)?,
292 season_offset_minutes: i16_of(r.integer()?)?,
293 })
294 }
295 choice => Err(Error::UnknownChoice { what: "SML_Time", choice }),
296 }
297 }
298
299 pub(crate) fn read_opt(r: &mut Reader<'_>, options: ParseOptions) -> Result<Option<Self>> {
300 if r.absent() { Ok(None) } else { Self::read(r, options).map(Some) }
301 }
302
303 pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
305 w.list(2)?;
306 match *self {
307 Self::SecIndex(s) => {
308 w.unsigned(1, 1)?;
309 w.unsigned(u64::from(s), 4)
310 }
311 Self::Timestamp(t) => {
312 w.unsigned(2, 1)?;
313 w.unsigned(u64::from(t), 4)
314 }
315 Self::LocalTimestamp { timestamp, local_offset_minutes, season_offset_minutes } => {
316 w.unsigned(3, 1)?;
317 w.list(3)?;
318 w.unsigned(u64::from(timestamp), 4)?;
319 w.integer(i64::from(local_offset_minutes), 2)?;
320 w.integer(i64::from(season_offset_minutes), 2)
321 }
322 }
323 }
324
325 pub(crate) fn write_opt(t: Option<Self>, w: &mut Writer<'_>) -> Result<()> {
326 match t {
327 Some(t) => t.write(w),
328 None => w.absent(),
329 }
330 }
331}
332
333fn civil_from_days(days: i64) -> (i64, i64, i64) {
336 let z = days + 719_468;
337 let era = z.div_euclid(146_097);
338 let doe = z.rem_euclid(146_097);
339 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
340 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
341 let mp = (5 * doy + 2) / 153;
342 let day = doy - (153 * mp + 2) / 5 + 1;
343 let month = if mp < 10 { mp + 3 } else { mp - 9 };
344 (yoe + era * 400 + i64::from(month <= 2), month, day)
345}
346
347fn write_date_time(f: &mut fmt::Formatter<'_>, seconds: i64) -> fmt::Result {
349 let (days, secs) = (seconds.div_euclid(86_400), seconds.rem_euclid(86_400));
350 let (y, mo, d) = civil_from_days(days);
351 write!(f, "{y:04}-{mo:02}-{d:02}T{:02}:{:02}:{:02}", secs / 3600, secs % 3600 / 60, secs % 60)
352}
353
354impl fmt::Display for Time {
365 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366 match *self {
367 Self::SecIndex(s) => write!(f, "secIndex {s} s"),
368 Self::Timestamp(t) => {
369 write_date_time(f, i64::from(t))?;
370 f.write_str("Z")
371 }
372 Self::LocalTimestamp { timestamp, local_offset_minutes, season_offset_minutes } => {
373 let offset = i64::from(local_offset_minutes) + i64::from(season_offset_minutes);
374 write_date_time(f, i64::from(timestamp) + 60 * offset)?;
375 let sign = if offset < 0 { '-' } else { '+' };
376 let offset = offset.unsigned_abs();
377 write!(f, "{sign}{:02}:{:02}", offset / 60, offset % 60)
378 }
379 }
380 }
381}
382
383#[cfg(test)]
384mod tests {
385 extern crate std;
386 use super::*;
387 use std::string::ToString;
388
389 fn q(mantissa: i128, exponent: i8) -> std::string::String {
390 Quantity { mantissa, exponent, unit: None }.to_string()
391 }
392
393 #[test]
394 fn displays_exact_decimals() {
395 assert_eq!(q(123_456, -1), "12345.6");
396 assert_eq!(q(5, -3), "0.005");
397 assert_eq!(q(-42, 0), "-42");
398 assert_eq!(q(7, 2), "700");
399 assert_eq!(q(0, -2), "0.00");
400 assert_eq!(Quantity { mantissa: 15, exponent: -1, unit: Some(Unit::WH) }.to_string(), "1.5 Wh");
401 }
402
403 #[test]
404 fn every_dlms_unit_code_has_a_symbol() {
405 for code in 1..=56u8 {
406 assert!(Unit(code).symbol().is_some_and(|s| !s.is_empty()), "unit {code}");
407 }
408 assert_eq!(Unit(57).to_string(), "unit(57)");
409 assert_eq!(Unit::WH.to_string(), "Wh");
410 assert_eq!(Quantity { mantissa: 3, exponent: 0, unit: Some(Unit::COUNT) }.to_string(), "3");
411 }
412
413 #[test]
414 fn time_displays_as_iso_8601() {
415 assert_eq!(Time::Timestamp(0).to_string(), "1970-01-01T00:00:00Z");
416 assert_eq!(Time::Timestamp(951_782_400).to_string(), "2000-02-29T00:00:00Z");
417 assert_eq!(Time::Timestamp(u32::MAX).to_string(), "2106-02-07T06:28:15Z");
418 assert_eq!(Time::SecIndex(42).to_string(), "secIndex 42 s");
419 for (t, date) in [
422 (4_107_456_000, "2100-02-28"),
423 (4_107_542_400, "2100-03-01"),
424 (951_868_800, "2000-03-01"),
425 (946_598_400, "1999-12-31"),
426 (3_981_312_000, "2096-02-29"),
427 (983_404_800, "2001-03-01"),
428 (4_260_124_800, "2104-12-31"),
429 ] {
430 assert_eq!(Time::Timestamp(t).to_string(), std::format!("{date}T00:00:00Z"));
431 }
432 let utc = Time::LocalTimestamp { timestamp: 0, local_offset_minutes: 0, season_offset_minutes: 0 };
433 assert_eq!(utc.to_string(), "1970-01-01T00:00:00+00:00");
434 let summer = Time::LocalTimestamp {
435 timestamp: 1_719_835_200,
436 local_offset_minutes: 60,
437 season_offset_minutes: 60,
438 };
439 assert_eq!(summer.to_string(), "2024-07-01T14:00:00+02:00");
440 let west =
441 Time::LocalTimestamp { timestamp: 0, local_offset_minutes: -330, season_offset_minutes: 0 };
442 assert_eq!(west.to_string(), "1969-12-31T18:30:00-05:30");
443 }
444
445 #[test]
446 fn times_round_trip() {
447 let opts = ParseOptions::default();
448 for t in [
449 Time::SecIndex(7),
450 Time::Timestamp(1_700_000_000),
451 Time::LocalTimestamp { timestamp: 1, local_offset_minutes: 60, season_offset_minutes: -60 },
452 ] {
453 let mut buf = [0u8; 32];
454 let mut w = Writer::new(&mut buf);
455 t.write(&mut w).unwrap();
456 let n = w.position();
457 assert_eq!(Time::read(&mut Reader::new(&buf[..n]), opts).unwrap(), t);
458 }
459 assert_eq!(Time::SecIndex(1).unix_seconds(), None);
460 assert_eq!(Time::Timestamp(5).unix_seconds(), Some(5));
461 }
462
463 #[test]
464 fn rescales_without_rounding() {
465 let e = Quantity { mantissa: 123_456, exponent: -1, unit: None };
466 assert_eq!(e.to_scale(-3), Some(12_345_600));
467 assert_eq!(e.to_scale(-1), Some(123_456));
468 assert_eq!(e.to_scale(0), None, "12345.6 is not a whole number");
469 let whole = Quantity { mantissa: 1230, exponent: -1, unit: None };
470 assert_eq!(whole.to_scale(0), Some(123));
471 assert_eq!(Quantity { mantissa: -1230, ..whole }.to_scale(0), Some(-123));
472 assert_eq!(Quantity { mantissa: -12_000, ..whole }.to_scale(2), Some(-12), "-1200.0 is -12 hundreds");
473 assert_eq!(Quantity { mantissa: 1235, ..whole }.to_scale(0), None);
474 assert_eq!(Quantity { mantissa: 1, exponent: 0, unit: None }.to_scale(-40), None, "overflow");
475 }
476}