1pub use crate::{minute::Crossing, taf7::Direction, taf9::ActivePower, taf10::Phase};
7use core::fmt;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum Quadrant {
11 R1,
12 R2,
13 R3,
14 R4,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Quantity {
20 ActiveEnergy(Direction, Option<Phase>),
21 ReactiveEnergy(Quadrant),
22 ActivePower(ActivePower),
23}
24
25impl Quantity {
26 pub const fn obis(self) -> &'static str {
27 use Direction::{Export, Import};
28 use Phase::{L1, L2, L3};
29 match self {
30 Self::ActiveEnergy(Import, None) => "1-0:1.8.0.255",
31 Self::ActiveEnergy(Import, Some(L1)) => "1-0:21.8.0.255",
32 Self::ActiveEnergy(Import, Some(L2)) => "1-0:41.8.0.255",
33 Self::ActiveEnergy(Import, Some(L3)) => "1-0:61.8.0.255",
34 Self::ActiveEnergy(Export, None) => "1-0:2.8.0.255",
35 Self::ActiveEnergy(Export, Some(L1)) => "1-0:22.8.0.255",
36 Self::ActiveEnergy(Export, Some(L2)) => "1-0:42.8.0.255",
37 Self::ActiveEnergy(Export, Some(L3)) => "1-0:62.8.0.255",
38 Self::ReactiveEnergy(Quadrant::R1) => "1-0:5.8.0.255",
39 Self::ReactiveEnergy(Quadrant::R2) => "1-0:6.8.0.255",
40 Self::ReactiveEnergy(Quadrant::R3) => "1-0:7.8.0.255",
41 Self::ReactiveEnergy(Quadrant::R4) => "1-0:8.8.0.255",
42 Self::ActivePower(power) => power.obis(),
43 }
44 }
45
46 fn accepts(self, value: Value) -> bool {
47 matches!(
48 (self, value),
49 (Self::ActiveEnergy(..), Value::WattHours(_))
50 | (Self::ReactiveEnergy(_), Value::VarHours(_))
51 | (Self::ActivePower(_), Value::Watts(_))
52 )
53 }
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Value {
59 WattHours(u64),
60 VarHours(u64),
61 Watts(i64),
62}
63
64impl Value {
65 fn amount(self) -> i128 {
66 match self {
67 Self::WattHours(value) | Self::VarHours(value) => value.into(),
68 Self::Watts(value) => value.into(),
69 }
70 }
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct Channel<'a> {
75 pub meter_id: &'a str,
76 pub quantity: Quantity,
77}
78
79#[derive(Debug, Clone, Copy)]
80pub struct Config<'a> {
81 pub profile_id: &'a str,
82 pub channel: Channel<'a>,
83 pub first_utc: i64,
85 pub reception_seconds: u32,
86 pub delivery_every_slots: Option<usize>,
88 pub thresholds: &'a [Value],
90}
91
92impl<'a> Config<'a> {
93 pub const fn new(profile_id: &'a str, channel: Channel<'a>, first_utc: i64) -> Self {
95 Self {
96 profile_id,
97 channel,
98 first_utc,
99 reception_seconds: 60,
100 delivery_every_slots: None,
101 thresholds: &[],
102 }
103 }
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct Sample {
108 pub sampled_utc: i64,
109 pub value: Value,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub struct ThresholdCrossing<'a> {
115 pub sampled_utc: i64,
116 pub direction: Crossing,
117 pub thresholds: &'a [Value],
118}
119
120fn crossed(thresholds: &[Value], previous: Value, sample: Sample) -> Option<ThresholdCrossing<'_>> {
121 let previous = previous.amount();
122 let current = sample.value.amount();
123 let (direction, first, end) = match current.cmp(&previous) {
124 core::cmp::Ordering::Greater => (
125 Crossing::Above,
126 thresholds.partition_point(|t| t.amount() < previous),
127 thresholds.partition_point(|t| t.amount() < current),
128 ),
129 core::cmp::Ordering::Less => (
130 Crossing::Below,
131 thresholds.partition_point(|t| t.amount() <= current),
132 thresholds.partition_point(|t| t.amount() <= previous),
133 ),
134 core::cmp::Ordering::Equal => return None,
135 };
136 (first < end).then(|| ThresholdCrossing {
137 sampled_utc: sample.sampled_utc,
138 direction,
139 thresholds: &thresholds[first..end],
140 })
141}
142
143#[derive(Debug, PartialEq, Eq)]
144pub struct Block<'a> {
145 pub profile_id: &'a str,
146 pub channel: Channel<'a>,
147 pub samples: &'a [Sample],
149 pub omitted: u64,
151 pub periodic: bool,
152 pub crossing: Option<ThresholdCrossing<'a>>,
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub enum Error {
157 EmptyIdentifier,
158 InvalidCapacity,
159 InvalidPeriod,
160 UnorderedThresholds,
161 WrongUnit,
162 WrongChannel,
163 UnexpectedSlot,
164}
165
166impl fmt::Display for Error {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 f.write_str(match self {
169 Self::EmptyIdentifier => "supply nonempty profile and meter identifiers",
170 Self::InvalidCapacity => {
171 "provide storage for at least one sample and the entire configured delivery period"
172 }
173 Self::InvalidPeriod => "reception and delivery periods must be positive",
174 Self::UnorderedThresholds => "supply thresholds in strictly increasing order",
175 Self::WrongUnit => "use the commissioned channel's unit",
176 Self::WrongChannel => "meter or quantity does not match the commissioned channel",
177 Self::UnexpectedSlot => "submit the next commissioned reception slot",
178 })
179 }
180}
181
182impl core::error::Error for Error {}
183
184pub struct Profile<'a, const N: usize> {
187 config: Config<'a>,
188 next_utc: Option<i64>,
189 slots_left: Option<usize>,
190 previous: Option<Value>,
191 buffer: [Sample; N],
192 write: usize,
193 len: usize,
194 omitted: u64,
195}
196
197impl<'a, const N: usize> Profile<'a, N> {
198 pub fn new(config: Config<'a>) -> Result<Self, Error> {
199 if config.profile_id.trim().is_empty() || config.channel.meter_id.trim().is_empty() {
200 return Err(Error::EmptyIdentifier);
201 }
202 if config.reception_seconds == 0 || config.delivery_every_slots == Some(0) {
203 return Err(Error::InvalidPeriod);
204 }
205 if N == 0 || config.delivery_every_slots.is_some_and(|slots| slots > N) {
206 return Err(Error::InvalidCapacity);
207 }
208 if config
209 .thresholds
210 .iter()
211 .any(|&t| !config.channel.quantity.accepts(t))
212 {
213 return Err(Error::WrongUnit);
214 }
215 if config
216 .thresholds
217 .windows(2)
218 .any(|pair| pair[0].amount() >= pair[1].amount())
219 {
220 return Err(Error::UnorderedThresholds);
221 }
222 Ok(Self {
223 config,
224 next_utc: Some(config.first_utc),
225 slots_left: config.delivery_every_slots,
226 previous: None,
227 buffer: [Sample {
228 sampled_utc: 0,
229 value: Value::Watts(0),
230 }; N],
231 write: 0,
232 len: 0,
233 omitted: 0,
234 })
235 }
236
237 pub fn record(
241 &mut self,
242 channel: Channel<'_>,
243 utc: i64,
244 value: Option<Value>,
245 ) -> Result<Option<Block<'_>>, Error> {
246 if channel != self.config.channel {
247 return Err(Error::WrongChannel);
248 }
249 if self.next_utc != Some(utc) {
250 return Err(Error::UnexpectedSlot);
251 }
252 if value.is_some_and(|v| !channel.quantity.accepts(v)) {
253 return Err(Error::WrongUnit);
254 }
255
256 self.next_utc = utc.checked_add(self.config.reception_seconds.into());
257 let periodic = self.slots_left == Some(1);
258 self.slots_left = if periodic {
259 self.config.delivery_every_slots
260 } else {
261 self.slots_left.map(|s| s - 1)
262 };
263
264 let previous = core::mem::replace(&mut self.previous, value);
265 let crossing = if let Some(value) = value {
266 let sample = Sample {
267 sampled_utc: utc,
268 value,
269 };
270 self.buffer[self.write] = sample;
271 self.write = (self.write + 1) % N;
272 if self.len == N {
273 self.omitted += 1;
274 } else {
275 self.len += 1;
276 }
277 previous.and_then(|prev| crossed(self.config.thresholds, prev, sample))
278 } else {
279 None
280 };
281
282 let immediate =
283 self.config.delivery_every_slots.is_none() && self.config.thresholds.is_empty();
284 if self.len == 0 || !(periodic || immediate || crossing.is_some()) {
285 return Ok(None);
286 }
287 if self.len == N {
288 self.buffer.rotate_left(self.write);
289 }
290 self.write = 0;
291 let len = core::mem::take(&mut self.len);
292 Ok(Some(Block {
293 profile_id: self.config.profile_id,
294 channel: self.config.channel,
295 samples: &self.buffer[..len],
296 omitted: core::mem::take(&mut self.omitted),
297 periodic,
298 crossing,
299 }))
300 }
301}