Skip to main content

sml_kit/
obis.rs

1use core::fmt;
2use core::str::FromStr;
3
4use crate::Error;
5
6/// An OBIS code (IEC 62056-61): the six-byte name of a measured quantity.
7///
8/// Displays as `A-B:C.D.E*F`, e.g. `1-0:1.8.0*255` for imported active energy, and
9/// parses from that form, from `A-B:C.D.E` (F = 255) and from the short `C.D.E` printed
10/// on meters (A = 1, B = 0, F = 255):
11///
12/// ```
13/// use sml_kit::Obis;
14///
15/// assert_eq!("1-0:1.8.0*255".parse(), Ok(Obis::ENERGY_IMPORT));
16/// assert_eq!("1.8.0".parse(), Ok(Obis::ENERGY_IMPORT));
17/// assert_eq!(Obis::ENERGY_IMPORT.name(), Some("active energy import (A+), total"));
18/// ```
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub struct Obis(pub [u8; 6]);
21
22impl Obis {
23    /// `1-0:1.8.0*255`: active energy imported (A+), total.
24    pub const ENERGY_IMPORT: Self = Self::new(1, 0, 1, 8, 0, 255);
25    /// `1-0:1.8.1*255`: active energy imported, tariff 1.
26    pub const ENERGY_IMPORT_T1: Self = Self::new(1, 0, 1, 8, 1, 255);
27    /// `1-0:1.8.2*255`: active energy imported, tariff 2.
28    pub const ENERGY_IMPORT_T2: Self = Self::new(1, 0, 1, 8, 2, 255);
29    /// `1-0:2.8.0*255`: active energy exported (A−), total.
30    pub const ENERGY_EXPORT: Self = Self::new(1, 0, 2, 8, 0, 255);
31    /// `1-0:2.8.1*255`: active energy exported, tariff 1.
32    pub const ENERGY_EXPORT_T1: Self = Self::new(1, 0, 2, 8, 1, 255);
33    /// `1-0:2.8.2*255`: active energy exported, tariff 2.
34    pub const ENERGY_EXPORT_T2: Self = Self::new(1, 0, 2, 8, 2, 255);
35    /// `1-0:16.7.0*255`: active power, sum of phases (positive = import).
36    pub const POWER: Self = Self::new(1, 0, 16, 7, 0, 255);
37    /// `1-0:36.7.0*255`: active power, phase L1.
38    pub const POWER_L1: Self = Self::new(1, 0, 36, 7, 0, 255);
39    /// `1-0:56.7.0*255`: active power, phase L2.
40    pub const POWER_L2: Self = Self::new(1, 0, 56, 7, 0, 255);
41    /// `1-0:76.7.0*255`: active power, phase L3.
42    pub const POWER_L3: Self = Self::new(1, 0, 76, 7, 0, 255);
43    /// `1-0:31.7.0*255`: current, phase L1.
44    pub const CURRENT_L1: Self = Self::new(1, 0, 31, 7, 0, 255);
45    /// `1-0:51.7.0*255`: current, phase L2.
46    pub const CURRENT_L2: Self = Self::new(1, 0, 51, 7, 0, 255);
47    /// `1-0:71.7.0*255`: current, phase L3.
48    pub const CURRENT_L3: Self = Self::new(1, 0, 71, 7, 0, 255);
49    /// `1-0:32.7.0*255`: voltage, phase L1.
50    pub const VOLTAGE_L1: Self = Self::new(1, 0, 32, 7, 0, 255);
51    /// `1-0:52.7.0*255`: voltage, phase L2.
52    pub const VOLTAGE_L2: Self = Self::new(1, 0, 52, 7, 0, 255);
53    /// `1-0:72.7.0*255`: voltage, phase L3.
54    pub const VOLTAGE_L3: Self = Self::new(1, 0, 72, 7, 0, 255);
55    /// `1-0:14.7.0*255`: supply frequency.
56    pub const FREQUENCY: Self = Self::new(1, 0, 14, 7, 0, 255);
57    /// `1-0:0.0.9*255`: the device identifier (server ID).
58    pub const DEVICE_ID: Self = Self::new(1, 0, 0, 0, 9, 255);
59    /// `1-0:96.1.0*255`: the meter's serial number (server ID on newer meters).
60    pub const SERIAL: Self = Self::new(1, 0, 96, 1, 0, 255);
61    /// `1-0:96.5.0*255`: the operating status word.
62    pub const STATUS: Self = Self::new(1, 0, 96, 5, 0, 255);
63    /// `129-129:199.130.3*255`: the manufacturer identifier.
64    pub const MANUFACTURER: Self = Self::new(129, 129, 199, 130, 3, 255);
65    /// `1-0:96.50.1*1`: the manufacturer identifier as newer meters label it.
66    pub const MANUFACTURER_ALT: Self = Self::new(1, 0, 96, 50, 1, 1);
67    /// `129-129:199.130.5*255`: the meter's public key (for signed readings).
68    pub const PUBLIC_KEY: Self = Self::new(129, 129, 199, 130, 5, 255);
69    /// `1-0:0.2.0*0`: the firmware version.
70    pub const FIRMWARE: Self = Self::new(1, 0, 0, 2, 0, 0);
71
72    /// The OBIS code `A-B:C.D.E*F`.
73    #[allow(clippy::many_single_char_names)] // A to F are the standard's names.
74    pub const fn new(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> Self {
75        Self([a, b, c, d, e, f])
76    }
77
78    /// The OBIS code in `bytes`, which must be exactly six bytes long.
79    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
80        <[u8; 6]>::try_from(bytes).map(Self).map_err(|_| Error::ObisLength(bytes.len()))
81    }
82
83    /// What the code means, for the codes a German meter commonly sends.
84    pub fn name(&self) -> Option<&'static str> {
85        const NAMES: &[(Obis, &str)] = &[
86            (Obis::ENERGY_IMPORT, "active energy import (A+), total"),
87            (Obis::ENERGY_IMPORT_T1, "active energy import (A+), tariff 1"),
88            (Obis::ENERGY_IMPORT_T2, "active energy import (A+), tariff 2"),
89            (Obis::ENERGY_EXPORT, "active energy export (A-), total"),
90            (Obis::ENERGY_EXPORT_T1, "active energy export (A-), tariff 1"),
91            (Obis::ENERGY_EXPORT_T2, "active energy export (A-), tariff 2"),
92            (Obis::POWER, "active power, total"),
93            (Obis::POWER_L1, "active power, L1"),
94            (Obis::POWER_L2, "active power, L2"),
95            (Obis::POWER_L3, "active power, L3"),
96            (Obis::CURRENT_L1, "current, L1"),
97            (Obis::CURRENT_L2, "current, L2"),
98            (Obis::CURRENT_L3, "current, L3"),
99            (Obis::VOLTAGE_L1, "voltage, L1"),
100            (Obis::VOLTAGE_L2, "voltage, L2"),
101            (Obis::VOLTAGE_L3, "voltage, L3"),
102            (Obis::FREQUENCY, "frequency"),
103            (Obis::DEVICE_ID, "device identifier"),
104            (Obis::SERIAL, "serial number"),
105            (Obis::STATUS, "status word"),
106            (Obis::MANUFACTURER, "manufacturer"),
107            (Obis::MANUFACTURER_ALT, "manufacturer"),
108            (Obis::PUBLIC_KEY, "public key"),
109            (Obis::FIRMWARE, "firmware version"),
110        ];
111        NAMES.iter().find(|(o, _)| o == self).map(|&(_, n)| n)
112    }
113
114    /// Whether this is active power, total or per phase (`1-0:{16,36,56,76}.7.0`, any F).
115    pub(crate) fn is_active_power(self) -> bool {
116        matches!(self.0, [1, 0, 16 | 36 | 56 | 76, 7, 0, _])
117    }
118}
119
120impl From<[u8; 6]> for Obis {
121    fn from(bytes: [u8; 6]) -> Self {
122        Self(bytes)
123    }
124}
125
126impl From<Obis> for [u8; 6] {
127    fn from(obis: Obis) -> Self {
128        obis.0
129    }
130}
131
132/// Six bytes, or [`Error::ObisLength`].
133impl TryFrom<&[u8]> for Obis {
134    type Error = Error;
135
136    fn try_from(bytes: &[u8]) -> Result<Self, Error> {
137        Self::from_bytes(bytes)
138    }
139}
140
141impl fmt::Display for Obis {
142    #[allow(clippy::many_single_char_names)] // A to F are the standard's names.
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        let [a, b, c, d, e, g] = self.0;
145        write!(f, "{a}-{b}:{c}.{d}.{e}*{g}")
146    }
147}
148
149impl FromStr for Obis {
150    type Err = Error;
151
152    #[allow(clippy::many_single_char_names)] // A to F are the standard's names.
153    fn from_str(s: &str) -> Result<Self, Error> {
154        fn num(s: &str) -> Result<u8, Error> {
155            // `u8::from_str` alone would accept a leading `+`; it rejects empty and > 255.
156            if !s.bytes().all(|b| b.is_ascii_digit()) {
157                return Err(Error::ObisSyntax);
158            }
159            s.parse().map_err(|_| Error::ObisSyntax)
160        }
161        fn cde(s: &str) -> Result<[u8; 3], Error> {
162            let mut it = s.split('.');
163            let (Some(c), Some(d), Some(e), None) = (it.next(), it.next(), it.next(), it.next()) else {
164                return Err(Error::ObisSyntax);
165            };
166            Ok([num(c)?, num(d)?, num(e)?])
167        }
168        let (ab, rest) = match s.split_once(':') {
169            Some((ab, rest)) => (Some(ab), rest),
170            None => (None, s),
171        };
172        let (cde_text, f) = match rest.split_once('*') {
173            Some((cde, f)) => (cde, num(f)?),
174            None => (rest, 255),
175        };
176        let (a, b) = match ab {
177            Some(ab) => {
178                let (a, b) = ab.split_once('-').ok_or(Error::ObisSyntax)?;
179                (num(a)?, num(b)?)
180            }
181            None if f == 255 && !rest.contains('*') => (1, 0),
182            None => return Err(Error::ObisSyntax),
183        };
184        let [c, d, e] = cde(cde_text)?;
185        Ok(Self([a, b, c, d, e, f]))
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    extern crate std;
192    use super::*;
193    use std::string::ToString;
194
195    #[test]
196    fn displays_in_reduced_id_notation() {
197        assert_eq!(Obis::ENERGY_IMPORT.to_string(), "1-0:1.8.0*255");
198        assert_eq!(Obis::MANUFACTURER.to_string(), "129-129:199.130.3*255");
199    }
200
201    #[test]
202    fn rejects_wrong_length() {
203        assert_eq!(Obis::from_bytes(&[1, 2, 3]), Err(Error::ObisLength(3)));
204        assert_eq!(Obis::try_from(&[1u8, 2, 3][..]), Err(Error::ObisLength(3)));
205        assert_eq!(Obis::try_from(&[1u8, 0, 1, 8, 0, 255][..]), Ok(Obis::ENERGY_IMPORT));
206        assert_eq!(Obis::from([1, 0, 1, 8, 0, 255]), Obis::ENERGY_IMPORT);
207        assert_eq!(<[u8; 6]>::from(Obis::POWER), [1, 0, 16, 7, 0, 255]);
208    }
209
210    #[test]
211    fn parses_the_three_forms() {
212        assert_eq!("1-0:1.8.0*255".parse(), Ok(Obis::ENERGY_IMPORT));
213        assert_eq!("1-0:1.8.0".parse(), Ok(Obis::ENERGY_IMPORT));
214        assert_eq!("16.7.0".parse(), Ok(Obis::POWER));
215        assert_eq!("1-0:96.50.1*1".parse(), Ok(Obis::MANUFACTURER_ALT));
216        for o in [Obis::MANUFACTURER, Obis::FIRMWARE, Obis::new(0, 0, 0, 0, 0, 0)] {
217            assert_eq!(o.to_string().parse(), Ok(o));
218        }
219    }
220
221    #[test]
222    fn rejects_malformed_text() {
223        for bad in [
224            "",
225            "1.8",
226            "1.8.0.0",
227            "1-0:1.8.0*",
228            "1:1.8.0",
229            "256.8.0",
230            "+1.8.0",
231            "1.8.0*255",
232            "a.b.c",
233            "1-0-0:1.8.0",
234        ] {
235            assert_eq!(bad.parse::<Obis>(), Err(Error::ObisSyntax), "{bad}");
236        }
237    }
238
239    #[test]
240    fn power_codes_any_billing_period() {
241        assert!(Obis::POWER_L2.is_active_power());
242        assert!(Obis::new(1, 0, 16, 7, 0, 0).is_active_power());
243        assert!(!Obis::ENERGY_IMPORT.is_active_power());
244    }
245}