Skip to main content

dlms_cosem_kit/cosem/
profile.rs

1//! Profile generic: selective access and typed rows.
2
3use super::SelectiveAccess;
4use crate::axdr::{Data, DateTime, Seq};
5use crate::codec::{Encode, Error, ErrorKind, Result, Writer};
6use crate::obis::Obis;
7
8/// Which capture object a range selection is measured against.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct CaptureObject {
11    /// The class of the captured object.
12    pub class_id: u16,
13    /// Its logical name.
14    pub logical_name: Obis,
15    /// Which of its attributes was captured.
16    pub attribute_index: i8,
17    /// Which element of a structured attribute, or 0 for the whole thing.
18    pub data_index: u16,
19}
20
21impl CaptureObject {
22    /// A capture object.
23    #[must_use]
24    pub const fn new(class_id: u16, logical_name: Obis, attribute_index: i8, data_index: u16) -> Self {
25        Self { class_id, logical_name, attribute_index, data_index }
26    }
27
28    /// The clock's time attribute, which is what nearly every profile sorts by.
29    #[must_use]
30    pub const fn clock() -> Self {
31        Self::new(8, Obis::new(0, 0, 1, 0, 0, 255), 2, 0)
32    }
33
34    /// Decode one `capture_object_definition` structure.
35    pub fn from_data(d: &Data<'_>) -> Result<Self> {
36        let s = d.as_structure().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?;
37        let bad = || Error::new(ErrorKind::InvalidValue, 0);
38        Ok(Self {
39            class_id: u16::try_from(s.get(0)?.as_u64().ok_or_else(bad)?).map_err(|_| bad())?,
40            logical_name: s.get(1)?.as_obis().ok_or_else(bad)?,
41            attribute_index: i8::try_from(s.get(2)?.as_i64().ok_or_else(bad)?).map_err(|_| bad())?,
42            data_index: u16::try_from(s.get(3)?.as_u64().ok_or_else(bad)?).map_err(|_| bad())?,
43        })
44    }
45}
46
47impl Encode for CaptureObject {
48    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
49        w.write_bytes(&[0x02, 0x04])?;
50        w.write_bytes(&[0x12])?;
51        w.write_u16(self.class_id)?;
52        w.write_bytes(&[0x09, 0x06])?;
53        w.write_bytes(self.logical_name.as_bytes())?;
54        w.write_bytes(&[0x0F, self.attribute_index as u8])?;
55        w.write_bytes(&[0x12])?;
56        w.write_u16(self.data_index)
57    }
58}
59
60/// Read the rows whose sort value falls in a range — selector 1.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct RangeDescriptor {
63    /// Which captured value the range applies to. Almost always the clock.
64    pub restricting_object: CaptureObject,
65    /// The first value to include.
66    pub from: DateTime,
67    /// The last value to include.
68    pub to: DateTime,
69}
70
71impl RangeDescriptor {
72    /// A range over the clock, which is what a load-profile read wants.
73    #[must_use]
74    pub const fn by_clock(from: DateTime, to: DateTime) -> Self {
75        Self { restricting_object: CaptureObject::clock(), from, to }
76    }
77
78    /// The selective access descriptor this range becomes.
79    pub fn to_selective_access<'b>(&self, buf: &'b mut [u8]) -> Result<SelectiveAccess<'b>> {
80        let mut w = crate::codec::SliceWriter::new(buf);
81        // structure { restricting_object, from, to, selected_values }
82        w.write_bytes(&[0x02, 0x04])?;
83        self.restricting_object.encode(&mut w)?;
84        w.write_bytes(&[0x09, 0x0C])?;
85        w.write_bytes(&self.from.to_bytes())?;
86        w.write_bytes(&[0x09, 0x0C])?;
87        w.write_bytes(&self.to.to_bytes())?;
88        // An empty array selects every captured column.
89        w.write_bytes(&[0x01, 0x00])?;
90        let n = w.written();
91        let parameters = Data::from_bytes_in(&buf[..n])?;
92        Ok(SelectiveAccess { selector: 1, parameters })
93    }
94}
95
96/// Read rows by their position in the buffer — selector 2.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct EntryDescriptor {
99    /// The first entry, counting from one.
100    pub from_entry: u32,
101    /// The last entry; zero means "to the end".
102    pub to_entry: u32,
103    /// The first column, counting from one.
104    pub from_value: u16,
105    /// The last column; zero means "every column".
106    pub to_value: u16,
107}
108
109impl EntryDescriptor {
110    /// Every column of a range of entries.
111    #[must_use]
112    pub const fn entries(from: u32, to: u32) -> Self {
113        Self { from_entry: from, to_entry: to, from_value: 1, to_value: 0 }
114    }
115
116    /// The selective access descriptor this becomes.
117    pub fn to_selective_access<'b>(&self, buf: &'b mut [u8]) -> Result<SelectiveAccess<'b>> {
118        let mut w = crate::codec::SliceWriter::new(buf);
119        w.write_bytes(&[0x02, 0x04])?;
120        w.write_u8(0x06)?;
121        w.write_u32(self.from_entry)?;
122        w.write_u8(0x06)?;
123        w.write_u32(self.to_entry)?;
124        w.write_u8(0x12)?;
125        w.write_u16(self.from_value)?;
126        w.write_u8(0x12)?;
127        w.write_u16(self.to_value)?;
128        let n = w.written();
129        let parameters = Data::from_bytes_in(&buf[..n])?;
130        Ok(SelectiveAccess { selector: 2, parameters })
131    }
132}
133
134/// The most capture objects [`ProfileBuffer::for_each_cell`] can undo compression for.
135///
136/// The previous row is held in a fixed array so the decoder needs no allocator. No
137/// profile in the Blue Book comes close to this.
138pub const MAX_COLUMNS: usize = 32;
139
140/// Apply a delta to the previous value in the same column.
141///
142/// The six delta types of Green Book edition 10 carry the *difference* from the previous
143/// row's value in the same column, which is what makes a load profile compress: a
144/// register that climbs by a few hundred each interval sends a byte or two instead of
145/// four. Expanding one therefore needs the neighbour it is relative to, and that is why
146/// it happens here rather than in [`Data`] — a `Data` that knew its neighbours would be
147/// a different type.
148///
149/// Two rules keep this honest:
150///
151/// * **The delta's width decides the base type**, and the previous value must already be
152///   that type. A `delta-long-unsigned` after a `double-long-unsigned` is a column whose
153///   type changed mid-buffer, which is a meter fault or a misread row — either way, not
154///   something to paper over by widening silently.
155/// * **The arithmetic wraps in the base type**, because that is where the meter's own
156///   register wraps. An expansion that saturated would turn a register rollover into a
157///   plateau, which reads as a meter that stopped counting.
158///
159/// The signed delta types add signed differences; the unsigned ones add unsigned
160/// increments, which is what their names say and what makes them worth having — a
161/// quantity known not to decrease does not need a sign bit. That reading is derived
162/// rather than read from the normative text, whose relevant clause is not in the
163/// excerpts this crate was built from.
164fn apply_delta(previous: Data<'_>, delta: Data<'_>) -> Option<Data<'static>> {
165    Some(match (previous, delta) {
166        (Data::Integer(base), Data::DeltaInteger(d)) => Data::Integer(base.wrapping_add(d)),
167        (Data::Long(base), Data::DeltaLong(d)) => Data::Long(base.wrapping_add(d)),
168        (Data::DoubleLong(base), Data::DeltaDoubleLong(d)) => Data::DoubleLong(base.wrapping_add(d)),
169        (Data::Unsigned(base), Data::DeltaUnsigned(d)) => Data::Unsigned(base.wrapping_add(d)),
170        (Data::LongUnsigned(base), Data::DeltaLongUnsigned(d)) => Data::LongUnsigned(base.wrapping_add(d)),
171        (Data::DoubleLongUnsigned(base), Data::DeltaDoubleLongUnsigned(d)) => {
172            Data::DoubleLongUnsigned(base.wrapping_add(d))
173        }
174        _ => return None,
175    })
176}
177
178/// A decoded profile buffer, with the columns it was captured against.
179///
180/// Rows are iterated out of the borrowed buffer. Both of the compressions a profile
181/// buffer uses are undone here, because a caller that has to remember the previous row is
182/// a caller that will forget:
183///
184/// * **Null-data compression** — a column that repeats the previous row's value is sent
185///   as `null-data`, or, for a run at the end of a row, left out by making the row
186///   shorter.
187/// * **Delta encoding** — a column sends the *difference* from the previous row
188///   `[GB Ed 10 changes]`, in one of the six delta types.
189///
190/// A caller that skipped either gets numbers rather than an error: zeroes where a
191/// reading repeated, and differences where readings were meant.
192#[derive(Debug, Clone, Copy)]
193pub struct ProfileBuffer<'a> {
194    rows: Seq<'a>,
195}
196
197impl<'a> ProfileBuffer<'a> {
198    /// Wrap the array a `buffer` attribute returned.
199    pub fn new(buffer: &Data<'a>) -> Result<Self> {
200        let rows = buffer.as_array().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?;
201        Ok(Self { rows })
202    }
203
204    /// How many rows.
205    #[must_use]
206    pub const fn len(&self) -> usize {
207        self.rows.len()
208    }
209
210    /// True when the buffer is empty.
211    #[must_use]
212    pub const fn is_empty(&self) -> bool {
213        self.rows.is_empty()
214    }
215
216    /// Iterate the rows as they arrived, without undoing compression.
217    pub fn raw_rows(&self) -> impl Iterator<Item = Result<Seq<'a>>> + 'a {
218        self.rows.iter().map(|row| {
219            row.and_then(|r| r.as_structure().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0)))
220        })
221    }
222
223    /// Visit every cell with its row and column, undoing null-data compression against
224    /// the previous row.
225    ///
226    /// `columns` is how many capture objects the profile has. Three compressions are
227    /// undone: a column whose value repeats the previous row is sent as `null-data`; a
228    /// run of repeated columns at the *end* of a row is sent by making the row shorter;
229    /// and a column may send a **delta** from the previous row rather than a value. The
230    /// visitor therefore sees exactly `columns` cells for every row, each an absolute
231    /// value — which is the point.
232    ///
233    /// # Errors
234    /// An oversized row returns [`ErrorKind::InvalidValue`] before its first callback.
235    /// Earlier rows may already have been visited. Also fails when `columns` exceeds
236    /// [`MAX_COLUMNS`]; when a row is not a structure; when the
237    /// first row omits a value or sends a delta and so has nothing to be relative to; or
238    /// when a delta's base type does not match the value it follows.
239    pub fn for_each_cell(
240        &self,
241        columns: usize,
242        mut f: impl FnMut(usize, usize, Data<'a>) -> Result<()>,
243    ) -> Result<()> {
244        // The previous row's values. Stored as `Data` because it borrows the same
245        // buffer the rows do and copying it costs nothing.
246        let mut previous: [Option<Data<'a>>; MAX_COLUMNS] = [None; MAX_COLUMNS];
247        if columns > previous.len() {
248            return Err(Error::new(ErrorKind::Unsupported, 0));
249        }
250        for (row_index, row) in self.raw_rows().enumerate() {
251            let row = row?;
252            if row.len() > columns {
253                return Err(Error::new(ErrorKind::InvalidValue, 0));
254            }
255            for (col, cell) in row.iter().enumerate() {
256                let cell = cell?;
257                // `col < columns <= previous.len()` holds, but saying so with `get_mut`
258                // is what keeps the bound out of the generated code as a panic path
259                // rather than in it.
260                let slot = previous.get_mut(col).ok_or_else(|| Error::new(ErrorKind::Unsupported, 0))?;
261                let value = if matches!(cell, Data::Null) {
262                    // Repeat: this column is unchanged from the previous row.
263                    slot.ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?
264                } else if cell.tag().is_delta() {
265                    // Relative: expand against the previous row's value in this column.
266                    // A delta in the first row has nothing to be relative to, and a
267                    // delta whose width disagrees with the base is a column whose type
268                    // changed — both are refused rather than guessed at.
269                    let base = slot.ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?;
270                    apply_delta(base, cell).ok_or_else(|| Error::new(ErrorKind::TypeMismatch, 0))?
271                } else {
272                    cell
273                };
274                *slot = Some(value);
275                f(row_index, col, value)?;
276            }
277            // A short row means the columns it left out are unchanged.
278            for col in row.len()..columns {
279                let value = previous
280                    .get(col)
281                    .copied()
282                    .flatten()
283                    .ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?;
284                f(row_index, col, value)?;
285            }
286        }
287        Ok(())
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294    use crate::codec::Decode;
295
296    /// 002-bounded-profile-reads/SR-001
297    #[test]
298    fn surplus_columns_are_rejected_before_visiting_the_row() {
299        let bytes = [1, 1, 2, 2, 17, 10, 17, 20];
300        let data = Data::from_bytes(&bytes).unwrap();
301        let profile = ProfileBuffer::new(&data).unwrap();
302        for columns in [0, 1] {
303            let mut visits = 0;
304            let error = profile
305                .for_each_cell(columns, |_, _, _| {
306                    visits += 1;
307                    Ok(())
308                })
309                .unwrap_err();
310            assert_eq!((error.kind, visits), (ErrorKind::InvalidValue, 0));
311        }
312        let mut values = [0; 2];
313        profile
314            .for_each_cell(2, |_, col, value| {
315                values[col] = value.as_u64().unwrap();
316                Ok(())
317            })
318            .unwrap();
319        assert_eq!(values, [10, 20]);
320    }
321
322    #[test]
323    fn a_range_descriptor_selects_by_clock() {
324        let from = DateTime::from_civil(2025, 1, 1, 0, 0, 0, 60).unwrap();
325        let to = DateTime::from_civil(2025, 1, 2, 0, 0, 0, 60).unwrap();
326        let mut buf = [0u8; 64];
327        let sa = RangeDescriptor::by_clock(from, to).to_selective_access(&mut buf).unwrap();
328        assert_eq!(sa.selector, 1);
329        let s = sa.parameters.as_structure().expect("a structure of four fields");
330        assert_eq!(s.len(), 4);
331        let restricting = s.get(0).unwrap();
332        assert_eq!(restricting.as_structure().unwrap().len(), 4);
333        assert_eq!(
334            CaptureObject::from_data(&restricting).unwrap().logical_name,
335            Obis::new(0, 0, 1, 0, 0, 255)
336        );
337    }
338
339    #[test]
340    fn an_entry_descriptor_selects_by_position() {
341        let mut buf = [0u8; 32];
342        let sa = EntryDescriptor::entries(1, 10).to_selective_access(&mut buf).unwrap();
343        assert_eq!(sa.selector, 2);
344        let s = sa.parameters.as_structure().unwrap();
345        assert_eq!(s.get(0).unwrap().as_u64(), Some(1));
346        assert_eq!(s.get(1).unwrap().as_u64(), Some(10));
347        assert_eq!(s.get(3).unwrap().as_u64(), Some(0), "zero means every column");
348    }
349
350    #[test]
351    fn null_data_compression_is_undone_against_the_previous_row() {
352        // Two columns; the second row repeats the first column.
353        let raw = [
354            0x01, 0x02, //
355            0x02, 0x02, 0x11, 0x07, 0x12, 0x00, 0x64, //
356            0x02, 0x02, 0x00, 0x12, 0x00, 0xC8,
357        ];
358        let d = Data::from_bytes(&raw).unwrap();
359        let buffer = ProfileBuffer::new(&d).unwrap();
360        assert_eq!(buffer.len(), 2);
361        let mut cells = alloc::vec::Vec::new();
362        buffer
363            .for_each_cell(2, |row, col, v| {
364                cells.push((row, col, v.as_i64()));
365                Ok(())
366            })
367            .unwrap();
368        assert_eq!(cells[0], (0, 0, Some(7)));
369        assert_eq!(cells[1], (0, 1, Some(100)));
370        assert_eq!(cells[2], (1, 0, Some(7)), "the repeated column carried forward");
371        assert_eq!(cells[3], (1, 1, Some(200)));
372    }
373
374    #[test]
375    fn a_short_row_repeats_the_columns_it_left_out() {
376        // Two columns. The second row carries only the first, so the second column is
377        // unchanged — the other half of null-data compression, and the half a caller
378        // notices only when a reading silently goes missing.
379        let raw = [
380            0x01, 0x02, //
381            0x02, 0x02, 0x11, 0x07, 0x12, 0x00, 0x64, //
382            0x02, 0x01, 0x11, 0x09,
383        ];
384        let d = Data::from_bytes(&raw).unwrap();
385        let buffer = ProfileBuffer::new(&d).unwrap();
386        let mut cells = alloc::vec::Vec::new();
387        buffer
388            .for_each_cell(2, |row, col, v| {
389                cells.push((row, col, v.as_i64()));
390                Ok(())
391            })
392            .unwrap();
393        assert_eq!(cells.len(), 4, "every row yields every column");
394        assert_eq!(cells[2], (1, 0, Some(9)));
395        assert_eq!(cells[3], (1, 1, Some(100)), "the column the row left out carried forward");
396    }
397
398    /// Delta encoding: a column sends the difference from the previous row.
399    ///
400    /// A caller that skipped this gets no error — it gets *differences where readings
401    /// were meant*, which for a rising register looks like a meter that suddenly reads
402    /// almost nothing.
403    #[test]
404    fn delta_columns_are_expanded_against_the_previous_row() {
405        // One column. Row 0 is an absolute double-long-unsigned 1 000 000; rows 1 and 2
406        // send delta-double-long-unsigned increments of 250 and 300.
407        let raw = [
408            0x01, 0x03, //
409            0x02, 0x01, 0x06, 0x00, 0x0F, 0x42, 0x40, //
410            0x02, 0x01, 0x21, 0x00, 0x00, 0x00, 0xFA, //
411            0x02, 0x01, 0x21, 0x00, 0x00, 0x01, 0x2C,
412        ];
413        let d = Data::from_bytes(&raw).unwrap();
414        let buffer = ProfileBuffer::new(&d).unwrap();
415        let mut values = alloc::vec::Vec::new();
416        buffer
417            .for_each_cell(1, |_, _, v| {
418                values.push(v.as_u64());
419                Ok(())
420            })
421            .unwrap();
422        assert_eq!(values, [Some(1_000_000), Some(1_000_250), Some(1_000_550)]);
423    }
424
425    /// A signed delta may go down, and the expansion wraps where the meter's register
426    /// wraps rather than saturating — a rollover that saturated would read as a meter
427    /// that stopped counting.
428    #[test]
429    fn a_signed_delta_may_decrease_and_the_arithmetic_wraps() {
430        assert_eq!(apply_delta(Data::Long(100), Data::DeltaLong(-30)), Some(Data::Long(70)));
431        assert_eq!(
432            apply_delta(Data::DoubleLongUnsigned(u32::MAX), Data::DeltaDoubleLongUnsigned(2)),
433            Some(Data::DoubleLongUnsigned(1)),
434            "a register rollover is a rollover, not a ceiling"
435        );
436    }
437
438    /// A delta whose width disagrees with the value it follows is a column whose type
439    /// changed mid-buffer. Widening it silently would hand back a number nobody sent.
440    #[test]
441    fn a_delta_of_the_wrong_width_is_refused_rather_than_widened() {
442        assert_eq!(apply_delta(Data::DoubleLongUnsigned(1000), Data::DeltaLongUnsigned(5)), None);
443        assert_eq!(apply_delta(Data::Unsigned(1), Data::DeltaInteger(1)), None);
444
445        let raw = [
446            0x01, 0x02, //
447            0x02, 0x01, 0x06, 0x00, 0x0F, 0x42, 0x40, //
448            0x02, 0x01, 0x20, 0x00, 0xFA,
449        ];
450        let d = Data::from_bytes(&raw).unwrap();
451        let buffer = ProfileBuffer::new(&d).unwrap();
452        assert_eq!(buffer.for_each_cell(1, |_, _, _| Ok(())).unwrap_err().kind, ErrorKind::TypeMismatch);
453    }
454
455    /// A delta in the first row is relative to nothing.
456    #[test]
457    fn a_leading_delta_is_refused_like_a_leading_null() {
458        let raw = [0x01, 0x01, 0x02, 0x01, 0x21, 0x00, 0x00, 0x00, 0x05];
459        let d = Data::from_bytes(&raw).unwrap();
460        let buffer = ProfileBuffer::new(&d).unwrap();
461        assert!(buffer.for_each_cell(1, |_, _, _| Ok(())).is_err());
462    }
463
464    #[test]
465    fn a_leading_null_has_nothing_to_repeat_and_is_refused() {
466        let raw = [0x01, 0x01, 0x02, 0x01, 0x00];
467        let d = Data::from_bytes(&raw).unwrap();
468        let buffer = ProfileBuffer::new(&d).unwrap();
469        assert!(buffer.for_each_cell(1, |_, _, _| Ok(())).is_err());
470    }
471}