Skip to main content

smgw_core/
taf2.rs

1//! Single-meter TAF 2 register simulation for quarter-hour electricity readings.
2//!
3//! Use one instance per meter, energy direction and evaluation profile. The caller
4//! authenticates the source, classifies its status and supplies the commissioned
5//! register for the entire elapsed period. Store original observations separately.
6
7use core::fmt;
8
9/// A commissioned tariff register (1 through 62 in this simulator).
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub struct TariffRegister(u8);
12
13impl TariffRegister {
14    /// Reserve 0 for the total and 63 for energy with uncertain attribution.
15    pub fn new(number: u8) -> Result<Self, Error> {
16        match number {
17            1..=62 => Ok(Self(number)),
18            _ => Err(Error::InvalidRegister),
19        }
20    }
21
22    /// Numeric identifier within the evaluation profile.
23    pub const fn number(self) -> u8 {
24        self.0
25    }
26}
27
28/// Meter status at a scheduled registration instant, supplied by the caller.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum Reading {
31    /// Timely, validated cumulative energy in Wh.
32    Valid(u64),
33    /// No reading arrived within the receiving window.
34    Missing,
35    /// Clock quality or reception timing precludes using the value.
36    TimeInvalid,
37    /// Timely cumulative Wh carrying a nonfatal meter fault.
38    MeterFault(u64),
39    /// End the trace for this meter under the simulator's stop-on-fatal policy.
40    Fatal,
41}
42
43/// Where to book the measured energy delta, in addition to the total.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum Destination {
46    Tariff(TariffRegister),
47    ErrorRegister,
48}
49
50/// Result of consuming one slot.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum Outcome {
53    Booked { wh: u64, destination: Destination },
54    Deferred,
55    Stopped,
56}
57
58/// A rejected operation leaves all accumulator state intact.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum Error {
61    InvalidRegister,
62    UnalignedBaseline,
63    UnexpectedSlot,
64    DecreasingReading,
65    MeterStopped,
66}
67
68impl fmt::Display for Error {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.write_str(match self {
71            Self::InvalidRegister => "tariff register must be in 1..=62",
72            Self::UnalignedBaseline => "baseline must be on a UTC quarter-hour",
73            Self::UnexpectedSlot => "expected the next UTC quarter-hour",
74            Self::DecreasingReading => "cumulative Wh decreased",
75            Self::MeterStopped => "meter stopped after fatal fault",
76        })
77    }
78}
79
80impl core::error::Error for Error {}
81
82/// Fixed-size derived registers for one continuous, nondecreasing register trace.
83#[derive(Debug)]
84pub struct Registers {
85    wh: [u64; 64],
86    last_slot: i64,
87    last_wh: u64,
88    // Attribution for energy accrued but not yet booked, including fault recovery.
89    pending: Option<Destination>,
90    stopped: bool,
91}
92
93impl Registers {
94    /// Start at a validated cumulative reading. All derived registers start at zero.
95    pub fn new(start_utc: i64, baseline_wh: u64) -> Result<Self, Error> {
96        if start_utc % 900 != 0 {
97            return Err(Error::UnalignedBaseline);
98        }
99        Ok(Self {
100            wh: [0; 64],
101            last_slot: start_utc,
102            last_wh: baseline_wh,
103            pending: None,
104            stopped: false,
105        })
106    }
107
108    pub fn total_wh(&self) -> u64 {
109        self.wh[0]
110    }
111    pub fn error_wh(&self) -> u64 {
112        self.wh[63]
113    }
114    pub fn tariff_wh(&self, tariff: TariffRegister) -> u64 {
115        self.wh[usize::from(tariff.0)]
116    }
117
118    /// Submit one elapsed period, even if its reading is missing. At a switch on
119    /// the closing boundary, supply the outgoing register. After `Fatal`, start
120    /// a new instance for the replacement meter.
121    pub fn record(
122        &mut self,
123        end_utc: i64,
124        tariff: TariffRegister,
125        reading: Reading,
126    ) -> Result<Outcome, Error> {
127        if self.stopped {
128            return Err(Error::MeterStopped);
129        }
130        if self.last_slot.checked_add(900) != Some(end_utc) {
131            return Err(Error::UnexpectedSlot);
132        }
133        let period = Destination::Tariff(tariff);
134        let mut destination = match self.pending {
135            Some(previous) if previous != period => Destination::ErrorRegister,
136            _ => period,
137        };
138        let outcome = match reading {
139            Reading::Missing | Reading::TimeInvalid => {
140                self.pending = Some(destination);
141                Outcome::Deferred
142            }
143            Reading::Fatal => {
144                self.stopped = true;
145                Outcome::Stopped
146            }
147            Reading::Valid(value) | Reading::MeterFault(value) => {
148                let delta = value
149                    .checked_sub(self.last_wh)
150                    .ok_or(Error::DecreasingReading)?;
151                let fault = matches!(reading, Reading::MeterFault(_));
152                if fault {
153                    destination = Destination::ErrorRegister;
154                }
155                let index = match destination {
156                    Destination::Tariff(id) => usize::from(id.0),
157                    Destination::ErrorRegister => 63,
158                };
159                // All deltas telescope to value - baseline_wh, which fits in u64.
160                self.wh[0] += delta;
161                self.wh[index] += delta;
162                self.last_wh = value;
163                self.pending = fault.then_some(Destination::ErrorRegister);
164                Outcome::Booked {
165                    wh: delta,
166                    destination,
167                }
168            }
169        };
170        self.last_slot = end_utc;
171        Ok(outcome)
172    }
173}