Skip to main content

smgw_core/
taf9.rs

1//! TAF 9 single-channel, instantaneous active-power simulation.
2//!
3//! Supply qualified meter measurements in signed whole watts, using the commissioned
4//! meter's sign convention for both samples and threshold. The caller authenticates
5//! the meter, authorizes requests and handles recipient logging and delivery.
6
7pub use crate::minute::Crossing;
8use crate::minute::Samples;
9use core::fmt;
10
11/// Active-power quantities in BSI TR-03109-1 v1.1, table 4.7.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum ActivePower {
14    Total,
15    L1,
16    L2,
17    L3,
18}
19
20impl ActivePower {
21    pub const fn obis(self) -> &'static str {
22        match self {
23            Self::Total => "1-0:16.7.0.255",
24            Self::L1 => "1-0:36.7.0.255",
25            Self::L2 => "1-0:56.7.0.255",
26            Self::L3 => "1-0:76.7.0.255",
27        }
28    }
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct Channel<'a> {
33    pub meter_id: &'a str,
34    pub quantity: ActivePower,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct Reading<'a> {
39    pub profile_id: &'a str,
40    pub channel: Channel<'a>,
41    pub sampled_utc: i64,
42    pub watts: i64,
43}
44
45/// One measurement may satisfy both configured triggers.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct Notification<'a> {
48    pub reading: Reading<'a>,
49    pub periodic: bool,
50    pub crossing: Option<Crossing>,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum Error {
55    EmptyIdentifier,
56    WrongChannel,
57    UnexpectedSlot,
58}
59impl fmt::Display for Error {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str(match self {
62            Self::EmptyIdentifier => "supply profile and meter identifiers",
63            Self::WrongChannel => "meter or active-power quantity does not match",
64            Self::UnexpectedSlot => "submit the next commissioned 60-second slot",
65        })
66    }
67}
68impl core::error::Error for Error {}
69
70/// Single-value profile with a 60-second reception and optional 60-second reporting period.
71pub struct Profile<'a> {
72    id: &'a str,
73    channel: Channel<'a>,
74    samples: Samples<i64>,
75}
76
77impl<'a> Profile<'a> {
78    /// Commission the first sample instant, periodic reporting and an optional
79    /// threshold in the same signed watts as the meter. The first valid sample
80    /// sets the baseline. A crossing occurs when a later sample moves strictly
81    /// above or below the threshold from the other side or from equality.
82    pub fn new(
83        id: &'a str,
84        channel: Channel<'a>,
85        first_utc: i64,
86        periodic: bool,
87        threshold_w: Option<i64>,
88    ) -> Result<Self, Error> {
89        if id.trim().is_empty() || channel.meter_id.trim().is_empty() {
90            return Err(Error::EmptyIdentifier);
91        }
92        Ok(Self {
93            id,
94            channel,
95            samples: Samples::new(first_utc, periodic, threshold_w),
96        })
97    }
98
99    /// Submit each scheduled sample, including gaps as `None`. A gap invalidates
100    /// on-demand output and breaks the comparison with the previous sample.
101    pub fn record(
102        &mut self,
103        channel: Channel<'_>,
104        sampled_utc: i64,
105        watts: Option<i64>,
106    ) -> Result<Option<Notification<'a>>, Error> {
107        if channel != self.channel {
108            return Err(Error::WrongChannel);
109        }
110        let event = self
111            .samples
112            .record(sampled_utc, watts, |w| w)
113            .map_err(|_| Error::UnexpectedSlot)?;
114        Ok(event.map(|(watts, crossing)| Notification {
115            reading: self.reading(sampled_utc, watts),
116            periodic: self.samples.periodic,
117            crossing,
118        }))
119    }
120
121    fn reading(&self, sampled_utc: i64, watts: i64) -> Reading<'a> {
122        Reading {
123            profile_id: self.id,
124            channel: self.channel,
125            sampled_utc,
126            watts,
127        }
128    }
129
130    /// Select the latest valid reading for an authorized request. It expires at
131    /// the next reception slot even when the caller has stopped submitting data.
132    pub fn on_demand(&self, now_utc: i64) -> Option<Reading<'a>> {
133        self.samples
134            .current(now_utc)
135            .map(|(utc, watts)| self.reading(utc, watts))
136    }
137}