Skip to main content

smgw_core/
taf1.rs

1//! TAF 1 selection of one cumulative electricity reading per billing close.
2//!
3//! Commission the monthly or multi-month billing calendar in local time and
4//! pass its resolved closing instants in UTC. The caller authenticates the
5//! meter, archives original observations, and authorizes and signs delivery.
6
7use crate::taf7::{Channel, Entry, Observation, Quality};
8use core::fmt;
9
10/// Local report for one commissioned quantity at the end of a billing period.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct ClosingReading<'a> {
13    pub profile_id: &'a str,
14    pub channel: Channel<'a>,
15    /// Scheduled end of the billing period, in Unix seconds.
16    pub end_utc: i64,
17    /// Absolute register reading, normalized to whole watt-hours.
18    pub cumulative_wh: u64,
19}
20
21/// Rejection during commissioning or finalization. A rejected close can be retried.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Error {
24    EmptyProfileId,
25    EmptyMeterId,
26    InvalidSchedule,
27    WrongChannel,
28    UnexpectedClose,
29    ScheduleComplete,
30}
31
32impl fmt::Display for Error {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        f.write_str(match self {
35            Self::EmptyProfileId => "supply an evaluation profile identifier",
36            Self::EmptyMeterId => "supply a meter identifier",
37            Self::InvalidSchedule => {
38                "supply a nonempty, strictly increasing list of billing closes"
39            }
40            Self::WrongChannel => "closing observation belongs to a different meter or direction",
41            Self::UnexpectedClose => "expected the next commissioned billing close",
42            Self::ScheduleComplete => "all commissioned billing periods have been finalized",
43        })
44    }
45}
46
47impl core::error::Error for Error {}
48
49/// Single-channel evaluator. Each accepted close is consumed once per instance.
50pub struct Profile<'a> {
51    id: &'a str,
52    channel: Channel<'a>,
53    remaining: &'a [i64],
54}
55
56impl<'a> Profile<'a> {
57    /// Commission explicit UTC closes. Calendar and profile validity are resolved upstream.
58    pub fn new(id: &'a str, channel: Channel<'a>, closes_utc: &'a [i64]) -> Result<Self, Error> {
59        if id.trim().is_empty() {
60            return Err(Error::EmptyProfileId);
61        }
62        if channel.meter_id.trim().is_empty() {
63            return Err(Error::EmptyMeterId);
64        }
65        if closes_utc.is_empty() || closes_utc.windows(2).any(|pair| pair[0] >= pair[1]) {
66            return Err(Error::InvalidSchedule);
67        }
68        Ok(Self {
69            id,
70            channel,
71            remaining: closes_utc,
72        })
73    }
74
75    pub fn next_close(&self) -> Option<i64> {
76        self.remaining.first().copied()
77    }
78
79    /// Finalize an exact scheduled close. A valid reading produces one report.
80    /// A missing or invalid observation consumes the period and returns `Ok(None)`.
81    /// An error leaves the period open. Finalize only after reception is complete.
82    pub fn close(
83        &mut self,
84        channel: Channel<'_>,
85        entry: Entry,
86    ) -> Result<Option<ClosingReading<'a>>, Error> {
87        let (&end_utc, rest) = self
88            .remaining
89            .split_first()
90            .ok_or(Error::ScheduleComplete)?;
91        if channel != self.channel {
92            return Err(Error::WrongChannel);
93        }
94        if entry.scheduled_utc != end_utc {
95            return Err(Error::UnexpectedClose);
96        }
97        self.remaining = rest;
98        Ok(match entry.observation {
99            Observation::Received {
100                quality: Quality::Valid,
101                cumulative_wh,
102                ..
103            } => Some(ClosingReading {
104                profile_id: self.id,
105                channel: self.channel,
106                end_utc,
107                cumulative_wh,
108            }),
109            _ => None,
110        })
111    }
112}