Skip to main content

opcua_kit/commissioning/meter/
projection.rs

1use std::collections::{BTreeMap, btree_map::Entry};
2
3use super::{
4    Contract, Duration, Error, Expected, FloatingBits, Instant, JsonObject, MAX_DOCUMENT_BYTES,
5    MeterExclusion, MeterExclusionReason, MeterPoint, MeterProjection, MeterReading, MeterTrace,
6    NodeId, OffsetDateTime, Reading, Window, compact_line_bytes, decode, meter_signal,
7    validate_reading,
8};
9
10// Every minimally encoded wire close already takes over 32 bytes. Check the supplied
11// count before indexing, even if every entry describes exactly the same quarter.
12const MAX_CLOSES: usize = MAX_DOCUMENT_BYTES / 32;
13
14/// A site's independently bound CEMS comparison window, supplied to [`MeterProjector::new`].
15#[derive(Clone, Copy, Debug)]
16pub struct MeterWindow<'a> {
17    /// Device to which the independent close feed belongs.
18    pub device: &'a str,
19    /// ApplicationUri of that meter's OPC UA server.
20    pub application_uri: &'a str,
21    /// URI-qualified identity of the corresponding register.
22    pub node: &'a NodeId,
23    /// Inclusive, quarter-hour-aligned comparison start.
24    pub start: OffsetDateTime,
25    /// Inclusive register end and exclusive close start limit, at most 31 days after start.
26    pub end: OffsetDateTime,
27    /// Largest accepted absolute difference in watt-hours.
28    pub tolerance_wh: u64,
29}
30
31#[derive(Debug, PartialEq, Eq)]
32struct Observation {
33    status: u32,
34    value: Option<u64>,
35    bits: Option<FloatingBits>,
36    usable_wh: Option<u64>,
37}
38
39/// A bounded projector for a stream of already validated readings. The projector
40/// borrows only the contract. It retains the raw facts needed to detect in-window
41/// conflicts and charges every push its compact JSON size plus one newline.
42///
43/// ```
44/// use opcua_kit::commissioning::{Contract, Error, meter::{
45///     MeterProjection, MeterProjector, MeterReading, MeterWindow, OffsetDateTime,
46/// }};
47///
48/// fn reconcile_input(
49///     contract: &Contract,
50///     window: MeterWindow<'_>,
51///     readings: impl IntoIterator<Item = MeterReading>,
52///     independent_closes: &[(OffsetDateTime, u64)],
53/// ) -> Result<MeterProjection, Error> {
54///     let mut projector = MeterProjector::new(contract, window)?;
55///     for reading in readings {
56///         projector.push(&reading)?;
57///     }
58///     projector.finish(independent_closes)
59/// }
60/// ```
61#[derive(Debug)]
62pub struct MeterProjector<'a> {
63    contract: &'a Contract,
64    signal: &'a Expected,
65    result: MeterProjection,
66    observations: BTreeMap<Instant, Observation>,
67    remaining_bytes: usize,
68    pushes: usize,
69    failure: Option<Error>,
70}
71
72fn utc(at: OffsetDateTime) -> Result<Instant, Error> {
73    Instant::utc(at).ok_or_else(|| Error::new("timestamp outside four-digit UTC year range"))
74}
75
76impl<'a> MeterProjector<'a> {
77    /// Bind the independently configured close feed and validate the comparison window.
78    pub fn new(contract: &'a Contract, window: MeterWindow<'_>) -> Result<Self, Error> {
79        Self::bind(contract, meter_signal(contract)?, window)
80    }
81
82    fn bind(
83        contract: &'a Contract,
84        signal: &'a Expected,
85        window: MeterWindow<'_>,
86    ) -> Result<Self, Error> {
87        if window.device != contract.device()
88            || window.application_uri != contract.application_uri()
89            || window.node != &signal.node
90        {
91            return Err(Error::new(
92                "CEMS window meter differs from the reviewed device, application URI or register node",
93            ));
94        }
95        let start = utc(window.start)?;
96        let end = utc(window.end)?;
97        let span = end.0 - start.0;
98        if !start.aligned() || !end.aligned() || span <= Duration::ZERO || span > Duration::days(31)
99        {
100            return Err(Error::new(
101                "use a positive UTC quarter-hour-aligned window of at most 31 days",
102            ));
103        }
104        Ok(Self {
105            contract,
106            signal,
107            result: MeterProjection {
108                trace: MeterTrace {
109                    start,
110                    end,
111                    tolerance_wh: window.tolerance_wh,
112                    closed: Vec::new(),
113                    register: Vec::new(),
114                },
115                skipped_status: 0,
116                skipped_source_time: 0,
117                skipped_precision: 0,
118                first_exclusion: None,
119                outside_window: 0,
120                duplicate_readings: 0,
121            },
122            observations: BTreeMap::new(),
123            remaining_bytes: MAX_DOCUMENT_BYTES,
124            pushes: 0,
125            failure: None,
126        })
127    }
128
129    /// Remaining typed reading budget in bytes. Compare with [`MeterReading::compact_line_bytes`]
130    /// before pushing. A failed push leaves zero usable bytes.
131    pub fn remaining_input_bytes(&self) -> usize {
132        self.remaining_bytes
133    }
134
135    /// Validate the reading against this contract and add it to the projection.
136    /// The first error is terminal and is returned by later pushes and [`Self::finish`].
137    /// The total compact size including one newline per push must fit in 4 MiB.
138    pub fn push(&mut self, reading: &MeterReading) -> Result<(), Error> {
139        if let Some(error) = &self.failure {
140            return Err(error.clone());
141        }
142        self.pushes += 1;
143        let result = if let Some(remaining) = self
144            .remaining_bytes
145            .checked_sub(reading.compact_line_bytes())
146        {
147            self.remaining_bytes = remaining;
148            self.ingest(&reading.row, self.pushes)
149        } else {
150            Err(Error::new("meter readings exceed 4 MiB"))
151        };
152        result.map_err(|error| {
153            let error = error.at(&format!("reading {}", self.pushes));
154            self.failure = Some(error.clone());
155            self.remaining_bytes = 0;
156            error
157        })
158    }
159
160    fn ingest(&mut self, row: &Reading, input_position: usize) -> Result<(), Error> {
161        validate_reading(self.contract, self.signal, row)?;
162        let result = &mut self.result;
163        if row
164            .source_at
165            .is_some_and(|at| at < result.trace.start || at > result.trace.end)
166        {
167            result.outside_window += 1;
168            return Ok(());
169        }
170        let eligibility = match row.source_at {
171            _ if row.status != 0 => Err(MeterExclusionReason::Status(row.status)),
172            None => Err(MeterExclusionReason::MissingSourceTime),
173            Some(at) if at > row.received_at => Err(MeterExclusionReason::SourceAfterReceipt),
174            Some(_) => match row.value_bits {
175                Some(bits) => bits.whole_wh().map(Some),
176                None => Ok(row.value),
177            },
178        };
179        let usable_wh = match eligibility {
180            Ok(wh) => wh,
181            Err(reason) => {
182                use MeterExclusionReason::*;
183                match reason {
184                    Status(_) => result.skipped_status += 1,
185                    MissingSourceTime | SourceAfterReceipt => result.skipped_source_time += 1,
186                    NonFiniteWh | NegativeWh | FractionalWh | InsufficientResolution => {
187                        result.skipped_precision += 1;
188                    }
189                }
190                result.first_exclusion.get_or_insert(MeterExclusion {
191                    input_position,
192                    source_at: row.source_at.map(|at| at.0),
193                    reason,
194                });
195                None
196            }
197        };
198        if let Some(at) = row.source_at {
199            let evidence = Observation {
200                status: row.status,
201                value: row.value,
202                bits: row.value_bits,
203                usable_wh,
204            };
205            match self.observations.entry(at) {
206                Entry::Vacant(entry) => {
207                    entry.insert(evidence);
208                }
209                Entry::Occupied(entry) if *entry.get() != evidence => {
210                    return Err(Error::new(
211                        "conflicting meter evidence at the same source instant",
212                    ));
213                }
214                Entry::Occupied(_) if usable_wh.is_some() => result.duplicate_readings += 1,
215                Entry::Occupied(_) => {}
216            }
217        }
218        Ok(())
219    }
220
221    fn set_closes(
222        &mut self,
223        closed: impl ExactSizeIterator<Item = (OffsetDateTime, u64)>,
224    ) -> Result<(), Error> {
225        if closed.len() > MAX_CLOSES {
226            return Err(Error::new(
227                "CEMS window exceeds 131072 independent close entries",
228            ));
229        }
230        let mut values = BTreeMap::new();
231        for (at, wh) in closed {
232            let at = utc(at)?;
233            if !at.aligned() || at < self.result.trace.start || at >= self.result.trace.end {
234                return Err(Error::new(
235                    "closed energy must use a quarter-hour start inside the window",
236                ));
237            }
238            if values.insert(at, wh).is_some_and(|prior| prior != wh) {
239                return Err(Error::new(
240                    "conflicting independent closes at the same instant",
241                ));
242            }
243        }
244        self.result.trace.closed = values
245            .into_iter()
246            .map(|(at, wh)| MeterPoint { at, wh })
247            .collect();
248        Ok(())
249    }
250
251    /// Supply the independent closes for the meter bound at construction, then
252    /// return its sorted trace, omission counts and first exclusion. An empty slice leaves all closes missing.
253    /// Each pair is the UTC quarter start (or its offset equivalent) and interval energy
254    /// in Wh. Accepts up to 131,072 entries including duplicates. Identical closes coalesce.
255    /// The compact trace and its trailing newline must fit in 4 MiB.
256    pub fn finish(mut self, closed: &[(OffsetDateTime, u64)]) -> Result<MeterProjection, Error> {
257        if let Some(error) = self.failure {
258            return Err(error);
259        }
260        self.set_closes(closed.iter().copied())?;
261        self.complete()
262    }
263
264    fn complete(mut self) -> Result<MeterProjection, Error> {
265        self.result.trace.register = self
266            .observations
267            .into_iter()
268            .filter_map(|(at, evidence)| evidence.usable_wh.map(|wh| MeterPoint { at, wh }))
269            .collect();
270        compact_line_bytes(&self.result.trace)?;
271        Ok(self.result)
272    }
273}
274
275/// Project newline-delimited meter readings and a separate CEMS window with
276/// independent `closed` energy. The window must identify the same device,
277/// application URI and register node. Both inputs are limited to 4 MiB. Unusable
278/// readings are counted and omitted. Incompatible scope or conflicting evidence
279/// at an in-window source instant rejects the whole projection.
280pub fn project_meter_trace(
281    contract: &Contract,
282    readings_ndjson: &[u8],
283    window_json: &[u8],
284) -> Result<MeterProjection, Error> {
285    let signal = meter_signal(contract)?;
286    if readings_ndjson.len() > MAX_DOCUMENT_BYTES {
287        return Err(Error::new("meter readings exceed 4 MiB"));
288    }
289    let window: Window = decode(window_json, "CEMS window")?;
290    let binding = MeterWindow {
291        device: &window.meter.device,
292        application_uri: &window.meter.application_uri,
293        node: &window.meter.node,
294        start: window.start.0,
295        end: window.end.0,
296        tolerance_wh: window.tolerance_wh,
297    };
298    let mut projector = MeterProjector::bind(contract, signal, binding)?;
299    projector.set_closes(
300        window
301            .closed
302            .into_iter()
303            .map(|JsonObject(point)| (point.at.0, point.wh)),
304    )?;
305    for (index, line) in readings_ndjson.split(|b| *b == b'\n').enumerate() {
306        if line.iter().all(|b| matches!(b, b' ' | b'\t' | b'\r')) {
307            continue;
308        }
309        // This replay is already bounded by the original physical byte count.
310        decode(line, "meter reading")
311            .and_then(|row| projector.ingest(&row, index + 1))
312            .map_err(|err| err.at(&format!("readings line {}", index + 1)))?;
313    }
314    projector.complete()
315}