Skip to main content

sml_kit/
tree.rs

1//! Process parameters and profile entries: `SML_Tree`, `SML_ProcParValue`,
2//! `SML_PeriodEntry` and `SML_TupelEntry` (TR-03109-1 Anlage IV, letters BB, FF, GG, HH).
3//!
4//! A gateway or service tool reads and writes a meter's parameters as a tree of named
5//! nodes. FNN Lastenheft EDL names the common ones, e.g. device identification
6//! `81 81 C7 82 01 FF` with the manufacturer, server ID, public key and firmware below it.
7//!
8//! ```
9//! use sml_kit::{ProcParValue, SmlValue, Tree, Trees};
10//!
11//! let leaves = [Tree::leaf(&[0x81, 0x81, 0xC7, 0x82, 0x03, 0xFF], ProcParValue::Value(SmlValue::Bytes(b"EMH")))];
12//! let root = Tree { name: &[0x81, 0x81, 0xC7, 0x82, 0x01, 0xFF], value: None, children: Some(Trees::from_slice(&leaves)) };
13//! let manufacturer = root.child(&[0x81, 0x81, 0xC7, 0x82, 0x03, 0xFF]).unwrap();
14//! assert_eq!(manufacturer.value, Some(ProcParValue::Value(SmlValue::Bytes(b"EMH"))));
15//! ```
16
17use crate::seq::{Ctx, Element, Seq};
18use crate::tl::{Reader, Writer};
19use crate::value::{Quantity, SmlValue, Time, Unit};
20use crate::{Error, ListEntry, Obis, Result, ServerId};
21
22/// The children of a [`Tree`].
23pub type Trees<'a> = Seq<'a, Tree<'a>>;
24/// Period entries of a profile.
25pub type PeriodEntries<'a> = Seq<'a, PeriodEntry<'a>>;
26/// A sequence of names: an `SML_TreePath`, or a profile's object list.
27pub type NameList<'a> = Seq<'a, &'a [u8]>;
28
29/// `SML_Tree`: one named parameter, with a value, children, or both.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub struct Tree<'a> {
32    /// The parameter's name, usually an OBIS code.
33    pub name: &'a [u8],
34    /// The parameter's value, when the node has one.
35    pub value: Option<ProcParValue<'a>>,
36    /// The child parameters, when the node has them.
37    pub children: Option<Trees<'a>>,
38}
39
40impl<'a> Tree<'a> {
41    /// A node with a value and no children.
42    pub const fn leaf(name: &'a [u8], value: ProcParValue<'a>) -> Self {
43        Self { name, value: Some(value), children: None }
44    }
45
46    /// Whether the node has no children (absent or empty).
47    pub fn is_leaf(&self) -> bool {
48        self.children.is_none_or(|c| c.is_empty())
49    }
50
51    /// The first child named `name` that parses.
52    pub fn child(&self, name: &[u8]) -> Option<Self> {
53        self.children?.iter().filter_map(core::result::Result::ok).find(|c| c.name == name)
54    }
55}
56
57impl<'a> Element<'a> for Tree<'a> {
58    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
59        r.list(3)?;
60        let name = r.octet_string()?;
61        let value = if r.absent() { None } else { Some(ProcParValue::read(r, ctx)?) };
62        // The children are checked with the depth-bounded skip and parsed only when
63        // iterated, so a deep tree is an error here, never a deep recursion.
64        let children = Seq::read_opt(r, ctx)?;
65        Ok(Self { name, value, children })
66    }
67
68    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
69        w.list(3)?;
70        w.octet_string(self.name)?;
71        match self.value {
72            Some(v) => v.write(w)?,
73            None => w.absent()?,
74        }
75        Seq::write_opt(self.children, w)
76    }
77}
78
79impl<'a> Tree<'a> {
80    pub(crate) fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
81        // Validate the whole tree with the bounded skip before reading it.
82        r.clone().skip()?;
83        <Self as Element<'a>>::read(r, ctx)
84    }
85
86    pub(crate) fn read_opt(r: &mut Reader<'a>, ctx: Ctx) -> Result<Option<Self>> {
87        if r.absent() { Ok(None) } else { Self::read(r, ctx).map(Some) }
88    }
89
90    /// Write the tree.
91    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
92        <Self as Element<'a>>::write(self, w)
93    }
94
95    pub(crate) fn write_opt(t: Option<&Self>, w: &mut Writer<'_>) -> Result<()> {
96        match t {
97            Some(t) => t.write(w),
98            None => w.absent(),
99        }
100    }
101}
102
103/// `SML_ProcParValue`: the value of a parameter.
104#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
105pub enum ProcParValue<'a> {
106    /// `0x01`: a plain value.
107    Value(SmlValue<'a>),
108    /// `0x02`: a period entry (e.g. a historic consumption).
109    Period(PeriodEntry<'a>),
110    /// `0x03`: a tupel entry (signed A+/A− and reactive registers).
111    Tupel(TupelEntry<'a>),
112    /// `0x04`: a time.
113    Time(Time),
114    /// `0x05`: a list entry (e.g. the signed meter reading `01 00 01 11 00 FF` of an EDL
115    /// meter). libsml does not accept this choice; the specification has it since 2009.
116    Entry(ListEntry<'a>),
117}
118
119impl<'a> ProcParValue<'a> {
120    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
121        r.list(2)?;
122        Ok(match r.unsigned()? {
123            1 => Self::Value(SmlValue::read(r, ctx.options)?.0),
124            2 => Self::Period(<PeriodEntry<'a> as Element<'a>>::read(r, ctx)?),
125            3 => Self::Tupel(TupelEntry::read(r, ctx)?),
126            4 => Self::Time(Time::read(r, ctx.options)?),
127            5 => Self::Entry(<ListEntry<'a> as Element<'a>>::read(r, ctx)?),
128            choice => return Err(Error::UnknownChoice { what: "SML_ProcParValue", choice }),
129        })
130    }
131
132    /// Write the value with its choice tag.
133    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
134        w.list(2)?;
135        match self {
136            Self::Value(v) => {
137                w.unsigned(1, 1)?;
138                v.write(w)
139            }
140            Self::Period(p) => {
141                w.unsigned(2, 1)?;
142                p.write(w)
143            }
144            Self::Tupel(t) => {
145                w.unsigned(3, 1)?;
146                t.write(w)
147            }
148            Self::Time(t) => {
149                w.unsigned(4, 1)?;
150                t.write(w)
151            }
152            Self::Entry(e) => {
153                w.unsigned(5, 1)?;
154                e.write(w)
155            }
156        }
157    }
158}
159
160/// `SML_PeriodEntry`: one value of a profile period, or a historic value.
161#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
162pub struct PeriodEntry<'a> {
163    /// What the value is.
164    pub obis: Obis,
165    /// The unit.
166    pub unit: Unit,
167    /// The decimal exponent.
168    pub scaler: i8,
169    /// The value.
170    pub value: SmlValue<'a>,
171    /// A signature over the value, when the device signs. **Not verified** by this crate.
172    pub value_signature: Option<&'a [u8]>,
173}
174
175impl PeriodEntry<'_> {
176    /// The value as an exact [`Quantity`], when it is numeric.
177    pub fn quantity(&self) -> Option<Quantity> {
178        let mantissa = match self.value {
179            SmlValue::Int(v) => i128::from(v),
180            SmlValue::Uint(v) => i128::from(v),
181            SmlValue::Bool(_) | SmlValue::Bytes(_) | SmlValue::Time(_) => return None,
182        };
183        Some(Quantity { mantissa, exponent: self.scaler, unit: Some(self.unit) })
184    }
185}
186
187impl<'a> Element<'a> for PeriodEntry<'a> {
188    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
189        r.list(5)?;
190        let obis = Obis::from_bytes(r.octet_string()?)?;
191        let unit = Unit(u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?);
192        let scaler = i8::try_from(r.integer()?).map_err(|_| Error::ValueOutOfRange)?;
193        let value = SmlValue::read(r, ctx.options)?.0;
194        let value_signature = r.opt_octet_string()?;
195        Ok(Self { obis, unit, scaler, value, value_signature })
196    }
197
198    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
199        w.list(5)?;
200        w.octet_string(&self.obis.0)?;
201        w.unsigned(u64::from(self.unit.0), 1)?;
202        w.integer(i64::from(self.scaler), 1)?;
203        self.value.write(w)?;
204        w.opt_octet_string(self.value_signature)
205    }
206}
207
208/// One register of a [`TupelEntry`]: `value × 10^scaler` in `unit`, as on the wire
209/// (`Unsigned8`, `Integer8`, `Integer64`).
210#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
211pub struct Register {
212    /// The unit.
213    pub unit: Unit,
214    /// The decimal exponent.
215    pub scaler: i8,
216    /// The raw value.
217    pub value: i64,
218}
219
220impl Register {
221    /// The register as an exact [`Quantity`].
222    pub const fn quantity(self) -> Quantity {
223        Quantity { mantissa: self.value as i128, exponent: self.scaler, unit: Some(self.unit) }
224    }
225}
226
227/// `SML_TupelEntry`: a signed set of registers (A+, R1, R4 and A−, R2, R3). 23 fields on
228/// the wire.
229#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
230pub struct TupelEntry<'a> {
231    /// The device.
232    pub server_id: ServerId<'a>,
233    /// When the registers were captured.
234    pub sec_index: Time,
235    /// Device status bits.
236    pub status: u64,
237    /// Active energy import (A+).
238    pub a_plus: Register,
239    /// Reactive energy, quadrant I (R1).
240    pub r1: Register,
241    /// Reactive energy, quadrant IV (R4).
242    pub r4: Register,
243    /// Signature over A+, R1 and R4. **Not verified** by this crate.
244    pub signature_a_plus: &'a [u8],
245    /// Active energy export (A−).
246    pub a_minus: Register,
247    /// Reactive energy, quadrant II (R2).
248    pub r2: Register,
249    /// Reactive energy, quadrant III (R3).
250    pub r3: Register,
251    /// Signature over A−, R2 and R3. **Not verified** by this crate.
252    pub signature_a_minus: &'a [u8],
253}
254
255fn read_register(r: &mut Reader<'_>) -> Result<Register> {
256    let unit = Unit(u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?);
257    let scaler = i8::try_from(r.integer()?).map_err(|_| Error::ValueOutOfRange)?;
258    Ok(Register { unit, scaler, value: r.integer()? })
259}
260
261fn write_register(w: &mut Writer<'_>, reg: Register) -> Result<()> {
262    w.unsigned(u64::from(reg.unit.0), 1)?;
263    w.integer(i64::from(reg.scaler), 1)?;
264    w.integer(reg.value, 8)
265}
266
267impl<'a> TupelEntry<'a> {
268    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
269        r.list(23)?;
270        let server_id = ServerId::new(r.octet_string()?);
271        let sec_index = Time::read(r, ctx.options)?;
272        let status = r.unsigned()?;
273        let (a_plus, r1, r4) = (read_register(r)?, read_register(r)?, read_register(r)?);
274        let signature_a_plus = r.octet_string()?;
275        let (a_minus, r2, r3) = (read_register(r)?, read_register(r)?, read_register(r)?);
276        let signature_a_minus = r.octet_string()?;
277        Ok(Self {
278            server_id,
279            sec_index,
280            status,
281            a_plus,
282            r1,
283            r4,
284            signature_a_plus,
285            a_minus,
286            r2,
287            r3,
288            signature_a_minus,
289        })
290    }
291
292    /// Write the entry, every register in its fixed wire width.
293    pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
294        w.list(23)?;
295        w.octet_string(self.server_id.as_bytes())?;
296        self.sec_index.write(w)?;
297        w.unsigned(self.status, 8)?;
298        for q in [self.a_plus, self.r1, self.r4] {
299            write_register(w, q)?;
300        }
301        w.octet_string(self.signature_a_plus)?;
302        for q in [self.a_minus, self.r2, self.r3] {
303            write_register(w, q)?;
304        }
305        w.octet_string(self.signature_a_minus)
306    }
307}