use super::SelectiveAccess;
use crate::axdr::{Data, DateTime, Seq};
use crate::codec::{Encode, Error, ErrorKind, Result, Writer};
use crate::obis::Obis;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CaptureObject {
pub class_id: u16,
pub logical_name: Obis,
pub attribute_index: i8,
pub data_index: u16,
}
impl CaptureObject {
#[must_use]
pub const fn new(class_id: u16, logical_name: Obis, attribute_index: i8, data_index: u16) -> Self {
Self { class_id, logical_name, attribute_index, data_index }
}
#[must_use]
pub const fn clock() -> Self {
Self::new(8, Obis::new(0, 0, 1, 0, 0, 255), 2, 0)
}
pub fn from_data(d: &Data<'_>) -> Result<Self> {
let s = d.as_structure().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?;
let bad = || Error::new(ErrorKind::InvalidValue, 0);
Ok(Self {
class_id: u16::try_from(s.get(0)?.as_u64().ok_or_else(bad)?).map_err(|_| bad())?,
logical_name: s.get(1)?.as_obis().ok_or_else(bad)?,
attribute_index: i8::try_from(s.get(2)?.as_i64().ok_or_else(bad)?).map_err(|_| bad())?,
data_index: u16::try_from(s.get(3)?.as_u64().ok_or_else(bad)?).map_err(|_| bad())?,
})
}
}
impl Encode for CaptureObject {
fn encode(&self, w: &mut dyn Writer) -> Result<()> {
w.write_bytes(&[0x02, 0x04])?;
w.write_bytes(&[0x12])?;
w.write_u16(self.class_id)?;
w.write_bytes(&[0x09, 0x06])?;
w.write_bytes(self.logical_name.as_bytes())?;
w.write_bytes(&[0x0F, self.attribute_index as u8])?;
w.write_bytes(&[0x12])?;
w.write_u16(self.data_index)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RangeDescriptor {
pub restricting_object: CaptureObject,
pub from: DateTime,
pub to: DateTime,
}
impl RangeDescriptor {
#[must_use]
pub const fn by_clock(from: DateTime, to: DateTime) -> Self {
Self { restricting_object: CaptureObject::clock(), from, to }
}
pub fn to_selective_access<'b>(&self, buf: &'b mut [u8]) -> Result<SelectiveAccess<'b>> {
let mut w = crate::codec::SliceWriter::new(buf);
w.write_bytes(&[0x02, 0x04])?;
self.restricting_object.encode(&mut w)?;
w.write_bytes(&[0x09, 0x0C])?;
w.write_bytes(&self.from.to_bytes())?;
w.write_bytes(&[0x09, 0x0C])?;
w.write_bytes(&self.to.to_bytes())?;
w.write_bytes(&[0x01, 0x00])?;
let n = w.written();
let parameters = Data::from_bytes_in(&buf[..n])?;
Ok(SelectiveAccess { selector: 1, parameters })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EntryDescriptor {
pub from_entry: u32,
pub to_entry: u32,
pub from_value: u16,
pub to_value: u16,
}
impl EntryDescriptor {
#[must_use]
pub const fn entries(from: u32, to: u32) -> Self {
Self { from_entry: from, to_entry: to, from_value: 1, to_value: 0 }
}
pub fn to_selective_access<'b>(&self, buf: &'b mut [u8]) -> Result<SelectiveAccess<'b>> {
let mut w = crate::codec::SliceWriter::new(buf);
w.write_bytes(&[0x02, 0x04])?;
w.write_u8(0x06)?;
w.write_u32(self.from_entry)?;
w.write_u8(0x06)?;
w.write_u32(self.to_entry)?;
w.write_u8(0x12)?;
w.write_u16(self.from_value)?;
w.write_u8(0x12)?;
w.write_u16(self.to_value)?;
let n = w.written();
let parameters = Data::from_bytes_in(&buf[..n])?;
Ok(SelectiveAccess { selector: 2, parameters })
}
}
pub const MAX_COLUMNS: usize = 32;
fn apply_delta(previous: Data<'_>, delta: Data<'_>) -> Option<Data<'static>> {
Some(match (previous, delta) {
(Data::Integer(base), Data::DeltaInteger(d)) => Data::Integer(base.wrapping_add(d)),
(Data::Long(base), Data::DeltaLong(d)) => Data::Long(base.wrapping_add(d)),
(Data::DoubleLong(base), Data::DeltaDoubleLong(d)) => Data::DoubleLong(base.wrapping_add(d)),
(Data::Unsigned(base), Data::DeltaUnsigned(d)) => Data::Unsigned(base.wrapping_add(d)),
(Data::LongUnsigned(base), Data::DeltaLongUnsigned(d)) => Data::LongUnsigned(base.wrapping_add(d)),
(Data::DoubleLongUnsigned(base), Data::DeltaDoubleLongUnsigned(d)) => {
Data::DoubleLongUnsigned(base.wrapping_add(d))
}
_ => return None,
})
}
#[derive(Debug, Clone, Copy)]
pub struct ProfileBuffer<'a> {
rows: Seq<'a>,
}
impl<'a> ProfileBuffer<'a> {
pub fn new(buffer: &Data<'a>) -> Result<Self> {
let rows = buffer.as_array().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?;
Ok(Self { rows })
}
#[must_use]
pub const fn len(&self) -> usize {
self.rows.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.rows.is_empty()
}
pub fn raw_rows(&self) -> impl Iterator<Item = Result<Seq<'a>>> + 'a {
self.rows.iter().map(|row| {
row.and_then(|r| r.as_structure().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0)))
})
}
pub fn for_each_cell(
&self,
columns: usize,
mut f: impl FnMut(usize, usize, Data<'a>) -> Result<()>,
) -> Result<()> {
let mut previous: [Option<Data<'a>>; MAX_COLUMNS] = [None; MAX_COLUMNS];
if columns > previous.len() {
return Err(Error::new(ErrorKind::Unsupported, 0));
}
for (row_index, row) in self.raw_rows().enumerate() {
let row = row?;
if row.len() > columns {
return Err(Error::new(ErrorKind::InvalidValue, 0));
}
for (col, cell) in row.iter().enumerate() {
let cell = cell?;
let slot = previous.get_mut(col).ok_or_else(|| Error::new(ErrorKind::Unsupported, 0))?;
let value = if matches!(cell, Data::Null) {
slot.ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?
} else if cell.tag().is_delta() {
let base = slot.ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?;
apply_delta(base, cell).ok_or_else(|| Error::new(ErrorKind::TypeMismatch, 0))?
} else {
cell
};
*slot = Some(value);
f(row_index, col, value)?;
}
for col in row.len()..columns {
let value = previous
.get(col)
.copied()
.flatten()
.ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?;
f(row_index, col, value)?;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codec::Decode;
#[test]
fn surplus_columns_are_rejected_before_visiting_the_row() {
let bytes = [1, 1, 2, 2, 17, 10, 17, 20];
let data = Data::from_bytes(&bytes).unwrap();
let profile = ProfileBuffer::new(&data).unwrap();
for columns in [0, 1] {
let mut visits = 0;
let error = profile
.for_each_cell(columns, |_, _, _| {
visits += 1;
Ok(())
})
.unwrap_err();
assert_eq!((error.kind, visits), (ErrorKind::InvalidValue, 0));
}
let mut values = [0; 2];
profile
.for_each_cell(2, |_, col, value| {
values[col] = value.as_u64().unwrap();
Ok(())
})
.unwrap();
assert_eq!(values, [10, 20]);
}
#[test]
fn a_range_descriptor_selects_by_clock() {
let from = DateTime::from_civil(2025, 1, 1, 0, 0, 0, 60).unwrap();
let to = DateTime::from_civil(2025, 1, 2, 0, 0, 0, 60).unwrap();
let mut buf = [0u8; 64];
let sa = RangeDescriptor::by_clock(from, to).to_selective_access(&mut buf).unwrap();
assert_eq!(sa.selector, 1);
let s = sa.parameters.as_structure().expect("a structure of four fields");
assert_eq!(s.len(), 4);
let restricting = s.get(0).unwrap();
assert_eq!(restricting.as_structure().unwrap().len(), 4);
assert_eq!(
CaptureObject::from_data(&restricting).unwrap().logical_name,
Obis::new(0, 0, 1, 0, 0, 255)
);
}
#[test]
fn an_entry_descriptor_selects_by_position() {
let mut buf = [0u8; 32];
let sa = EntryDescriptor::entries(1, 10).to_selective_access(&mut buf).unwrap();
assert_eq!(sa.selector, 2);
let s = sa.parameters.as_structure().unwrap();
assert_eq!(s.get(0).unwrap().as_u64(), Some(1));
assert_eq!(s.get(1).unwrap().as_u64(), Some(10));
assert_eq!(s.get(3).unwrap().as_u64(), Some(0), "zero means every column");
}
#[test]
fn null_data_compression_is_undone_against_the_previous_row() {
let raw = [
0x01, 0x02, 0x02, 0x02, 0x11, 0x07, 0x12, 0x00, 0x64, 0x02, 0x02, 0x00, 0x12, 0x00, 0xC8,
];
let d = Data::from_bytes(&raw).unwrap();
let buffer = ProfileBuffer::new(&d).unwrap();
assert_eq!(buffer.len(), 2);
let mut cells = alloc::vec::Vec::new();
buffer
.for_each_cell(2, |row, col, v| {
cells.push((row, col, v.as_i64()));
Ok(())
})
.unwrap();
assert_eq!(cells[0], (0, 0, Some(7)));
assert_eq!(cells[1], (0, 1, Some(100)));
assert_eq!(cells[2], (1, 0, Some(7)), "the repeated column carried forward");
assert_eq!(cells[3], (1, 1, Some(200)));
}
#[test]
fn a_short_row_repeats_the_columns_it_left_out() {
let raw = [
0x01, 0x02, 0x02, 0x02, 0x11, 0x07, 0x12, 0x00, 0x64, 0x02, 0x01, 0x11, 0x09,
];
let d = Data::from_bytes(&raw).unwrap();
let buffer = ProfileBuffer::new(&d).unwrap();
let mut cells = alloc::vec::Vec::new();
buffer
.for_each_cell(2, |row, col, v| {
cells.push((row, col, v.as_i64()));
Ok(())
})
.unwrap();
assert_eq!(cells.len(), 4, "every row yields every column");
assert_eq!(cells[2], (1, 0, Some(9)));
assert_eq!(cells[3], (1, 1, Some(100)), "the column the row left out carried forward");
}
#[test]
fn delta_columns_are_expanded_against_the_previous_row() {
let raw = [
0x01, 0x03, 0x02, 0x01, 0x06, 0x00, 0x0F, 0x42, 0x40, 0x02, 0x01, 0x21, 0x00, 0x00, 0x00, 0xFA, 0x02, 0x01, 0x21, 0x00, 0x00, 0x01, 0x2C,
];
let d = Data::from_bytes(&raw).unwrap();
let buffer = ProfileBuffer::new(&d).unwrap();
let mut values = alloc::vec::Vec::new();
buffer
.for_each_cell(1, |_, _, v| {
values.push(v.as_u64());
Ok(())
})
.unwrap();
assert_eq!(values, [Some(1_000_000), Some(1_000_250), Some(1_000_550)]);
}
#[test]
fn a_signed_delta_may_decrease_and_the_arithmetic_wraps() {
assert_eq!(apply_delta(Data::Long(100), Data::DeltaLong(-30)), Some(Data::Long(70)));
assert_eq!(
apply_delta(Data::DoubleLongUnsigned(u32::MAX), Data::DeltaDoubleLongUnsigned(2)),
Some(Data::DoubleLongUnsigned(1)),
"a register rollover is a rollover, not a ceiling"
);
}
#[test]
fn a_delta_of_the_wrong_width_is_refused_rather_than_widened() {
assert_eq!(apply_delta(Data::DoubleLongUnsigned(1000), Data::DeltaLongUnsigned(5)), None);
assert_eq!(apply_delta(Data::Unsigned(1), Data::DeltaInteger(1)), None);
let raw = [
0x01, 0x02, 0x02, 0x01, 0x06, 0x00, 0x0F, 0x42, 0x40, 0x02, 0x01, 0x20, 0x00, 0xFA,
];
let d = Data::from_bytes(&raw).unwrap();
let buffer = ProfileBuffer::new(&d).unwrap();
assert_eq!(buffer.for_each_cell(1, |_, _, _| Ok(())).unwrap_err().kind, ErrorKind::TypeMismatch);
}
#[test]
fn a_leading_delta_is_refused_like_a_leading_null() {
let raw = [0x01, 0x01, 0x02, 0x01, 0x21, 0x00, 0x00, 0x00, 0x05];
let d = Data::from_bytes(&raw).unwrap();
let buffer = ProfileBuffer::new(&d).unwrap();
assert!(buffer.for_each_cell(1, |_, _, _| Ok(())).is_err());
}
#[test]
fn a_leading_null_has_nothing_to_repeat_and_is_refused() {
let raw = [0x01, 0x01, 0x02, 0x01, 0x00];
let d = Data::from_bytes(&raw).unwrap();
let buffer = ProfileBuffer::new(&d).unwrap();
assert!(buffer.for_each_cell(1, |_, _, _| Ok(())).is_err());
}
}