1pub use crate::{registration::Period, taf7::Direction, taf14::Quadrant};
7use core::fmt;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum Register {
12 Active(Direction),
13 Reactive(Quadrant),
14}
15
16impl Register {
17 const fn group_c(self) -> u8 {
18 match self {
19 Self::Active(Direction::Import) => 1,
20 Self::Active(Direction::Export) => 2,
21 Self::Reactive(Quadrant::R1) => 5,
22 Self::Reactive(Quadrant::R2) => 6,
23 Self::Reactive(Quadrant::R3) => 7,
24 Self::Reactive(Quadrant::R4) => 8,
25 }
26 }
27
28 pub const fn energy_obis(self) -> [u8; 6] {
29 [1, 0, self.group_c(), 8, 0, 255]
30 }
31 pub const fn demand_obis(self) -> [u8; 6] {
32 [1, 0, self.group_c(), 29, 0, 255]
33 }
34 pub const fn maximum_obis(self) -> [u8; 6] {
35 [1, 0, self.group_c(), 6, 0, 255]
36 }
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct Channel<'a> {
41 pub meter_id: &'a str,
42 pub register: Register,
43 pub scale: i8,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
49pub enum Status {
50 Valid,
51 Warning,
52 Missing,
53 TemporaryError,
54 PermanentError,
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct Reading {
59 pub count: u64,
60 pub status: Status,
61 pub validated_for_billing: bool,
62}
63
64impl Reading {
65 pub const fn valid(count: u64) -> Self {
66 Self {
67 count,
68 status: Status::Valid,
69 validated_for_billing: true,
70 }
71 }
72
73 pub const MISSING: Self = Self {
74 count: 0,
75 status: Status::Missing,
76 validated_for_billing: false,
77 };
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct Demand {
82 pub count: u128,
84 pub status: Status,
85 pub validated_for_billing: bool,
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct Peak {
90 pub end_utc: i64,
91 pub demand: Demand,
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub struct Interval<'a> {
96 pub profile_id: &'a str,
97 pub channel: Channel<'a>,
98 pub end_utc: i64,
99 pub closing: Reading,
101 pub mean: Demand,
102 pub peak: Option<Peak>,
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum Error {
108 EmptyIdentifier,
109 InvalidWindow,
110 WrongChannel,
111 UnexpectedSlot,
112 CounterDecreased,
113}
114
115impl fmt::Display for Error {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.write_str(match self {
118 Self::EmptyIdentifier => "supply profile and meter identifiers",
119 Self::InvalidWindow => {
120 "supply ordered boundaries aligned to a 5- or 15-minute electricity interval"
121 }
122 Self::WrongChannel => "meter, register or scale does not match",
123 Self::UnexpectedSlot => "time lies outside the expected registration interval",
124 Self::CounterDecreased => {
125 "qualify the register reset or correct the decreasing reading"
126 }
127 })
128 }
129}
130impl core::error::Error for Error {}
131
132pub struct Profile<'a> {
134 id: &'a str,
135 channel: Channel<'a>,
136 period: Period,
137 close: i64,
138 next: Option<i64>,
139 previous: Option<Reading>,
140 peak: Option<Peak>,
141 permanent_fault: bool,
142}
143
144impl<'a> Profile<'a> {
145 pub fn new(
146 id: &'a str,
147 channel: Channel<'a>,
148 period: Period,
149 open_utc: i64,
150 close_utc: i64,
151 ) -> Result<Self, Error> {
152 if id.trim().is_empty() || channel.meter_id.trim().is_empty() {
153 return Err(Error::EmptyIdentifier);
154 }
155 let seconds = period.seconds();
156 if period == Period::Hour
157 || open_utc >= close_utc
158 || open_utc % seconds != 0
159 || close_utc % seconds != 0
160 {
161 return Err(Error::InvalidWindow);
162 }
163 Ok(Self {
164 id,
165 channel,
166 period,
167 close: close_utc,
168 next: Some(open_utc),
169 previous: None,
170 peak: None,
171 permanent_fault: false,
172 })
173 }
174
175 pub fn record(
178 &mut self,
179 channel: Channel<'_>,
180 utc: i64,
181 reading: Reading,
182 ) -> Result<Option<Interval<'a>>, Error> {
183 if channel != self.channel {
184 return Err(Error::WrongChannel);
185 }
186 if self.next != Some(utc) {
187 return Err(Error::UnexpectedSlot);
188 }
189 let mut reading = reading;
190 if self.permanent_fault && reading.status != Status::Missing {
191 reading.status = Status::PermanentError;
192 }
193 reading.validated_for_billing &= reading.status <= Status::Warning;
194 let mean = self
195 .previous
196 .map(|previous| self.derive(previous, reading, self.period.seconds()))
197 .transpose()?;
198 self.permanent_fault |= reading.status == Status::PermanentError;
199 self.previous = Some(reading);
200 self.next = if utc == self.close {
201 None
202 } else {
203 utc.checked_add(self.period.seconds())
204 };
205 Ok(mean.map(|mean| {
206 if mean.count > self.peak.map_or(0, |p| p.demand.count) {
207 self.peak = Some(Peak {
208 end_utc: utc,
209 demand: mean,
210 });
211 }
212 Interval {
213 profile_id: self.id,
214 channel: self.channel,
215 end_utc: utc,
216 closing: reading,
217 mean,
218 peak: self.peak,
219 }
220 }))
221 }
222
223 pub fn provisional(
225 &self,
226 channel: Channel<'_>,
227 utc: i64,
228 reading: Reading,
229 ) -> Result<Demand, Error> {
230 if channel != self.channel {
231 return Err(Error::WrongChannel);
232 }
233 let previous = self.previous.ok_or(Error::UnexpectedSlot)?;
234 let next = self.next.ok_or(Error::UnexpectedSlot)?;
235 let start = next - self.period.seconds();
236 if utc <= start || utc >= next {
237 return Err(Error::UnexpectedSlot);
238 }
239 self.derive(previous, reading, utc - start)
240 }
241
242 fn derive(&self, previous: Reading, current: Reading, seconds: i64) -> Result<Demand, Error> {
243 let status = if self.permanent_fault {
244 Status::PermanentError
245 } else {
246 previous.status.max(current.status)
247 };
248 let usable = status <= Status::Warning;
249 let count = if usable {
250 let delta = current
251 .count
252 .checked_sub(previous.count)
253 .ok_or(Error::CounterDecreased)?;
254 let seconds = seconds as u128;
255 (u128::from(delta) * 3600 + seconds / 2) / seconds
256 } else {
257 0
258 };
259 Ok(Demand {
260 count,
261 status,
262 validated_for_billing: usable
263 && previous.validated_for_billing
264 && current.validated_for_billing,
265 })
266 }
267}