Skip to main content

cls_eedi/
metering.rs

1//! Aggregate signed momentary total power from the provisioned controllable devices.
2//!
3//! KEO's `controllable` source represents all controllable devices in the local
4//! network. This function takes each device's validated total active power in watts.
5//! The caller identifies the device through its authenticated session, checks
6//! measurement quality and selects observations from one sampling window.
7//! [KEO measurements](https://github.com/KEO-cls-eedi/specification/blob/1.2.0/doc/clseedi.md#L553-L605)
8
9use crate::wire::ScaledNumber;
10use std::collections::{BTreeMap, BTreeSet};
11
12/// Maximum number of devices in one aggregation.
13pub const MAX_PARTICIPANTS: usize = 256;
14/// Maximum byte length of a local provisioned participant identifier.
15pub const MAX_PARTICIPANT_ID_BYTES: usize = 256;
16
17/// A complete, exact controllable power observation could not be constructed.
18#[derive(Debug, PartialEq, Eq, thiserror::Error)]
19pub enum AggregateError {
20    #[error("a nonempty set of controllable devices is required")]
21    Empty,
22    #[error("too many participants or samples")]
23    Capacity,
24    #[error("participant ID is empty or exceeds the byte limit")]
25    InvalidId,
26    #[error("participant appears more than once")]
27    DuplicateParticipant,
28    #[error("sample belongs to an unprovisioned participant")]
29    UnexpectedParticipant,
30    #[error("more than one sample was supplied for a participant")]
31    DuplicateSample,
32    #[error("exact total is outside the wire scaled-number representation")]
33    Unrepresentable,
34}
35
36/// Sum one signed total-power reading in watts per provisioned device.
37///
38/// Every ID must appear exactly once in `expected`. An absent reading or an
39/// explicit `None` (e.g. stale, invalid or out of range) yields `Ok(None)`.
40/// Membership errors are reported even if another sample is missing.
41/// IDs are opaque, case-sensitive local identifiers. Positive watts indicate
42/// consumption, negative watts production.
43///
44/// The result retains the finest input scale that fits a signed 64-bit coefficient.
45/// Zero retains the finest input scale. The calculation never rounds.
46///
47/// ```
48/// use cls_eedi::{metering::controllable_total_power, wire::ScaledNumber};
49///
50/// let samples = [
51///     ("pump", Some(ScaledNumber { number: 1250, scale: 0 })),
52///     ("pv", Some(ScaledNumber { number: -3025, scale: -1 })),
53/// ];
54/// assert_eq!(controllable_total_power(&["pv", "pump"], &samples)?,
55///            Some(ScaledNumber { number: 9475, scale: -1 }));
56/// # Ok::<(), cls_eedi::metering::AggregateError>(())
57/// ```
58pub fn controllable_total_power(
59    expected: &[&str],
60    samples: &[(&str, Option<ScaledNumber>)],
61) -> Result<Option<ScaledNumber>, AggregateError> {
62    if expected.is_empty() {
63        return Err(AggregateError::Empty);
64    }
65    if expected.len() > MAX_PARTICIPANTS || samples.len() > MAX_PARTICIPANTS {
66        return Err(AggregateError::Capacity);
67    }
68    let mut participants = BTreeSet::new();
69    for &id in expected {
70        check_id(id)?;
71        if !participants.insert(id) {
72            return Err(AggregateError::DuplicateParticipant);
73        }
74    }
75    let mut seen = BTreeSet::new();
76    for (id, _) in samples {
77        check_id(id)?;
78        if !participants.contains(id) {
79            return Err(AggregateError::UnexpectedParticipant);
80        }
81        if !seen.insert(id) {
82            return Err(AggregateError::DuplicateSample);
83        }
84    }
85    if seen.len() != participants.len() || samples.iter().any(|(_, value)| value.is_none()) {
86        return Ok(None);
87    }
88    let values = samples.iter().filter_map(|(_, v)| v.as_ref());
89    exact_sum(values).map(Some)
90}
91
92fn check_id(id: &str) -> Result<(), AggregateError> {
93    if id.is_empty() || id.len() > MAX_PARTICIPANT_ID_BYTES {
94        return Err(AggregateError::InvalidId);
95    }
96    Ok(())
97}
98
99fn exact_sum<'a>(
100    values: impl Iterator<Item = &'a ScaledNumber>,
101) -> Result<ScaledNumber, AggregateError> {
102    let mut columns = BTreeMap::<i32, i128>::new();
103    let mut finest = i16::MAX;
104    for value in values {
105        finest = finest.min(value.scale);
106        *columns.entry(i32::from(value.scale)).or_default() += i128::from(value.number);
107    }
108
109    // Collapse intersecting decimal columns before checking representability.
110    // Signed remainders let carries die out even for negative numbers. Each
111    // input contributes at most 19 occupied places plus a bounded sum carry.
112    // An empty 65,535-place gap therefore requires no allocation or iteration.
113    let mut digits = Vec::new();
114    while let Some((place, coefficient)) = columns.pop_first() {
115        let digit = coefficient % 10;
116        if digit != 0 {
117            digits.push((place, digit));
118        }
119        let carry = coefficient / 10;
120        if carry != 0 {
121            *columns.entry(place + 1).or_default() += carry;
122        }
123    }
124    let Some(&(lowest, _)) = digits.first() else {
125        return Ok(ScaledNumber {
126            number: 0,
127            scale: finest,
128        });
129    };
130    // A trailing power of ten above i16::MAX must remain in the coefficient.
131    let mut scale = lowest.min(i32::from(i16::MAX)) as i16;
132    let mut previous = digits.last().expect("nonempty digits").0;
133    let mut coefficient = 0i128;
134    for (place, digit) in digits.into_iter().rev().chain([(i32::from(scale), 0)]) {
135        let factor = 10i128
136            .checked_pow((previous - place) as u32)
137            .ok_or(AggregateError::Unrepresentable)?;
138        coefficient = coefficient
139            .checked_mul(factor)
140            .and_then(|n| n.checked_add(digit))
141            .ok_or(AggregateError::Unrepresentable)?;
142        previous = place;
143    }
144    let mut number = i64::try_from(coefficient).map_err(|_| AggregateError::Unrepresentable)?;
145    while scale > finest {
146        let Some(shifted) = number.checked_mul(10) else {
147            break;
148        };
149        number = shifted;
150        scale -= 1;
151    }
152    Ok(ScaledNumber { number, scale })
153}