Skip to main content

smgw_core/
taf7.rs

1//! Bounded, in-memory TAF 7 series for one commissioned active-energy channel.
2//!
3//! Each slot retains the original cumulative Wh, source time and caller-classified
4//! quality, or an explicit gap. Archive the block before starting the next one.
5
6use crate::taf2;
7use core::fmt;
8
9/// Direction of cumulative active energy, normalized to whole watt-hours.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum Direction {
12    Import,
13    Export,
14}
15
16/// Identity supplied by a caller that has authenticated the meter.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct Channel<'a> {
19    pub meter_id: &'a str,
20    pub direction: Direction,
21}
22
23/// Registration cadence for this electricity simulation.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Period {
26    QuarterHour,
27    Hour,
28}
29
30impl Period {
31    pub const fn seconds(self) -> i64 {
32        match self {
33            Self::QuarterHour => 900,
34            Self::Hour => 3600,
35        }
36    }
37}
38
39/// Status assigned by the caller using the source and reception evidence.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum Quality {
42    Valid,
43    TimeInvalid,
44    MeterFault,
45    Fatal,
46}
47
48/// Original observation for a scheduled instant. Source and scheduled times are Unix seconds.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Observation {
51    Missing,
52    Received {
53        source_utc: i64,
54        cumulative_wh: u64,
55        quality: Quality,
56    },
57}
58
59impl From<Observation> for taf2::Reading {
60    /// Project a slot's quality and value for register arithmetic. The caller
61    /// supplies the commissioned tariff and enforces the TAF 2 quarter-hour grid.
62    fn from(value: Observation) -> Self {
63        match value {
64            Observation::Missing => Self::Missing,
65            Observation::Received {
66                cumulative_wh,
67                quality,
68                ..
69            } => match quality {
70                Quality::Valid => Self::Valid(cumulative_wh),
71                Quality::TimeInvalid => Self::TimeInvalid,
72                Quality::MeterFault => Self::MeterFault(cumulative_wh),
73                Quality::Fatal => Self::Fatal,
74            },
75        }
76    }
77}
78
79/// One original observation, indexed by its scheduled registration instant.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct Entry {
82    pub scheduled_utc: i64,
83    pub observation: Observation,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum Error {
88    EmptyMeterId,
89    EmptyBlock,
90    UnalignedStart,
91    TimestampOverflow,
92    WrongChannel,
93    UnexpectedSlot,
94    Full,
95}
96
97impl fmt::Display for Error {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.write_str(match self {
100            Self::EmptyMeterId => "supply a meter identifier",
101            Self::EmptyBlock => "the block must hold at least one slot",
102            Self::UnalignedStart => "first slot must align to the UTC registration grid",
103            Self::TimestampOverflow => "last slot is outside the representable UTC range",
104            Self::WrongChannel => "observation belongs to a different meter or energy direction",
105            Self::UnexpectedSlot => {
106                "submit the next scheduled slot, including missing observations"
107            }
108            Self::Full => "series is full; archive it and start a new block",
109        })
110    }
111}
112impl core::error::Error for Error {}
113
114/// Append-only block of at most N entries. Every slot uses fixed storage, including gaps.
115pub struct Series<'a, const N: usize> {
116    channel: Channel<'a>,
117    period: Period,
118    next: i64,
119    entries: [Entry; N],
120    len: usize,
121}
122
123impl<'a, const N: usize> Series<'a, N> {
124    /// Start an empty block at its first reportable instant.
125    pub fn new(channel: Channel<'a>, period: Period, first_utc: i64) -> Result<Self, Error> {
126        if channel.meter_id.trim().is_empty() {
127            return Err(Error::EmptyMeterId);
128        }
129        let last = N.checked_sub(1).ok_or(Error::EmptyBlock)?;
130        if first_utc % period.seconds() != 0 {
131            return Err(Error::UnalignedStart);
132        }
133        let last_utc = i128::from(first_utc) + last as i128 * i128::from(period.seconds());
134        i64::try_from(last_utc).map_err(|_| Error::TimestampOverflow)?;
135        Ok(Self {
136            channel,
137            period,
138            next: first_utc,
139            entries: [Entry {
140                scheduled_utc: 0,
141                observation: Observation::Missing,
142            }; N],
143            len: 0,
144        })
145    }
146
147    pub fn channel(&self) -> Channel<'a> {
148        self.channel
149    }
150    pub fn period(&self) -> Period {
151        self.period
152    }
153    pub fn next_slot(&self) -> Option<i64> {
154        (self.len < N).then_some(self.next)
155    }
156    /// Accepted entries in chronological order. A refused append leaves this slice unchanged.
157    pub fn entries(&self) -> &[Entry] {
158        &self.entries[..self.len]
159    }
160
161    /// Append exactly one slot. Submit a missing observation explicitly when no sample arrives.
162    pub fn record(
163        &mut self,
164        channel: Channel<'_>,
165        scheduled_utc: i64,
166        observation: Observation,
167    ) -> Result<(), Error> {
168        if channel != self.channel {
169            return Err(Error::WrongChannel);
170        }
171        let next = self.next_slot().ok_or(Error::Full)?;
172        if scheduled_utc != next {
173            return Err(Error::UnexpectedSlot);
174        }
175        self.entries[self.len] = Entry {
176            scheduled_utc,
177            observation,
178        };
179        self.len += 1;
180        if self.len < N {
181            self.next += self.period.seconds();
182        }
183        Ok(())
184    }
185}