Skip to main content

opcua_kit/commissioning/
meter.rs

1//! Evidence for one approved cumulative grid-import register and its CEMS trace.
2//!
3//! A metadata snapshot contains no register values. Select a single scalar
4//! UInt32, UInt64, Float or Double in watt-hours and use a separate meter reading document.
5//! The site must confirm import direction and the source clock's meaning.
6//! Projection preserves observed instants and never invents a quarter boundary.
7//!
8//! Good-severity evidence carries an unsigned register in `value`, or the raw
9//! floating-point word in `valueBits`. A Float word is a JSON UInt32. A Double
10//! word is a string of 16 lowercase hex digits, most significant digit first.
11//! Floating-point readings qualify as whole Wh only in `[0, 2²⁴)` for Float
12//! and `[0, 2⁵³)` for Double, under the same status and timestamp rules.
13
14use std::{fmt, marker::PhantomData};
15
16use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
17
18pub use time::OffsetDateTime;
19use time::{Duration, UtcOffset, format_description::well_known::Rfc3339};
20
21use super::{ByteBudget, Contract, Error, Expected, MAX_DOCUMENT_BYTES, NodeId, Unit, present};
22use crate::{Severity, status_severity};
23
24const UA: &str = "http://opcfoundation.org/UA/";
25
26#[cfg(feature = "client")]
27mod live;
28
29mod projection;
30pub use projection::{MeterProjector, MeterWindow, project_meter_trace};
31
32pub(crate) fn meter_signal(contract: &Contract) -> Result<&Expected, Error> {
33    if contract.0.principal != "anonymous"
34        && !contract
35            .0
36            .principal
37            .strip_prefix("username:")
38            .is_some_and(|name| !name.trim().is_empty() && name.len() <= 256)
39    {
40        return Err(Error::new(
41            "expected anonymous or username:<account> for the meter principal",
42        ));
43    }
44    let [signal] = contract.0.signals.as_slice() else {
45        return Err(Error::new(
46            "meter contract must select exactly one grid-import register",
47        ));
48    };
49    if signal.data_type.namespace() != UA
50        || !matches!(
51            signal.data_type.identifier(),
52            "i=7" | "i=9" | "i=10" | "i=11"
53        )
54    {
55        return Err(Error::new(
56            "meter contract requires standard UInt32, UInt64, Float or Double DataType",
57        ));
58    }
59    if signal.value_rank != Some(-1) {
60        return Err(Error::new("meter contract requires scalar valueRank -1"));
61    }
62    if !signal
63        .engineering_units
64        .as_ref()
65        .is_some_and(Unit::is_watt_hour)
66    {
67        return Err(Error::new(
68            "meter contract requires UN/CEFACT watt-hours (WHR)",
69        ));
70    }
71    Ok(signal)
72}
73
74/// Check that a reviewed contract selects exactly one supported grid-import register.
75pub fn validate_meter_contract(contract: &Contract) -> Result<(), Error> {
76    meter_signal(contract).map(|_| ())
77}
78
79#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
80struct Instant(OffsetDateTime);
81
82impl Instant {
83    fn utc(time: OffsetDateTime) -> Option<Self> {
84        time.checked_to_offset(UtcOffset::UTC)
85            .filter(|utc| (0..=9999).contains(&utc.year()))
86            .map(Self)
87    }
88
89    fn aligned(self) -> bool {
90        self.0.nanosecond() == 0 && self.0.unix_timestamp().rem_euclid(900) == 0
91    }
92}
93
94impl<'de> Deserialize<'de> for Instant {
95    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
96        let text = String::deserialize(deserializer)?;
97        let bytes = text.as_bytes();
98        // RFC 3339 parsers can normalize leap seconds and truncate subseconds.
99        // Reject either before parsing so distinct evidence cannot collapse.
100        let excess_precision = bytes.get(19) == Some(&b'.')
101            && bytes
102                .get(20..30)
103                .is_some_and(|digits| digits.iter().all(u8::is_ascii_digit));
104        if excess_precision
105            || bytes.get(17..19) == Some(b"60")
106            || !matches!(bytes.get(10), Some(b'T' | b't'))
107            || text.ends_with("-00:00")
108        {
109            return Err(de::Error::custom(
110                "expected RFC 3339 with known offset and at most nanosecond precision",
111            ));
112        }
113        let local = OffsetDateTime::parse(&text, &Rfc3339)
114            .map_err(|_| de::Error::custom("invalid RFC 3339 timestamp"))?;
115        Self::utc(local)
116            .ok_or_else(|| de::Error::custom("timestamp outside four-digit UTC year range"))
117    }
118}
119
120impl Serialize for Instant {
121    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
122        let text = self.0.format(&Rfc3339).map_err(serde::ser::Error::custom)?;
123        serializer.serialize_str(&text)
124    }
125}
126
127/// One scope-checked DataValue. Serialize this to retain its independent clocks,
128/// raw UInt32 status, and the original integer or floating-point bit pattern on Good severity.
129#[derive(Debug, Serialize)]
130#[serde(transparent)]
131pub struct MeterReading {
132    row: Reading,
133    #[serde(skip)]
134    line_bytes: usize,
135}
136
137// The wire parser and native reader validate the same evidence representation.
138#[derive(Debug, Serialize, Deserialize)]
139#[serde(rename_all = "camelCase", deny_unknown_fields)]
140struct Reading {
141    schema_version: u32,
142    device: String,
143    application_uri: String,
144    principal: String,
145    name: String,
146    #[serde(deserialize_with = "object")]
147    node: NodeId,
148    #[serde(deserialize_with = "object")]
149    data_type: NodeId,
150    value_rank: i32,
151    #[serde(deserialize_with = "object")]
152    engineering_units: Unit,
153    received_at: Instant,
154    // An explicit null records that a server did not return this clock.
155    #[serde(deserialize_with = "Option::deserialize")]
156    source_at: Option<Instant>,
157    #[serde(deserialize_with = "Option::deserialize")]
158    server_at: Option<Instant>,
159    status: u32,
160    #[serde(
161        default,
162        skip_serializing_if = "Option::is_none",
163        deserialize_with = "present"
164    )]
165    value: Option<u64>,
166    #[serde(
167        default,
168        skip_serializing_if = "Option::is_none",
169        deserialize_with = "present"
170    )]
171    value_bits: Option<FloatingBits>,
172}
173
174// A 32-bit word is exactly representable by JSON consumers using binary64.
175// A 64-bit word uses hexadecimal text so even its least significant bit survives.
176#[derive(Clone, Copy, Debug, Eq, PartialEq)]
177enum FloatingBits {
178    Float(u32),
179    Double(u64),
180}
181
182impl<'de> Deserialize<'de> for FloatingBits {
183    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
184        struct Word;
185        impl de::Visitor<'_> for Word {
186            type Value = FloatingBits;
187
188            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189                f.write_str("UInt32 or 16 lowercase hexadecimal digits")
190            }
191
192            fn visit_u64<E: de::Error>(self, word: u64) -> Result<Self::Value, E> {
193                u32::try_from(word)
194                    .map(FloatingBits::Float)
195                    .map_err(E::custom)
196            }
197
198            fn visit_str<E: de::Error>(self, word: &str) -> Result<Self::Value, E> {
199                if word.len() != 16 || !word.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
200                {
201                    return Err(E::custom("expected 16 lowercase hexadecimal digits"));
202                }
203                u64::from_str_radix(word, 16)
204                    .map(FloatingBits::Double)
205                    .map_err(E::custom)
206            }
207        }
208        // Restrict the JSON token to a scalar before constructing any payload.
209        d.deserialize_any(Word)
210    }
211}
212
213impl Serialize for FloatingBits {
214    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
215        match self {
216            Self::Float(bits) => s.serialize_u32(*bits),
217            Self::Double(bits) => s.collect_str(&format_args!("{bits:016x}")),
218        }
219    }
220}
221
222impl FloatingBits {
223    fn whole_wh(self) -> Result<u64, MeterExclusionReason> {
224        // Widening a binary32 is exact. Each cutoff is the first magnitude at
225        // which the next larger value of its original wire type is 2 Wh away.
226        let (wh, limit) = match self {
227            Self::Float(bits) => (f64::from(f32::from_bits(bits)), 16_777_216.0),
228            Self::Double(bits) => (f64::from_bits(bits), 9_007_199_254_740_992.0),
229        };
230        if !wh.is_finite() {
231            Err(MeterExclusionReason::NonFiniteWh)
232        } else if wh < 0.0 {
233            Err(MeterExclusionReason::NegativeWh)
234        } else if wh >= limit {
235            Err(MeterExclusionReason::InsufficientResolution)
236        } else if wh.fract() != 0.0 {
237            Err(MeterExclusionReason::FractionalWh)
238        } else {
239            Ok(wh as u64)
240        }
241    }
242}
243
244impl MeterReading {
245    fn checked(contract: &Contract, signal: &Expected, row: Reading) -> Result<Self, Error> {
246        validate_reading(contract, signal, &row)?;
247        let line_bytes = compact_line_bytes(&row)?;
248        Ok(Self { row, line_bytes })
249    }
250
251    /// Cached byte size of this compact UTF-8 JSON reading plus one LF.
252    /// This is the exact input charge for [`MeterProjector::push`].
253    pub fn compact_line_bytes(&self) -> usize {
254        self.line_bytes
255    }
256
257    /// Full OPC UA Value read status, including subcode and information bits.
258    pub fn status(&self) -> u32 {
259        self.row.status
260    }
261
262    /// Original UInt32 or UInt64 register value when the wire status has Good severity.
263    pub fn value(&self) -> Option<u64> {
264        self.row.value
265    }
266
267    /// Original binary32 bits for a Float register when the wire status has Good severity.
268    pub fn value_bits(&self) -> Option<u32> {
269        match self.row.value_bits {
270            Some(FloatingBits::Float(bits)) => Some(bits),
271            _ => None,
272        }
273    }
274
275    /// Original binary64 bits for a Double register when the wire status has Good severity.
276    pub fn double_bits(&self) -> Option<u64> {
277        match self.row.value_bits {
278            Some(FloatingBits::Double(bits)) => Some(bits),
279            _ => None,
280        }
281    }
282
283    /// Original source clock, normalized to UTC at its supplied precision.
284    pub fn source_at(&self) -> Option<OffsetDateTime> {
285        self.row.source_at.map(|at| at.0)
286    }
287
288    /// Original server clock when the read included it.
289    pub fn server_at(&self) -> Option<OffsetDateTime> {
290        self.row.server_at.map(|at| at.0)
291    }
292
293    /// UTC receipt time measured by the reader.
294    pub fn received_at(&self) -> OffsetDateTime {
295        self.row.received_at.0
296    }
297}
298
299// serde's default derived struct decoder also accepts positional JSON arrays.
300// The document contracts use named object members, including on nested points.
301fn object<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<T, D::Error> {
302    struct Named<T>(PhantomData<T>);
303    impl<'de, T: Deserialize<'de>> de::Visitor<'de> for Named<T> {
304        type Value = T;
305        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306            f.write_str("a JSON object")
307        }
308        fn visit_map<A: de::MapAccess<'de>>(self, map: A) -> Result<T, A::Error> {
309            T::deserialize(de::value::MapAccessDeserializer::new(map))
310        }
311    }
312    d.deserialize_map(Named(PhantomData))
313}
314
315#[derive(Deserialize)]
316#[serde(transparent, bound(deserialize = "T: Deserialize<'de>"))]
317struct JsonObject<T>(#[serde(deserialize_with = "object")] T);
318
319fn decode<T: de::DeserializeOwned>(bytes: &[u8], kind: &str) -> Result<T, Error> {
320    if bytes.len() > MAX_DOCUMENT_BYTES {
321        return Err(Error::new(format!("{kind} exceeds 4 MiB")));
322    }
323    // Parser diagnostics can quote an entire register value or an unknown key.
324    serde_json::from_slice::<JsonObject<T>>(bytes)
325        .map(|wrapped| wrapped.0)
326        .map_err(|e| {
327            Error::new(format!(
328                "invalid {kind} at line {}, column {}: check required fields, types and timestamps",
329                e.line(),
330                e.column()
331            ))
332        })
333}
334
335fn validate_reading(
336    contract: &Contract,
337    signal: &Expected,
338    reading: &Reading,
339) -> Result<(), Error> {
340    if reading.schema_version != 1 {
341        return Err(Error::new(
342            "unsupported meter reading schemaVersion (expected 1)",
343        ));
344    }
345    if reading.device != contract.0.device
346        || reading.application_uri != contract.0.application_uri
347        || reading.principal != contract.0.principal
348        || reading.name != signal.name
349        || reading.node != signal.node
350    {
351        return Err(Error::new(
352            "meter reading scope or register identity differs from the contract",
353        ));
354    }
355    if reading.data_type != signal.data_type
356        || Some(reading.value_rank) != signal.value_rank
357        || Some(&reading.engineering_units) != signal.engineering_units.as_ref()
358    {
359        return Err(Error::new(
360            "meter reading DataType, ValueRank or EngineeringUnits differs from the contract",
361        ));
362    }
363    let valid_payload = match status_severity(reading.status) {
364        Severity::Good => match signal.data_type.identifier() {
365            "i=10" => {
366                reading.value.is_none()
367                    && matches!(reading.value_bits, Some(FloatingBits::Float(_)))
368            }
369            "i=11" => {
370                reading.value.is_none()
371                    && matches!(reading.value_bits, Some(FloatingBits::Double(_)))
372            }
373            _ => reading.value.is_some() && reading.value_bits.is_none(),
374        },
375        _ => reading.value.is_none() && reading.value_bits.is_none(),
376    };
377    if !valid_payload {
378        return Err(Error::new(
379            "Good integer readings require value, Float requires UInt32 valueBits, and Double requires 16 lowercase hex digits in valueBits. Other severities omit both fields",
380        ));
381    }
382    if signal.data_type.identifier() == "i=7"
383        && reading.value.is_some_and(|v| v > u64::from(u32::MAX))
384    {
385        return Err(Error::new(
386            "meter reading value exceeds the approved UInt32 DataType",
387        ));
388    }
389    Ok(())
390}
391
392// Check the encoded document including room for its NDJSON delimiter.
393fn compact_line_bytes(document: &impl Serialize) -> Result<usize, Error> {
394    let mut budget = ByteBudget(MAX_DOCUMENT_BYTES - 1);
395    serde_json::to_writer(&mut budget, document).map_err(|error| {
396        if error.is_io() {
397            Error::new("encoded meter document and newline exceed 4 MiB")
398        } else {
399            Error::new("could not encode meter document")
400        }
401    })?;
402    Ok(MAX_DOCUMENT_BYTES - budget.0)
403}
404
405/// Parse one strict reading and verify it belongs to the reviewed meter contract.
406pub fn parse_meter_reading(contract: &Contract, bytes: &[u8]) -> Result<MeterReading, Error> {
407    MeterReading::checked(
408        contract,
409        meter_signal(contract)?,
410        decode(bytes, "meter reading")?,
411    )
412}
413
414/// A UTC instant and an exact watt-hour amount in the CEMS trace.
415#[derive(Debug, Serialize, Deserialize)]
416#[serde(deny_unknown_fields)]
417pub struct MeterPoint {
418    at: Instant,
419    /// Cumulative register or independently closed interval energy, in watt-hours.
420    pub wh: u64,
421}
422
423impl MeterPoint {
424    /// UTC source instant for a register reading, or start instant of a close.
425    pub fn at(&self) -> OffsetDateTime {
426        self.at.0
427    }
428}
429
430// The site maps the independent close feed to the commissioned register.
431// This binding is checked locally and omitted from the consumer's trace.
432#[derive(Deserialize)]
433#[serde(rename_all = "camelCase", deny_unknown_fields)]
434struct WindowMeter {
435    device: String,
436    application_uri: String,
437    #[serde(deserialize_with = "object")]
438    node: NodeId,
439}
440
441#[derive(Deserialize)]
442#[serde(deny_unknown_fields)]
443struct Window {
444    #[serde(deserialize_with = "object")]
445    meter: WindowMeter,
446    start: Instant,
447    end: Instant,
448    tolerance_wh: u64,
449    closed: Vec<JsonObject<MeterPoint>>,
450}
451
452/// A ready-to-serialize input to `cemsd reconcile`. Reconciliation itself
453/// remains with CEMS, including its handling of counter decreases and gaps.
454#[derive(Debug, Serialize)]
455pub struct MeterTrace {
456    start: Instant,
457    end: Instant,
458    tolerance_wh: u64,
459    /// Usable source observations, ordered by UTC instant.
460    pub register: Vec<MeterPoint>,
461    /// Independent closes keyed by the start of the UTC quarter.
462    pub closed: Vec<MeterPoint>,
463}
464
465impl MeterTrace {
466    /// Inclusive start of the comparison window, normalized to UTC.
467    pub fn start(&self) -> OffsetDateTime {
468        self.start.0
469    }
470
471    /// Inclusive end of register coverage, normalized to UTC. Closes must start before this instant.
472    pub fn end(&self) -> OffsetDateTime {
473        self.end.0
474    }
475
476    /// Largest accepted absolute difference between the two energy series, in Wh.
477    pub fn tolerance_wh(&self) -> u64 {
478        self.tolerance_wh
479    }
480}
481
482/// Why an observation failed to qualify as a register point.
483#[derive(Clone, Copy, Debug, Eq, PartialEq)]
484#[non_exhaustive]
485pub enum MeterExclusionReason {
486    /// Nonzero OPC UA StatusCode, including all qualifier and information bits.
487    Status(u32),
488    /// The meter supplied no source timestamp.
489    MissingSourceTime,
490    /// The source instant is later than local receipt.
491    SourceAfterReceipt,
492    /// The floating-point register contains NaN or infinity.
493    NonFiniteWh,
494    /// The cumulative register is finite and below zero.
495    NegativeWh,
496    /// The nonnegative register contains a fraction of a watt-hour.
497    FractionalWh,
498    /// The next larger value in the register's wire type is more than 1 Wh away.
499    InsufficientResolution,
500}
501
502impl fmt::Display for MeterExclusionReason {
503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504        match self {
505            Self::Status(code) => write!(f, "OPC UA status 0x{code:08X}"),
506            Self::MissingSourceTime => f.write_str("missing source timestamp"),
507            Self::SourceAfterReceipt => f.write_str("source timestamp is after receipt"),
508            Self::NonFiniteWh => f.write_str("non-finite register value"),
509            Self::NegativeWh => f.write_str("negative cumulative Wh"),
510            Self::FractionalWh => f.write_str("fractional Wh"),
511            Self::InsufficientResolution => f.write_str("register cannot resolve 1 Wh increments"),
512        }
513    }
514}
515
516/// Location and cause of a single rejected observation.
517#[derive(Clone, Copy, Debug, Eq, PartialEq)]
518pub struct MeterExclusion {
519    /// One-based NDJSON line number (including blank lines), or one-based push number.
520    pub input_position: usize,
521    /// Meter source time in UTC, when supplied.
522    pub source_at: Option<OffsetDateTime>,
523    /// The first failed eligibility check for this observation.
524    pub reason: MeterExclusionReason,
525}
526
527/// Result of projecting evidence into a CEMS trace.
528#[derive(Debug)]
529pub struct MeterProjection {
530    /// Write this compactly as one JSON document for CEMS.
531    pub trace: MeterTrace,
532    /// Rows with a nonzero status, including qualified Good statuses.
533    pub skipped_status: usize,
534    /// Unqualified Good rows with missing source time or source time after receipt.
535    pub skipped_source_time: usize,
536    /// Otherwise eligible Float or Double rows without a nonnegative whole Wh
537    /// value below the original type's 1 Wh resolution limit (2²⁴ or 2⁵³).
538    pub skipped_precision: usize,
539    /// First observation in input order counted by any of the three `skipped_*` counters.
540    /// Outside-window observations and usable duplicates do not set this field.
541    pub first_exclusion: Option<MeterExclusion>,
542    /// Timed rows outside the requested window (regardless of status).
543    pub outside_window: usize,
544    /// Additional usable rows with the same source instant and exact value.
545    pub duplicate_readings: usize,
546}