Skip to main content

dlms_cosem_kit/
obis.rs

1//! OBIS — the six-byte name every COSEM object carries.
2//!
3//! An OBIS code identifies *what* a value is, independently of the interface class that
4//! holds it: `A-B:C.D.E*F`, where A is the medium, B the channel, C the physical
5//! quantity, D the processing, E the tariff and F the billing period
6//! (Blue Book Part 1, "OBIS code structure").
7//!
8//! ```
9//! use dlms_cosem_kit::Obis;
10//!
11//! let total = Obis::parse("1-0:1.8.0*255").unwrap();
12//! assert_eq!(total, Obis::new(1, 0, 1, 8, 0, 255));
13//! assert_eq!(total.medium(), obis_medium());
14//! # fn obis_medium() -> dlms_cosem_kit::obis::Medium { dlms_cosem_kit::obis::Medium::Electricity }
15//! ```
16
17use core::fmt;
18
19use crate::codec::{Decode, Encode, Error, ErrorKind, Reader, Result, Writer};
20
21/// The medium an object measures — OBIS value group A.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
23#[non_exhaustive]
24pub enum Medium {
25    /// Abstract objects: clocks, association views, diagnostics. A = 0.
26    Abstract,
27    /// AC electricity. A = 1.
28    Electricity,
29    /// DC electricity. A = 2.
30    ElectricityDc,
31    /// Heat cost allocators. A = 4.
32    HeatCostAllocator,
33    /// Cooling (thermal energy, inlet). A = 5.
34    Cooling,
35    /// Heat (thermal energy). A = 6.
36    Heat,
37    /// Gas. A = 7.
38    Gas,
39    /// Cold water. A = 8.
40    ColdWater,
41    /// Hot water. A = 9.
42    HotWater,
43    /// Other media. A = 15.
44    Other,
45    /// A value group A this crate does not name.
46    Reserved(u8),
47}
48
49impl Medium {
50    /// The value group A byte.
51    #[must_use]
52    pub const fn as_u8(self) -> u8 {
53        match self {
54            Self::Abstract => 0,
55            Self::Electricity => 1,
56            Self::ElectricityDc => 2,
57            Self::HeatCostAllocator => 4,
58            Self::Cooling => 5,
59            Self::Heat => 6,
60            Self::Gas => 7,
61            Self::ColdWater => 8,
62            Self::HotWater => 9,
63            Self::Other => 15,
64            Self::Reserved(v) => v,
65        }
66    }
67
68    /// Classify a value group A byte.
69    #[must_use]
70    pub const fn from_u8(v: u8) -> Self {
71        match v {
72            0 => Self::Abstract,
73            1 => Self::Electricity,
74            2 => Self::ElectricityDc,
75            4 => Self::HeatCostAllocator,
76            5 => Self::Cooling,
77            6 => Self::Heat,
78            7 => Self::Gas,
79            8 => Self::ColdWater,
80            9 => Self::HotWater,
81            15 => Self::Other,
82            other => Self::Reserved(other),
83        }
84    }
85}
86
87/// A COSEM logical name: `A-B:C.D.E*F`, six bytes on the wire.
88///
89/// `Obis` is `const`-constructible so well-known codes are compile-time constants, and
90/// it is a plain `[u8; 6]` so comparing, sorting and hashing are what they look like.
91#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
92pub struct Obis(pub [u8; 6]);
93
94impl Obis {
95    /// From the six value groups.
96    #[must_use]
97    pub const fn new(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> Self {
98        Self([a, b, c, d, e, f])
99    }
100
101    /// From the six bytes as they appear on the wire.
102    #[must_use]
103    pub const fn from_bytes(b: [u8; 6]) -> Self {
104        Self(b)
105    }
106
107    /// The six bytes as they appear on the wire.
108    #[must_use]
109    pub const fn as_bytes(&self) -> &[u8; 6] {
110        &self.0
111    }
112
113    /// Value group A — the medium.
114    #[must_use]
115    pub const fn a(&self) -> u8 {
116        self.0[0]
117    }
118
119    /// Value group B — the channel.
120    #[must_use]
121    pub const fn b(&self) -> u8 {
122        self.0[1]
123    }
124
125    /// Value group C — the physical quantity.
126    #[must_use]
127    pub const fn c(&self) -> u8 {
128        self.0[2]
129    }
130
131    /// Value group D — the processing.
132    #[must_use]
133    pub const fn d(&self) -> u8 {
134        self.0[3]
135    }
136
137    /// Value group E — the tariff or further classification.
138    #[must_use]
139    pub const fn e(&self) -> u8 {
140        self.0[4]
141    }
142
143    /// Value group F — the billing period.
144    #[must_use]
145    pub const fn f(&self) -> u8 {
146        self.0[5]
147    }
148
149    /// The medium, classified.
150    #[must_use]
151    pub const fn medium(&self) -> Medium {
152        Medium::from_u8(self.0[0])
153    }
154
155    /// True for a code in a manufacturer-specific range.
156    ///
157    /// Blue Book Part 1 reserves `C` in 128..=199 and `D`/`E` in 128..=254 for
158    /// manufacturers; a client should not attach standard semantics to one.
159    #[must_use]
160    pub const fn is_manufacturer_specific(&self) -> bool {
161        (self.0[2] >= 128 && self.0[2] <= 199)
162            || (self.0[3] >= 128 && self.0[3] <= 254)
163            || (self.0[4] >= 128 && self.0[4] <= 254)
164    }
165
166    /// Parse the textual notation.
167    ///
168    /// Accepts `A-B:C.D.E*F`, `A-B:C.D.E` (F defaults to 255) and the reduced `C.D.E`
169    /// used by IEC 62056-21 and the P1 port (A defaults to 1, B and E to 0, F to 255).
170    /// Separators are accepted liberally — `.`, `-`, `:` and `*` all delimit — because
171    /// meter documentation is not consistent about them, but the *number* of groups is
172    /// not: three or six, never four or five.
173    pub fn parse(s: &str) -> core::result::Result<Self, ObisParseError> {
174        let mut groups = [0u16; 6];
175        let mut n = 0usize;
176        let mut have_digit = false;
177        let mut cur: u16 = 0;
178        for ch in s.bytes() {
179            match ch {
180                b'0'..=b'9' => {
181                    if !have_digit {
182                        cur = 0;
183                    }
184                    have_digit = true;
185                    cur = cur
186                        .checked_mul(10)
187                        .and_then(|v| v.checked_add(u16::from(ch - b'0')))
188                        .ok_or(ObisParseError)?;
189                    if cur > 255 {
190                        return Err(ObisParseError);
191                    }
192                }
193                b'-' | b':' | b'.' | b'*' | b'&' => {
194                    if !have_digit || n >= 6 {
195                        return Err(ObisParseError);
196                    }
197                    groups[n] = cur;
198                    n += 1;
199                    have_digit = false;
200                }
201                _ => return Err(ObisParseError),
202            }
203        }
204        if !have_digit || n >= 6 {
205            return Err(ObisParseError);
206        }
207        groups[n] = cur;
208        n += 1;
209
210        // Indexing a fixed array with a literal, written so the bound is discharged at
211        // compile time rather than left as a runtime check.
212        let g = |i: usize| groups.get(i).copied().unwrap_or(0) as u8;
213        match n {
214            3 => Ok(Self::new(1, 0, g(0), g(1), g(2), 255)),
215            5 => Ok(Self::new(g(0), g(1), g(2), g(3), g(4), 255)),
216            6 => Ok(Self::new(g(0), g(1), g(2), g(3), g(4), g(5))),
217            _ => Err(ObisParseError),
218        }
219    }
220}
221
222/// The textual notation could not be read as an OBIS code.
223#[derive(Debug, Clone, Copy, PartialEq, Eq)]
224pub struct ObisParseError;
225
226impl fmt::Display for ObisParseError {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        f.write_str("not an OBIS code")
229    }
230}
231
232#[cfg(feature = "std")]
233impl std::error::Error for ObisParseError {}
234
235impl core::str::FromStr for Obis {
236    type Err = ObisParseError;
237
238    fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
239        Self::parse(s)
240    }
241}
242
243impl fmt::Display for Obis {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        let [a, b, c, d, e, g] = self.0;
246        write!(f, "{a}-{b}:{c}.{d}.{e}*{g}")
247    }
248}
249
250impl fmt::Debug for Obis {
251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        write!(f, "Obis({self})")
253    }
254}
255
256impl From<[u8; 6]> for Obis {
257    fn from(v: [u8; 6]) -> Self {
258        Self(v)
259    }
260}
261
262impl From<Obis> for [u8; 6] {
263    fn from(v: Obis) -> Self {
264        v.0
265    }
266}
267
268impl Encode for Obis {
269    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
270        w.write_bytes(&self.0)
271    }
272
273    fn encoded_len(&self) -> usize {
274        6
275    }
276}
277
278impl<'a> Decode<'a> for Obis {
279    fn decode(r: &mut Reader<'a>) -> Result<Self> {
280        Ok(Self(r.array::<6>()?))
281    }
282}
283
284impl Obis {
285    /// Read an OBIS code from an octet string that must be exactly six bytes.
286    pub fn from_octet_string(bytes: &[u8], offset: usize) -> Result<Self> {
287        let arr: [u8; 6] = bytes.try_into().map_err(|_| Error::new(ErrorKind::InvalidLength, offset))?;
288        Ok(Self(arr))
289    }
290}
291
292/// Well-known logical names.
293///
294/// Only codes whose meaning is fixed by the Blue Book and stable across profiles are
295/// listed. A meter's own object list is the authority for everything else.
296#[cfg(feature = "obis-names")]
297pub mod names {
298    use super::Obis;
299
300    /// The clock object, `0-0:1.0.0*255`.
301    pub const CLOCK: Obis = Obis::new(0, 0, 1, 0, 0, 255);
302    /// COSEM logical device name, `0-0:42.0.0*255`.
303    pub const LOGICAL_DEVICE_NAME: Obis = Obis::new(0, 0, 42, 0, 0, 255);
304    /// The current association object, `0-0:40.0.0*255`.
305    pub const CURRENT_ASSOCIATION: Obis = Obis::new(0, 0, 40, 0, 0, 255);
306    /// Security setup for the management association, `0-0:43.0.0*255`.
307    pub const SECURITY_SETUP: Obis = Obis::new(0, 0, 43, 0, 0, 255);
308    /// SAP assignment, `0-0:41.0.0*255`.
309    pub const SAP_ASSIGNMENT: Obis = Obis::new(0, 0, 41, 0, 0, 255);
310    /// Device ID 1, the manufacturer's serial number, `0-0:96.1.0*255`.
311    pub const DEVICE_ID_1: Obis = Obis::new(0, 0, 96, 1, 0, 255);
312    /// The error register, `0-0:97.97.0*255`.
313    pub const ERROR_REGISTER: Obis = Obis::new(0, 0, 97, 97, 0, 255);
314    /// The standard event log, `0-0:99.98.0*255`.
315    pub const EVENT_LOG: Obis = Obis::new(0, 0, 99, 98, 0, 255);
316    /// IEC HDLC setup for port 0, `0-0:22.0.0*255`.
317    pub const HDLC_SETUP: Obis = Obis::new(0, 0, 22, 0, 0, 255);
318    /// Disconnect control, `0-0:96.3.10*255`.
319    pub const DISCONNECT_CONTROL: Obis = Obis::new(0, 0, 96, 3, 10, 255);
320    /// Push setup, `0-0:25.9.0*255`.
321    pub const PUSH_SETUP: Obis = Obis::new(0, 0, 25, 9, 0, 255);
322    /// Image transfer, `0-0:44.0.0*255`.
323    pub const IMAGE_TRANSFER: Obis = Obis::new(0, 0, 44, 0, 0, 255);
324
325    /// Active energy imported, total: `1-0:1.8.0*255`.
326    pub const ACTIVE_ENERGY_IMPORT_TOTAL: Obis = Obis::new(1, 0, 1, 8, 0, 255);
327    /// Active energy imported, rate 1: `1-0:1.8.1*255`.
328    pub const ACTIVE_ENERGY_IMPORT_T1: Obis = Obis::new(1, 0, 1, 8, 1, 255);
329    /// Active energy imported, rate 2: `1-0:1.8.2*255`.
330    pub const ACTIVE_ENERGY_IMPORT_T2: Obis = Obis::new(1, 0, 1, 8, 2, 255);
331    /// Active energy exported, total: `1-0:2.8.0*255`.
332    pub const ACTIVE_ENERGY_EXPORT_TOTAL: Obis = Obis::new(1, 0, 2, 8, 0, 255);
333    /// Reactive energy imported (Q1+Q2), total: `1-0:3.8.0*255`.
334    pub const REACTIVE_ENERGY_IMPORT_TOTAL: Obis = Obis::new(1, 0, 3, 8, 0, 255);
335    /// Reactive energy exported (Q3+Q4), total: `1-0:4.8.0*255`.
336    pub const REACTIVE_ENERGY_EXPORT_TOTAL: Obis = Obis::new(1, 0, 4, 8, 0, 255);
337    /// Instantaneous active power imported: `1-0:1.7.0*255`.
338    pub const ACTIVE_POWER_IMPORT: Obis = Obis::new(1, 0, 1, 7, 0, 255);
339    /// Instantaneous active power exported: `1-0:2.7.0*255`.
340    pub const ACTIVE_POWER_EXPORT: Obis = Obis::new(1, 0, 2, 7, 0, 255);
341    /// Instantaneous voltage, phase L1: `1-0:32.7.0*255`.
342    pub const VOLTAGE_L1: Obis = Obis::new(1, 0, 32, 7, 0, 255);
343    /// Instantaneous voltage, phase L2: `1-0:52.7.0*255`.
344    pub const VOLTAGE_L2: Obis = Obis::new(1, 0, 52, 7, 0, 255);
345    /// Instantaneous voltage, phase L3: `1-0:72.7.0*255`.
346    pub const VOLTAGE_L3: Obis = Obis::new(1, 0, 72, 7, 0, 255);
347    /// Instantaneous current, phase L1: `1-0:31.7.0*255`.
348    pub const CURRENT_L1: Obis = Obis::new(1, 0, 31, 7, 0, 255);
349    /// Instantaneous current, phase L2: `1-0:51.7.0*255`.
350    pub const CURRENT_L2: Obis = Obis::new(1, 0, 51, 7, 0, 255);
351    /// Instantaneous current, phase L3: `1-0:71.7.0*255`.
352    pub const CURRENT_L3: Obis = Obis::new(1, 0, 71, 7, 0, 255);
353    /// The load profile with a one-minute to one-hour capture period: `1-0:99.1.0*255`.
354    pub const LOAD_PROFILE_1: Obis = Obis::new(1, 0, 99, 1, 0, 255);
355    /// The daily profile: `1-0:99.2.0*255`.
356    pub const LOAD_PROFILE_2: Obis = Obis::new(1, 0, 99, 2, 0, 255);
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362    use crate::codec::SliceWriter;
363
364    #[test]
365    fn textual_notation_round_trips() {
366        #[cfg(feature = "std")]
367        {
368            use std::string::ToString;
369            let o = Obis::new(1, 0, 1, 8, 0, 255);
370            assert_eq!(o.to_string(), "1-0:1.8.0*255");
371            assert_eq!(Obis::parse(&o.to_string()).unwrap(), o);
372        }
373    }
374
375    #[test]
376    fn the_three_accepted_shapes() {
377        assert_eq!(Obis::parse("1-0:1.8.0*255").unwrap(), Obis::new(1, 0, 1, 8, 0, 255));
378        assert_eq!(Obis::parse("1-0:1.8.0").unwrap(), Obis::new(1, 0, 1, 8, 0, 255));
379        assert_eq!(Obis::parse("1.8.0").unwrap(), Obis::new(1, 0, 1, 8, 0, 255));
380    }
381
382    #[test]
383    fn a_group_count_that_is_not_three_five_or_six_is_refused() {
384        assert!(Obis::parse("1.8").is_err());
385        assert!(Obis::parse("1-0:1.8").is_err());
386        assert!(Obis::parse("1-0:1.8.0*255*1").is_err());
387    }
388
389    #[test]
390    fn a_group_above_255_is_refused_rather_than_truncated() {
391        assert!(Obis::parse("1-0:1.8.256").is_err());
392        assert!(Obis::parse("1-0:1.8.99999").is_err());
393    }
394
395    #[test]
396    fn junk_is_refused() {
397        for s in ["", "-", "1-0:1.8.x", "1--0:1.8.0", "1-0:1.8.", "abc"] {
398            assert!(Obis::parse(s).is_err(), "{s:?} should not parse");
399        }
400    }
401
402    #[test]
403    fn wire_form_is_six_bytes_in_order() {
404        let o = Obis::new(1, 0, 1, 8, 0, 255);
405        let mut buf = [0u8; 6];
406        let mut w = SliceWriter::new(&mut buf);
407        o.encode(&mut w).unwrap();
408        assert_eq!(buf, [1, 0, 1, 8, 0, 255]);
409        assert_eq!(Obis::from_bytes(buf), o);
410    }
411
412    #[test]
413    fn manufacturer_ranges_are_recognised() {
414        assert!(Obis::new(1, 0, 128, 8, 0, 255).is_manufacturer_specific());
415        assert!(!Obis::new(1, 0, 1, 8, 0, 255).is_manufacturer_specific());
416    }
417
418    #[test]
419    fn media_classify() {
420        assert_eq!(Obis::new(0, 0, 1, 0, 0, 255).medium(), Medium::Abstract);
421        assert_eq!(Obis::new(7, 0, 3, 0, 0, 255).medium(), Medium::Gas);
422        assert_eq!(Obis::new(3, 0, 3, 0, 0, 255).medium(), Medium::Reserved(3));
423    }
424}