Skip to main content

smgw_lmn/dlms/
acquisition.rs

1pub use crate::Counts;
2
3use super::{
4    ClockRange, RowError, protocol,
5    rows::{Layout, scaler_unit},
6};
7use core::fmt;
8use protocol::{
9    Obis,
10    axdr::Data,
11    cosem::CaptureObject,
12    xdlms::{AttributeDescriptor, SelectiveAccess},
13};
14
15use smgw_core::taf15;
16
17/// An authorized meter association with exclusive access between GETs.
18/// The host bounds each response and its deadline and validates request correlation.
19pub trait AttributeReader {
20    type Error;
21
22    /// Identity bound to this association by the caller at commissioning.
23    fn meter_id(&self) -> &str;
24
25    /// Read exactly this attribute and selection. Propagate transport and meter refusals.
26    fn get(
27        &mut self,
28        attribute: AttributeDescriptor,
29        selection: Option<SelectiveAccess<'_>>,
30    ) -> Result<Data<'_>, Self::Error>;
31}
32
33/// The meter, profile, and captured objects commissioned for one TAF 15 channel.
34#[derive(Debug, Clone, Copy)]
35pub struct Source<'a> {
36    /// The class 3 register value is attribute 2 of this OBIS. Supported units are Wh, varh and m³.
37    pub channel: taf15::Channel<'a>,
38    /// Class 7 Profile Generic logical name.
39    pub profile: Obis,
40    /// Distinct captured measurement time. Absent means the registration clock supplies both times.
41    pub measured_time: Option<CaptureObject>,
42    /// Captured unsigned meter status. Absent means the records carry no meter status.
43    pub status: Option<CaptureObject>,
44}
45
46/// Why the selected range could not be imported.
47#[derive(Debug, PartialEq, Eq)]
48pub enum ReadError<E> {
49    /// The association or destination differs from the commissioned meter/channel.
50    WrongSource,
51    /// The inclusive selection extends beyond the commissioned destination.
52    Window,
53    /// The capture period differs from the destination's registration period.
54    Period,
55    /// The meter changed its capture definitions or scaler during the read.
56    MetadataChanged,
57    /// Range selector encoding failed.
58    Selector(protocol::Error),
59    /// A wire value or original record failed validation.
60    Row(RowError),
61    /// The underlying reader refused a GET or its transport failed.
62    Reader(E),
63}
64
65impl<E: fmt::Display> fmt::Display for ReadError<E> {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            Self::WrongSource => {
69                f.write_str("meter identity or channel differs from commissioning")
70            }
71            Self::Window => f.write_str("clock selection extends beyond the TAF 15 window"),
72            Self::Period => {
73                f.write_str("meter capture period differs from the commissioned interval")
74            }
75            Self::MetadataChanged => f.write_str("meter metadata changed during the selected read"),
76            Self::Selector(e) => write!(f, "clock selector: {e}"),
77            Self::Row(e) => e.fmt(f),
78            Self::Reader(e) => write!(f, "meter read: {e}"),
79        }
80    }
81}
82
83impl<E: core::error::Error + 'static> core::error::Error for ReadError<E> {
84    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
85        match self {
86            Self::Reader(e) => Some(e),
87            Self::Row(e) => Some(e),
88            _ => None,
89        }
90    }
91}
92
93fn metadata<R: AttributeReader>(
94    reader: &mut R,
95    source: &Source<'_>,
96    period: taf15::Period,
97) -> Result<(Layout, i8), ReadError<R::Error>> {
98    let captures = reader
99        .get(AttributeDescriptor::new(7, source.profile, 3), None)
100        .map_err(ReadError::Reader)?;
101    let layout = Layout::resolve(source, &captures).map_err(ReadError::Row)?;
102    let interval = reader
103        .get(AttributeDescriptor::new(7, source.profile, 4), None)
104        .map_err(ReadError::Reader)?;
105    if interval != Data::DoubleLongUnsigned(period.seconds() as u32) {
106        return Err(ReadError::Period);
107    }
108    let register = AttributeDescriptor::new(3, source.channel.obis.into(), 3);
109    let scaler = reader.get(register, None).map_err(ReadError::Reader)?;
110    Ok((
111        layout,
112        scaler_unit(source.channel, &scaler).map_err(ReadError::Row)?,
113    ))
114}
115
116/// Read the inclusive clock range from an existing association. A single-slot range
117/// can backfill an instant returned by [`taf15::Profile::missing`]. Exact repeats
118/// increment the duplicate count. On error all records and holes stay intact.
119///
120/// The meter must supply coherent capture metadata and rows for the duration of a read.
121/// A range can return fewer rows than requested, including none.
122pub fn read_profile<R: AttributeReader, const N: usize>(
123    reader: &mut R,
124    source: &Source<'_>,
125    range: ClockRange,
126    destination: &mut taf15::Profile<'_, N>,
127) -> Result<Counts, ReadError<R::Error>> {
128    if reader.meter_id() != source.channel.meter_id || destination.channel() != source.channel {
129        return Err(ReadError::WrongSource);
130    }
131    let window = destination.window();
132    if !window.contains(&range.start()) || !window.contains(&range.end()) {
133        return Err(ReadError::Window);
134    }
135
136    let header = metadata(reader, source, destination.period())?;
137    let mut scratch = [0; 64];
138    let selection = range.selection(&mut scratch).map_err(ReadError::Selector)?;
139    let buffer = AttributeDescriptor::new(7, source.profile, 2);
140    destination.capture_batch(|profile| {
141        let rows = reader
142            .get(buffer, Some(selection))
143            .map_err(ReadError::Reader)?;
144        let counts = header
145            .0
146            .capture(source, profile, range, header.1, &rows)
147            .map_err(ReadError::Row)?;
148        if header != metadata(reader, source, profile.period())? {
149            return Err(ReadError::MetadataChanged);
150        }
151        if reader.meter_id() != source.channel.meter_id {
152            return Err(ReadError::WrongSource);
153        }
154        Ok(counts)
155    })
156}