sml-kit 0.1.0

SML (Smart Message Language) for Rust: German smart meter readout with a sans-I/O, no_std, allocation-free core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use core::fmt;

use crate::message::ParseOptions;
use crate::tl::{Kind, Reader, Writer};
use crate::{Error, Result};

/// The value of a list entry: `SML_Value`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SmlValue<'a> {
    /// A boolean.
    Bool(bool),
    /// A byte string: identifiers, text, signatures.
    Bytes(&'a [u8]),
    /// A signed integer.
    Int(i64),
    /// An unsigned integer.
    Uint(u64),
    /// A point in time (`SML_ListType`, choice `smlTime`).
    Time(Time),
}

impl<'a> SmlValue<'a> {
    /// Read a value. Returns it with the number of data bytes of an integer on the wire
    /// (0 for every other type), which the DZG correction needs.
    pub(crate) fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<(Self, usize)> {
        let tl = r.clone().read_tl()?;
        Ok(match tl.kind {
            Kind::Boolean => (Self::Bool(r.boolean()?), 0),
            Kind::OctetString => (Self::Bytes(r.octet_string()?), 0),
            Kind::Integer => (Self::Int(r.integer()?), tl.len),
            Kind::Unsigned => (Self::Uint(r.unsigned()?), tl.len),
            Kind::List => {
                r.list(2)?;
                match r.unsigned()? {
                    1 => (Self::Time(Time::read(r, options)?), 0),
                    choice => return Err(Error::UnknownChoice { what: "SML_Value", choice }),
                }
            }
        })
    }

    /// Write the value: integers in the smallest of 1, 2, 4 or 8 bytes.
    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        match *self {
            Self::Bool(b) => w.boolean(b),
            Self::Bytes(b) => w.octet_string(b),
            Self::Int(v) => w.integer_min(v),
            Self::Uint(v) => w.unsigned_min(v),
            Self::Time(t) => {
                w.list(2)?;
                w.unsigned(1, 1)?;
                t.write(w)
            }
        }
    }
}

/// A unit code from the DLMS/COSEM unit table (IEC 62056-62), as SML carries it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Unit(pub u8);

impl Unit {
    /// Temperature, degree Celsius.
    pub const CELSIUS: Self = Self(9);
    /// Volume, cubic metre.
    pub const M3: Self = Self(13);
    /// Volume flow, cubic metre per hour.
    pub const M3_PER_H: Self = Self(15);
    /// Active power, watt.
    pub const W: Self = Self(27);
    /// Apparent power, volt-ampere.
    pub const VA: Self = Self(28);
    /// Reactive power, var.
    pub const VAR: Self = Self(29);
    /// Active energy, watt-hour.
    pub const WH: Self = Self(30);
    /// Apparent energy, volt-ampere-hour.
    pub const VAH: Self = Self(31);
    /// Reactive energy, var-hour.
    pub const VARH: Self = Self(32);
    /// Current, ampere.
    pub const A: Self = Self(33);
    /// Voltage, volt.
    pub const V: Self = Self(35);
    /// Frequency, hertz.
    pub const HZ: Self = Self(44);
    /// Percentage.
    pub const PERCENT: Self = Self(56);
    /// A count: no unit.
    pub const COUNT: Self = Self(255);

    /// The unit's symbol from the DLMS unit table, if the code is in it. A count (255)
    /// has the empty symbol.
    pub const fn symbol(self) -> Option<&'static str> {
        Some(match self.0 {
            1 => "a",
            2 => "mo",
            3 => "wk",
            4 => "d",
            5 => "h",
            6 => "min",
            7 => "s",
            8 => "°",
            9 => "°C",
            10 => "currency",
            11 => "m",
            12 => "m/s",
            13 | 14 => "m³",
            15 | 16 => "m³/h",
            17 | 18 => "m³/d",
            19 => "l",
            20 => "kg",
            21 => "N",
            22 => "Nm",
            23 => "Pa",
            24 => "bar",
            25 => "J",
            26 => "J/h",
            27 => "W",
            28 => "VA",
            29 => "var",
            30 => "Wh",
            31 => "VAh",
            32 => "varh",
            33 => "A",
            34 => "C",
            35 => "V",
            36 => "V/m",
            37 => "F",
            38 => "Ω",
            39 => "Ωm²/m",
            40 => "Wb",
            41 => "T",
            42 => "A/m",
            43 => "H",
            44 => "Hz",
            45 => "1/(Wh)",
            46 => "1/(varh)",
            47 => "1/(VAh)",
            48 => "V²h",
            49 => "A²h",
            50 => "kg/s",
            51 => "S",
            52 => "K",
            53 => "1/(V²h)",
            54 => "1/(A²h)",
            55 => "1/m³",
            56 => "%",
            255 => "",
            _ => return None,
        })
    }
}

impl fmt::Display for Unit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.symbol() {
            Some(s) => f.write_str(s),
            None => write!(f, "unit({})", self.0),
        }
    }
}

/// An exact measured quantity: `mantissa × 10^exponent` in `unit`.
///
/// Never a float: a meter reading is evidence for an invoice, and
/// `0.1 + 0.2` must not be a billing question. [`Display`](fmt::Display) prints the exact
/// decimal, e.g. `12345.6 Wh`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Quantity {
    /// The raw value from the meter.
    pub mantissa: i128,
    /// The scaler from the meter (`SML_ListEntry.scaler`), 0 when absent.
    pub exponent: i8,
    /// The unit, when the meter sent one.
    pub unit: Option<Unit>,
}

impl Quantity {
    /// The value in units of `10^exponent`, i.e. scaled to `exponent` decimal places.
    /// Returns `None` if the result does not fit an `i128`.
    pub fn to_scale(self, exponent: i8) -> Option<i128> {
        let diff = i32::from(self.exponent) - i32::from(exponent);
        if diff >= 0 {
            10i128.checked_pow(diff.unsigned_abs()).and_then(|p| self.mantissa.checked_mul(p))
        } else {
            let p = 10i128.checked_pow(diff.unsigned_abs())?;
            (self.mantissa % p == 0).then(|| self.mantissa / p)
        }
    }
}

impl fmt::Display for Quantity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Digits of |mantissa|, most significant first, without allocating.
        let mut digits = [0u8; 40];
        let mut n = self.mantissa.unsigned_abs();
        let mut len = 0usize;
        loop {
            if let Some(slot) = digits.get_mut(len) {
                *slot = b'0' + (n % 10) as u8;
            }
            len += 1;
            n /= 10;
            if n == 0 || len >= digits.len() {
                break;
            }
        }
        let digits = digits.get(..len).unwrap_or(&[]);
        if self.mantissa < 0 {
            f.write_str("-")?;
        }
        let exp = i32::from(self.exponent);
        if exp >= 0 {
            for d in digits.iter().rev() {
                write!(f, "{}", char::from(*d))?;
            }
            for _ in 0..exp {
                f.write_str("0")?;
            }
        } else {
            let frac = exp.unsigned_abs() as usize;
            if len <= frac {
                f.write_str("0.")?;
                for _ in len..frac {
                    f.write_str("0")?;
                }
                for d in digits.iter().rev() {
                    write!(f, "{}", char::from(*d))?;
                }
            } else {
                for (i, d) in digits.iter().rev().enumerate() {
                    if i == len - frac {
                        f.write_str(".")?;
                    }
                    write!(f, "{}", char::from(*d))?;
                }
            }
        }
        if let Some(unit) = self.unit.filter(|u| u.symbol() != Some("")) {
            write!(f, " {unit}")?;
        }
        Ok(())
    }
}

/// A point in time as SML encodes it: `SML_Time`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Time {
    /// Seconds since an arbitrary, device-specific epoch (often power-up).
    SecIndex(u32),
    /// Seconds since 1970-01-01T00:00:00Z.
    Timestamp(u32),
    /// A UTC timestamp with the local offsets the device applied.
    LocalTimestamp {
        /// Seconds since 1970-01-01T00:00:00Z.
        timestamp: u32,
        /// Offset of local time from UTC, in minutes.
        local_offset_minutes: i16,
        /// Additional daylight-saving offset, in minutes.
        season_offset_minutes: i16,
    },
}

impl Time {
    /// Seconds since 1970-01-01T00:00:00Z, for the two timestamp forms. A seconds index
    /// counts from a device-specific epoch and has no calendar time.
    pub const fn unix_seconds(self) -> Option<u32> {
        match self {
            Self::SecIndex(_) => None,
            Self::Timestamp(t) | Self::LocalTimestamp { timestamp: t, .. } => Some(t),
        }
    }

    pub(crate) fn read(r: &mut Reader<'_>, options: ParseOptions) -> Result<Self> {
        let u32_of = |v: u64| u32::try_from(v).map_err(|_| Error::ValueOutOfRange);
        // Holley DTZ541/DDZ285 send a bare Unsigned32 without the choice list.
        if options.bare_time && r.clone().read_tl().is_ok_and(|tl| tl.kind == Kind::Unsigned) {
            return Ok(Self::SecIndex(u32_of(r.unsigned()?)?));
        }
        r.list(2)?;
        let choice = r.unsigned()?;
        let i16_of = |v: i64| i16::try_from(v).map_err(|_| Error::ValueOutOfRange);
        match choice {
            1 => Ok(Self::SecIndex(u32_of(r.unsigned()?)?)),
            2 => Ok(Self::Timestamp(u32_of(r.unsigned()?)?)),
            3 => {
                r.list(3)?;
                Ok(Self::LocalTimestamp {
                    timestamp: u32_of(r.unsigned()?)?,
                    local_offset_minutes: i16_of(r.integer()?)?,
                    season_offset_minutes: i16_of(r.integer()?)?,
                })
            }
            choice => Err(Error::UnknownChoice { what: "SML_Time", choice }),
        }
    }

    pub(crate) fn read_opt(r: &mut Reader<'_>, options: ParseOptions) -> Result<Option<Self>> {
        if r.absent() { Ok(None) } else { Self::read(r, options).map(Some) }
    }

    /// Write the time with its choice tag.
    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
        w.list(2)?;
        match *self {
            Self::SecIndex(s) => {
                w.unsigned(1, 1)?;
                w.unsigned(u64::from(s), 4)
            }
            Self::Timestamp(t) => {
                w.unsigned(2, 1)?;
                w.unsigned(u64::from(t), 4)
            }
            Self::LocalTimestamp { timestamp, local_offset_minutes, season_offset_minutes } => {
                w.unsigned(3, 1)?;
                w.list(3)?;
                w.unsigned(u64::from(timestamp), 4)?;
                w.integer(i64::from(local_offset_minutes), 2)?;
                w.integer(i64::from(season_offset_minutes), 2)
            }
        }
    }

    pub(crate) fn write_opt(t: Option<Self>, w: &mut Writer<'_>) -> Result<()> {
        match t {
            Some(t) => t.write(w),
            None => w.absent(),
        }
    }
}

/// Year, month, day of a day count since 1970-01-01 (Howard Hinnant's `civil_from_days`,
/// integers only).
fn civil_from_days(days: i64) -> (i64, i64, i64) {
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    (yoe + era * 400 + i64::from(month <= 2), month, day)
}

/// Seconds since 1970 as `YYYY-MM-DDThh:mm:ss`.
fn write_date_time(f: &mut fmt::Formatter<'_>, seconds: i64) -> fmt::Result {
    let (days, secs) = (seconds.div_euclid(86_400), seconds.rem_euclid(86_400));
    let (y, mo, d) = civil_from_days(days);
    write!(f, "{y:04}-{mo:02}-{d:02}T{:02}:{:02}:{:02}", secs / 3600, secs % 3600 / 60, secs % 60)
}

/// Timestamps as ISO 8601: `2023-11-14T22:13:20Z`, or local wall time with its offset
/// (`2023-11-14T23:13:20+01:00`); a seconds index as `secIndex 42 s`.
///
/// ```
/// use sml_kit::Time;
///
/// assert_eq!(Time::Timestamp(1_700_000_000).to_string(), "2023-11-14T22:13:20Z");
/// let local = Time::LocalTimestamp { timestamp: 1_700_000_000, local_offset_minutes: 60, season_offset_minutes: 0 };
/// assert_eq!(local.to_string(), "2023-11-14T23:13:20+01:00");
/// ```
impl fmt::Display for Time {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::SecIndex(s) => write!(f, "secIndex {s} s"),
            Self::Timestamp(t) => {
                write_date_time(f, i64::from(t))?;
                f.write_str("Z")
            }
            Self::LocalTimestamp { timestamp, local_offset_minutes, season_offset_minutes } => {
                let offset = i64::from(local_offset_minutes) + i64::from(season_offset_minutes);
                write_date_time(f, i64::from(timestamp) + 60 * offset)?;
                let sign = if offset < 0 { '-' } else { '+' };
                let offset = offset.unsigned_abs();
                write!(f, "{sign}{:02}:{:02}", offset / 60, offset % 60)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;
    use std::string::ToString;

    fn q(mantissa: i128, exponent: i8) -> std::string::String {
        Quantity { mantissa, exponent, unit: None }.to_string()
    }

    #[test]
    fn displays_exact_decimals() {
        assert_eq!(q(123_456, -1), "12345.6");
        assert_eq!(q(5, -3), "0.005");
        assert_eq!(q(-42, 0), "-42");
        assert_eq!(q(7, 2), "700");
        assert_eq!(q(0, -2), "0.00");
        assert_eq!(Quantity { mantissa: 15, exponent: -1, unit: Some(Unit::WH) }.to_string(), "1.5 Wh");
    }

    #[test]
    fn every_dlms_unit_code_has_a_symbol() {
        for code in 1..=56u8 {
            assert!(Unit(code).symbol().is_some_and(|s| !s.is_empty()), "unit {code}");
        }
        assert_eq!(Unit(57).to_string(), "unit(57)");
        assert_eq!(Unit::WH.to_string(), "Wh");
        assert_eq!(Quantity { mantissa: 3, exponent: 0, unit: Some(Unit::COUNT) }.to_string(), "3");
    }

    #[test]
    fn time_displays_as_iso_8601() {
        assert_eq!(Time::Timestamp(0).to_string(), "1970-01-01T00:00:00Z");
        assert_eq!(Time::Timestamp(951_782_400).to_string(), "2000-02-29T00:00:00Z");
        assert_eq!(Time::Timestamp(u32::MAX).to_string(), "2106-02-07T06:28:15Z");
        assert_eq!(Time::SecIndex(42).to_string(), "secIndex 42 s");
        // Calendar corners: 2100 is not a leap year, 2000 and 2096 are (epochs from Python's
        // calendar.timegm, independent of this code).
        for (t, date) in [
            (4_107_456_000, "2100-02-28"),
            (4_107_542_400, "2100-03-01"),
            (951_868_800, "2000-03-01"),
            (946_598_400, "1999-12-31"),
            (3_981_312_000, "2096-02-29"),
            (983_404_800, "2001-03-01"),
            (4_260_124_800, "2104-12-31"),
        ] {
            assert_eq!(Time::Timestamp(t).to_string(), std::format!("{date}T00:00:00Z"));
        }
        let utc = Time::LocalTimestamp { timestamp: 0, local_offset_minutes: 0, season_offset_minutes: 0 };
        assert_eq!(utc.to_string(), "1970-01-01T00:00:00+00:00");
        let summer = Time::LocalTimestamp {
            timestamp: 1_719_835_200,
            local_offset_minutes: 60,
            season_offset_minutes: 60,
        };
        assert_eq!(summer.to_string(), "2024-07-01T14:00:00+02:00");
        let west =
            Time::LocalTimestamp { timestamp: 0, local_offset_minutes: -330, season_offset_minutes: 0 };
        assert_eq!(west.to_string(), "1969-12-31T18:30:00-05:30");
    }

    #[test]
    fn times_round_trip() {
        let opts = ParseOptions::default();
        for t in [
            Time::SecIndex(7),
            Time::Timestamp(1_700_000_000),
            Time::LocalTimestamp { timestamp: 1, local_offset_minutes: 60, season_offset_minutes: -60 },
        ] {
            let mut buf = [0u8; 32];
            let mut w = Writer::new(&mut buf);
            t.write(&mut w).unwrap();
            let n = w.position();
            assert_eq!(Time::read(&mut Reader::new(&buf[..n]), opts).unwrap(), t);
        }
        assert_eq!(Time::SecIndex(1).unix_seconds(), None);
        assert_eq!(Time::Timestamp(5).unix_seconds(), Some(5));
    }

    #[test]
    fn rescales_without_rounding() {
        let e = Quantity { mantissa: 123_456, exponent: -1, unit: None };
        assert_eq!(e.to_scale(-3), Some(12_345_600));
        assert_eq!(e.to_scale(-1), Some(123_456));
        assert_eq!(e.to_scale(0), None, "12345.6 is not a whole number");
        let whole = Quantity { mantissa: 1230, exponent: -1, unit: None };
        assert_eq!(whole.to_scale(0), Some(123));
        assert_eq!(Quantity { mantissa: -1230, ..whole }.to_scale(0), Some(-123));
        assert_eq!(Quantity { mantissa: -12_000, ..whole }.to_scale(2), Some(-12), "-1200.0 is -12 hundreds");
        assert_eq!(Quantity { mantissa: 1235, ..whole }.to_scale(0), None);
        assert_eq!(Quantity { mantissa: 1, exponent: 0, unit: None }.to_scale(-40), None, "overflow");
    }
}