Skip to main content

sml_kit/
profile.rs

1//! A packed profile: `SML_GetProfilePack.Res` (TR-03109-1 Anlage IV), the answer to a
2//! [`Body::GetProfilePackRequest`](crate::Body::GetProfilePackRequest).
3//!
4//! Where `GetProfileList.Res` sends one message per period, each value naming itself, the
5//! packed form names the columns once in a header (OBIS code, unit, scaler) and then sends
6//! rows of bare values. [`GetProfilePackResponse::quantity`] puts the two back together:
7//!
8//! ```
9//! use sml_kit::{
10//!     GetProfilePackResponse, Obis, ProfileColumn, ProfileColumns, ProfilePeriod,
11//!     ProfilePeriods, ProfileValue, ProfileValues, ServerId, SmlValue, Time, Unit,
12//! };
13//!
14//! let columns = [ProfileColumn { obis: Obis::ENERGY_IMPORT, unit: Unit::WH, scaler: -1 }];
15//! let values = [ProfileValue { value: SmlValue::Uint(12_345), value_signature: None }];
16//! let periods = [ProfilePeriod {
17//!     val_time: Time::SecIndex(900),
18//!     status: 0,
19//!     values: ProfileValues::from_slice(&values),
20//!     period_signature: None,
21//! }];
22//! let profile = GetProfilePackResponse {
23//!     server_id: ServerId::new(b"\x0a\x01EMH\x00\x00\x41\xf0\x45"),
24//!     act_time: Time::SecIndex(1000),
25//!     reg_period: 900,
26//!     tree_path: sml_kit::NameList::from_slice(&[]),
27//!     columns: ProfileColumns::from_slice(&columns),
28//!     periods: ProfilePeriods::from_slice(&periods),
29//!     rawdata: None,
30//!     profile_signature: None,
31//! };
32//! let first = profile.periods.iter().next().unwrap().unwrap();
33//! assert_eq!(profile.quantity(&first, Obis::ENERGY_IMPORT).unwrap().to_string(), "1234.5 Wh");
34//! ```
35
36use crate::seq::{Ctx, Element, Seq, sealed};
37use crate::tl::{Reader, Writer};
38use crate::value::{Quantity, SmlValue, Time, Unit};
39use crate::{Error, NameList, Obis, Result, ServerId};
40
41/// The column headers of a packed profile.
42pub type ProfileColumns<'a> = Seq<'a, ProfileColumn>;
43/// The rows of a packed profile.
44pub type ProfilePeriods<'a> = Seq<'a, ProfilePeriod<'a>>;
45/// The values of one row, in column order.
46pub type ProfileValues<'a> = Seq<'a, ProfileValue<'a>>;
47
48/// `SML_GetProfilePack.Res`: a profile as one header and many rows.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub struct GetProfilePackResponse<'a> {
51    /// The device that answered.
52    pub server_id: ServerId<'a>,
53    /// The device's time when it answered.
54    pub act_time: Time,
55    /// The registration period in seconds (0: event driven).
56    pub reg_period: u32,
57    /// The profile.
58    pub tree_path: NameList<'a>,
59    /// What each column holds (`header_List`).
60    pub columns: ProfileColumns<'a>,
61    /// The rows (`period_List`).
62    pub periods: ProfilePeriods<'a>,
63    /// Raw data, when asked for.
64    pub rawdata: Option<&'a [u8]>,
65    /// A signature over the profile, when the device signs. **Not verified** by this crate.
66    pub profile_signature: Option<&'a [u8]>,
67}
68
69impl<'a> GetProfilePackResponse<'a> {
70    /// The value of column `obis` in `period`, scaled by the column's header, when it is
71    /// numeric. `None` when no column has that name or a header or value cannot be read.
72    /// (A decoded response has one value per column; a built one is not checked, and a
73    /// short row gives `None` for the missing columns.)
74    pub fn quantity(&self, period: &ProfilePeriod<'_>, obis: Obis) -> Option<Quantity> {
75        let index = self.columns.iter().position(|c| c.is_ok_and(|c| c.obis == obis))?;
76        let column = self.columns.iter().nth(index)?.ok()?;
77        let value = period.values.iter().nth(index)?.ok()?;
78        let mantissa = match value.value {
79            SmlValue::Int(v) => i128::from(v),
80            SmlValue::Uint(v) => i128::from(v),
81            SmlValue::Bool(_) | SmlValue::Bytes(_) | SmlValue::Time(_) => return None,
82        };
83        Some(Quantity { mantissa, exponent: column.scaler, unit: Some(column.unit) })
84    }
85
86    /// Reads the response and checks every row against the header: TR-03109-1 Anlage IV
87    /// (77) requires one value per column, so a row of another length is
88    /// [`Error::ListLength`], not a table with a hole in it.
89    pub(crate) fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
90        r.list(8)?;
91        let response = Self {
92            server_id: ServerId::new(r.octet_string()?),
93            act_time: Time::read(r, ctx.options)?,
94            reg_period: u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?,
95            tree_path: Seq::read(r, ctx)?,
96            columns: Seq::read(r, ctx)?,
97            periods: Seq::read(r, ctx)?,
98            rawdata: r.opt_octet_string()?,
99            profile_signature: r.opt_octet_string()?,
100        };
101        for period in &response.periods {
102            let found = period?.values.len();
103            if found != response.columns.len() {
104                return Err(Error::ListLength { expected: response.columns.len(), found });
105            }
106        }
107        Ok(response)
108    }
109
110    pub(crate) fn write(&self, w: &mut Writer<'_>) -> Result<()> {
111        w.list(8)?;
112        w.octet_string(self.server_id.as_bytes())?;
113        self.act_time.write(w)?;
114        w.unsigned(u64::from(self.reg_period), 4)?;
115        self.tree_path.write(w)?;
116        self.columns.write(w)?;
117        self.periods.write(w)?;
118        w.opt_octet_string(self.rawdata)?;
119        w.opt_octet_string(self.profile_signature)
120    }
121}
122
123/// `SML_ProfObjHeaderEntry`: what one column of a packed profile holds.
124#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
125pub struct ProfileColumn {
126    /// What the column's values are.
127    pub obis: Obis,
128    /// Their unit.
129    pub unit: Unit,
130    /// Their decimal exponent.
131    pub scaler: i8,
132}
133
134/// `SML_ProfObjPeriodEntry`: one row of a packed profile.
135#[derive(Clone, Copy, Debug, PartialEq, Eq)]
136pub struct ProfilePeriod<'a> {
137    /// The period's time.
138    pub val_time: Time,
139    /// Status bits of the period.
140    pub status: u64,
141    /// One value per column, in the header's order.
142    pub values: ProfileValues<'a>,
143    /// A signature over the period, when the device signs. **Not verified** by this crate.
144    pub period_signature: Option<&'a [u8]>,
145}
146
147/// `SML_ValueEntry`: one value of a row; its unit and scaler are in the column header.
148#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
149pub struct ProfileValue<'a> {
150    /// The value.
151    pub value: SmlValue<'a>,
152    /// A signature over the value, when the device signs. **Not verified** by this crate.
153    pub value_signature: Option<&'a [u8]>,
154}
155
156impl sealed::Sealed for ProfileColumn {}
157impl sealed::Sealed for ProfilePeriod<'_> {}
158impl sealed::Sealed for ProfileValue<'_> {}
159
160impl<'a> Element<'a> for ProfileColumn {
161    fn read(r: &mut Reader<'a>, _: Ctx) -> Result<Self> {
162        r.list(3)?;
163        let obis = Obis::from_bytes(r.octet_string()?)?;
164        let unit = Unit(u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?);
165        let scaler = i8::try_from(r.integer()?).map_err(|_| Error::ValueOutOfRange)?;
166        Ok(Self { obis, unit, scaler })
167    }
168
169    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
170        w.list(3)?;
171        w.octet_string(&self.obis.0)?;
172        w.unsigned(u64::from(self.unit.0), 1)?;
173        w.integer(i64::from(self.scaler), 1)
174    }
175}
176
177impl<'a> Element<'a> for ProfilePeriod<'a> {
178    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
179        r.list(4)?;
180        Ok(Self {
181            val_time: Time::read(r, ctx.options)?,
182            status: r.unsigned()?,
183            values: Seq::read(r, ctx)?,
184            period_signature: r.opt_octet_string()?,
185        })
186    }
187
188    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
189        w.list(4)?;
190        self.val_time.write(w)?;
191        w.unsigned(self.status, 8)?;
192        self.values.write(w)?;
193        w.opt_octet_string(self.period_signature)
194    }
195}
196
197impl<'a> Element<'a> for ProfileValue<'a> {
198    fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
199        r.list(2)?;
200        let value = SmlValue::read(r, ctx.options)?.0;
201        Ok(Self { value, value_signature: r.opt_octet_string()? })
202    }
203
204    fn write(&self, w: &mut Writer<'_>) -> Result<()> {
205        w.list(2)?;
206        self.value.write(w)?;
207        w.opt_octet_string(self.value_signature)
208    }
209}