1use super::SelectiveAccess;
4use crate::axdr::{Data, DateTime, Seq};
5use crate::codec::{Encode, Error, ErrorKind, Result, Writer};
6use crate::obis::Obis;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct CaptureObject {
11 pub class_id: u16,
13 pub logical_name: Obis,
15 pub attribute_index: i8,
17 pub data_index: u16,
19}
20
21impl CaptureObject {
22 #[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 #[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct RangeDescriptor {
63 pub restricting_object: CaptureObject,
65 pub from: DateTime,
67 pub to: DateTime,
69}
70
71impl RangeDescriptor {
72 #[must_use]
74 pub const fn by_clock(from: DateTime, to: DateTime) -> Self {
75 Self { restricting_object: CaptureObject::clock(), from, to }
76 }
77
78 pub fn to_selective_access<'b>(&self, buf: &'b mut [u8]) -> Result<SelectiveAccess<'b>> {
80 let mut w = crate::codec::SliceWriter::new(buf);
81 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct EntryDescriptor {
99 pub from_entry: u32,
101 pub to_entry: u32,
103 pub from_value: u16,
105 pub to_value: u16,
107}
108
109impl EntryDescriptor {
110 #[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 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
134pub const MAX_COLUMNS: usize = 32;
139
140fn 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#[derive(Debug, Clone, Copy)]
193pub struct ProfileBuffer<'a> {
194 rows: Seq<'a>,
195}
196
197impl<'a> ProfileBuffer<'a> {
198 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 #[must_use]
206 pub const fn len(&self) -> usize {
207 self.rows.len()
208 }
209
210 #[must_use]
212 pub const fn is_empty(&self) -> bool {
213 self.rows.is_empty()
214 }
215
216 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 pub fn for_each_cell(
240 &self,
241 columns: usize,
242 mut f: impl FnMut(usize, usize, Data<'a>) -> Result<()>,
243 ) -> Result<()> {
244 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 let slot = previous.get_mut(col).ok_or_else(|| Error::new(ErrorKind::Unsupported, 0))?;
261 let value = if matches!(cell, Data::Null) {
262 slot.ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?
264 } else if cell.tag().is_delta() {
265 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 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 #[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 let raw = [
354 0x01, 0x02, 0x02, 0x02, 0x11, 0x07, 0x12, 0x00, 0x64, 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 let raw = [
380 0x01, 0x02, 0x02, 0x02, 0x11, 0x07, 0x12, 0x00, 0x64, 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 #[test]
404 fn delta_columns_are_expanded_against_the_previous_row() {
405 let raw = [
408 0x01, 0x03, 0x02, 0x01, 0x06, 0x00, 0x0F, 0x42, 0x40, 0x02, 0x01, 0x21, 0x00, 0x00, 0x00, 0xFA, 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 #[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 #[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, 0x02, 0x01, 0x06, 0x00, 0x0F, 0x42, 0x40, 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 #[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}