Skip to main content

mbus_kit/
profile.rs

1//! Compact profiles (EN 13757-3:2018 Annex F.2, OMS Vol. 2 Annex G): a series of values
2//! in one record, e.g. a heat cost allocator's monthly history.
3//!
4//! ```text
5//! DIF(…D)  DIFE…  VIF  VIFE…  1F|13|1E   LVAR  spacing-control  spacing-value  element…
6//! ```
7//!
8//! The profile belongs to a **base value** (the record with the same storage, tariff,
9//! subunit and VIF without the profile VIFE) and a **base time** (the date record of that
10//! storage). Element *k* (0-based) lies *k* + 1 spacings after the base time (`1F`, `1E`)
11//! or before it (`13`): [`Profile::offset`], [`Profile::date`]. [`Profile::values`] turns
12//! the elements into readings: absolute elements are the readings; increments accumulate
13//! from the base value.
14
15use core::fmt;
16
17use crate::record::DataField;
18use crate::time::Date;
19use crate::value::{self, Unit, Value};
20use crate::vif::Direction;
21
22/// How the elements relate to the readings (spacing control bits 7–6).
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
24pub enum Increment {
25    /// Each element is a reading (signed).
26    Absolute,
27    /// Each element is a positive increment (unsigned).
28    Positive,
29    /// Each element is a negative increment (unsigned).
30    Negative,
31    /// Each element is the younger minus the older reading (signed).
32    Difference,
33}
34
35/// The time between elements (spacing value with its unit).
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub enum Spacing {
38    /// `n` seconds, minutes, hours or days.
39    Every(u8, Unit),
40    /// Half a month.
41    HalfMonth,
42    /// 1, 3 or 6 months.
43    Months(u8),
44    /// Not spaced in time: the elements are array columns.
45    Columns,
46    /// A reserved spacing value.
47    Reserved(u8),
48}
49
50/// How far an element lies from the profile's base time; negative is earlier.
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
52pub enum Offset {
53    /// Seconds (spacing in seconds, minutes, hours or days).
54    Seconds(i64),
55    /// Whole months.
56    Months(i32),
57    /// Half months.
58    HalfMonths(i32),
59}
60
61/// A compact profile record's payload.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct Profile<'a> {
64    /// Forward, inverse, or with register numbers.
65    pub direction: Direction,
66    /// What the elements mean.
67    pub increment: Increment,
68    /// The time between elements.
69    pub spacing: Spacing,
70    /// How each element is coded.
71    pub element: DataField,
72    elements: &'a [u8],
73}
74
75impl<'a> Profile<'a> {
76    /// Parse the LVAR payload of a profile record. `None` for a malformed one.
77    pub(crate) fn parse(direction: Direction, payload: &'a [u8]) -> Option<Self> {
78        let (&[control, value], elements) = payload.split_first_chunk::<2>()?;
79        let element = DataField::from_nibble(control & 0x0F);
80        let size = element.size()?;
81        if size == 0 || elements.len() % size != 0 {
82            return None;
83        }
84        let unit = Unit::duration((control >> 4) & 0x03);
85        let spacing = match (value, (control >> 4) & 0x03) {
86            (0, _) => Spacing::Columns,
87            (1..=250, _) => Spacing::Every(value, unit),
88            (253, 3) => Spacing::HalfMonth,
89            (254, 3) => Spacing::Months(1),
90            (254, 2) => Spacing::Months(3),
91            (254, 1) => Spacing::Months(6),
92            (v, _) => Spacing::Reserved(v),
93        };
94        let increment = match control >> 6 {
95            0 => Increment::Absolute,
96            1 => Increment::Positive,
97            2 => Increment::Negative,
98            _ => Increment::Difference,
99        };
100        Some(Self { direction, increment, spacing, element, elements })
101    }
102
103    /// The number of elements.
104    pub fn len(&self) -> usize {
105        self.element.size().and_then(|s| self.elements.len().checked_div(s)).unwrap_or(0)
106    }
107
108    /// Whether the profile has no elements.
109    pub fn is_empty(&self) -> bool {
110        self.len() == 0
111    }
112
113    /// Element `k` (0-based) as transmitted, `None` if it is out of range or holds the
114    /// "illegal" preset value (unused or overflowed).
115    pub fn element(&self, k: usize) -> Option<i128> {
116        let size = self.element.size()?;
117        let start = k.checked_mul(size)?;
118        let bytes = self.elements.get(start..start.checked_add(size)?)?;
119        let signed = matches!(self.increment, Increment::Absolute | Increment::Difference);
120        match self.element {
121            DataField::Int(_) if signed => {
122                let v = i128::from(value::le_signed(bytes));
123                (v != -(1i128 << (8 * size - 1))).then_some(v)
124            }
125            DataField::Int(_) => {
126                let v = i128::from(value::le_unsigned(bytes));
127                (v != (1i128 << (8 * size)) - 1).then_some(v)
128            }
129            DataField::Bcd(_) => match value::bcd(bytes) {
130                Value::Bcd(v) => Some(i128::from(v)),
131                _ => None,
132            },
133            _ => None,
134        }
135    }
136
137    /// When element `k` (0-based) was taken, relative to the base time: `k + 1` spacings
138    /// later, or earlier for an inverse profile. `None` for elements that are columns,
139    /// not points in time, a reserved spacing, or `k` out of range.
140    pub fn offset(&self, k: usize) -> Option<Offset> {
141        if k >= self.len() {
142            return None;
143        }
144        let steps = i64::try_from(k).ok()?.checked_add(1)?;
145        let steps = if self.direction == Direction::Inverse { -steps } else { steps };
146        Some(match self.spacing {
147            Spacing::Every(n, unit) => {
148                let seconds = match unit {
149                    Unit::Minutes => 60,
150                    Unit::Hours => 3600,
151                    Unit::Days => 86_400,
152                    _ => 1,
153                };
154                Offset::Seconds(steps.checked_mul(i64::from(n) * seconds)?)
155            }
156            Spacing::Months(n) => Offset::Months(i32::try_from(steps.checked_mul(i64::from(n))?).ok()?),
157            Spacing::HalfMonth => Offset::HalfMonths(i32::try_from(steps).ok()?),
158            Spacing::Columns | Spacing::Reserved(_) => return None,
159        })
160    }
161
162    /// The date of element `k` for a month-spaced profile, from the base record's date
163    /// (month ends kept, OMS Vol. 2 Table G.5). `None` for other spacings.
164    pub fn date(&self, k: usize, base: Date) -> Option<Date> {
165        match self.offset(k)? {
166            Offset::Months(m) => base.add_months(m),
167            _ => None,
168        }
169    }
170
171    /// The readings, element by element, from the base value (in the base record's
172    /// mantissa: apply its unit and exponent). `None` for an illegal element; the series
173    /// continues from the last valid reading.
174    pub fn values(&self, base: i128) -> impl Iterator<Item = Option<i128>> + '_ {
175        let mut acc = base;
176        (0..self.len()).map(move |k| {
177            let e = self.element(k)?;
178            if self.increment == Increment::Absolute {
179                return Some(e);
180            }
181            let delta = if self.increment == Increment::Negative { e.checked_neg()? } else { e };
182            acc = if self.direction == Direction::Inverse {
183                acc.checked_sub(delta)?
184            } else {
185                acc.checked_add(delta)?
186            };
187            Some(acc)
188        })
189    }
190}
191
192impl fmt::Display for Profile<'_> {
193    /// `profile of 4 increments, every month`.
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        let what = match self.increment {
196            Increment::Absolute => "readings",
197            Increment::Positive | Increment::Negative => "increments",
198            Increment::Difference => "differences",
199        };
200        write!(f, "{} {what}", self.len())?;
201        match self.spacing {
202            Spacing::Every(n, unit) => write!(f, ", every {n} {unit}")?,
203            Spacing::HalfMonth => f.write_str(", every half month")?,
204            Spacing::Months(1) => f.write_str(", every month")?,
205            Spacing::Months(n) => write!(f, ", every {n} months")?,
206            Spacing::Columns => f.write_str(", as columns")?,
207            Spacing::Reserved(v) => write!(f, ", spacing {v}")?,
208        }
209        if self.direction == Direction::Inverse {
210            f.write_str(", backwards")?;
211        }
212        Ok(())
213    }
214}