Skip to main content

smgw_core/
taf10.rs

1//! TAF 10 grid-state measurements for one commissioned meter and OBIS channel.
2//!
3//! Supply qualified instantaneous samples every 60 seconds. Each notification is
4//! one value. The host enforces profile validity, authenticates inputs, authorizes
5//! recipients and handles access logging and delivery.
6
7use crate::minute::Samples;
8pub use crate::{minute::Crossing, taf9::ActivePower};
9use core::fmt;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Phase {
13    L1,
14    L2,
15    L3,
16}
17
18/// Permitted phase differences. The named reference voltage is the second operand.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum PhaseAngle {
21    VoltageL2ToL1,
22    VoltageL3ToL1,
23    CurrentToVoltage(Phase),
24}
25
26/// BSI TR-03109-1 v1.1, table 4.9.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Quantity {
29    ActivePower(ActivePower),
30    Current(Phase),
31    Frequency,
32    PhaseAngle(PhaseAngle),
33    Voltage(Phase),
34}
35
36impl Quantity {
37    pub const fn obis(self) -> &'static str {
38        match self {
39            Self::ActivePower(power) => power.obis(),
40            Self::Current(Phase::L1) => "1-0:31.7.0.255",
41            Self::Current(Phase::L2) => "1-0:51.7.0.255",
42            Self::Current(Phase::L3) => "1-0:71.7.0.255",
43            Self::Frequency => "1-0:14.7.0.255",
44            Self::PhaseAngle(PhaseAngle::VoltageL2ToL1) => "1-0:81.7.1.255",
45            Self::PhaseAngle(PhaseAngle::VoltageL3ToL1) => "1-0:81.7.2.255",
46            Self::PhaseAngle(PhaseAngle::CurrentToVoltage(Phase::L1)) => "1-0:81.7.4.255",
47            Self::PhaseAngle(PhaseAngle::CurrentToVoltage(Phase::L2)) => "1-0:81.7.15.255",
48            Self::PhaseAngle(PhaseAngle::CurrentToVoltage(Phase::L3)) => "1-0:81.7.26.255",
49            Self::Voltage(Phase::L1) => "1-0:32.7.0.255",
50            Self::Voltage(Phase::L2) => "1-0:52.7.0.255",
51            Self::Voltage(Phase::L3) => "1-0:72.7.0.255",
52        }
53    }
54
55    fn accepts(self, value: Value) -> bool {
56        matches!(
57            (self, value),
58            (Self::ActivePower(_), Value::Watts(_))
59                | (Self::Current(_), Value::Milliamps(_))
60                | (Self::Frequency, Value::Millihertz(_))
61                | (Self::PhaseAngle(_), Value::Millidegrees(_))
62                | (Self::Voltage(_), Value::Millivolts(_))
63        )
64    }
65}
66
67/// Exact simulator units. Normalize meter scalers before submitting a value.
68/// Angle thresholds use the same signed linear representation as the samples.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum Value {
71    Watts(i64),
72    Milliamps(u32),
73    Millihertz(u32),
74    Millidegrees(i32),
75    Millivolts(u32),
76}
77
78impl Value {
79    fn amount(self) -> i64 {
80        match self {
81            Self::Watts(n) => n,
82            Self::Millivolts(n) | Self::Milliamps(n) | Self::Millihertz(n) => n.into(),
83            Self::Millidegrees(n) => n.into(),
84        }
85    }
86}
87
88impl fmt::Display for Value {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        let unit = match self {
91            Self::Watts(_) => "W",
92            Self::Milliamps(_) => "mA",
93            Self::Millihertz(_) => "mHz",
94            Self::Millidegrees(_) => "millidegrees",
95            Self::Millivolts(_) => "mV",
96        };
97        write!(f, "{} {unit}", self.amount())
98    }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct Channel<'a> {
103    pub meter_id: &'a str,
104    pub quantity: Quantity,
105}
106
107/// Configuration for a single-value block at each commissioned minute.
108pub struct Config<'a> {
109    pub profile_id: &'a str,
110    pub channel: Channel<'a>,
111    /// When set, all reports substitute this reference for the physical meter ID.
112    /// Use a non-identifying profile ID and a separately commissioned pseudonym.
113    pub pseudonym: Option<&'a str>,
114    pub first_utc: i64,
115    pub periodic: bool,
116    pub threshold: Option<Value>,
117}
118
119/// An outward reading. Only the configured reporting reference is carried.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub struct Reading<'a> {
122    pub profile_id: &'a str,
123    pub meter_reference: &'a str,
124    pub quantity: Quantity,
125    pub sampled_utc: i64,
126    pub value: Value,
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub struct Notification<'a> {
131    pub reading: Reading<'a>,
132    pub periodic: bool,
133    pub crossing: Option<Crossing>,
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum Error {
138    EmptyIdentifier,
139    IdentifyingReport,
140    WrongChannel,
141    WrongUnit,
142    UnexpectedSlot,
143}
144
145impl fmt::Display for Error {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        f.write_str(match self {
148            Self::EmptyIdentifier => {
149                "supply nonempty profile, meter and configured pseudonym identifiers"
150            }
151            Self::IdentifyingReport => {
152                "the pseudonymous report must use identifiers distinct from the physical meter ID"
153            }
154            Self::WrongChannel => "meter or grid-state quantity does not match",
155            Self::WrongUnit => "use the commissioned quantity's unit",
156            Self::UnexpectedSlot => "submit the next commissioned 60-second slot",
157        })
158    }
159}
160impl core::error::Error for Error {}
161
162/// Fixed-storage evaluator. Input rejection leaves the current reading and cursor intact.
163pub struct Profile<'a> {
164    profile_id: &'a str,
165    channel: Channel<'a>,
166    meter_reference: &'a str,
167    samples: Samples<Value>,
168}
169
170impl<'a> Profile<'a> {
171    pub fn new(config: Config<'a>) -> Result<Self, Error> {
172        let meter = config.channel.meter_id.trim();
173        let reference = config.pseudonym.unwrap_or(config.channel.meter_id);
174        if meter.is_empty() || config.profile_id.trim().is_empty() || reference.trim().is_empty() {
175            return Err(Error::EmptyIdentifier);
176        }
177        if config.pseudonym.is_some()
178            && (meter == reference.trim() || meter == config.profile_id.trim())
179        {
180            return Err(Error::IdentifyingReport);
181        }
182        if config
183            .threshold
184            .is_some_and(|v| !config.channel.quantity.accepts(v))
185        {
186            return Err(Error::WrongUnit);
187        }
188        Ok(Self {
189            profile_id: config.profile_id,
190            channel: config.channel,
191            meter_reference: reference,
192            samples: Samples::new(
193                config.first_utc,
194                config.periodic,
195                config.threshold.map(Value::amount),
196            ),
197        })
198    }
199
200    /// Submit an authenticated physical channel and its qualified sample.
201    /// A missing or invalid observation is represented by `None`.
202    pub fn record(
203        &mut self,
204        channel: Channel<'_>,
205        sampled_utc: i64,
206        value: Option<Value>,
207    ) -> Result<Option<Notification<'a>>, Error> {
208        if self.channel != channel {
209            return Err(Error::WrongChannel);
210        }
211        if value.is_some_and(|v| !channel.quantity.accepts(v)) {
212            return Err(Error::WrongUnit);
213        }
214        let event = self
215            .samples
216            .record(sampled_utc, value, Value::amount)
217            .map_err(|_| Error::UnexpectedSlot)?;
218        Ok(event.map(|(value, crossing)| Notification {
219            reading: self.reading(sampled_utc, value),
220            periodic: self.samples.periodic,
221            crossing,
222        }))
223    }
224
225    /// Select a fresh sample after the host has authorized the on-demand request.
226    pub fn on_demand(&self, now_utc: i64) -> Option<Reading<'a>> {
227        self.samples
228            .current(now_utc)
229            .map(|(utc, v)| self.reading(utc, v))
230    }
231
232    fn reading(&self, sampled_utc: i64, value: Value) -> Reading<'a> {
233        Reading {
234            profile_id: self.profile_id,
235            meter_reference: self.meter_reference,
236            quantity: self.channel.quantity,
237            sampled_utc,
238            value,
239        }
240    }
241}