1pub use crate::registration::Period;
7use core::fmt;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct Channel<'a> {
11 pub meter_id: &'a str,
12 pub obis: [u8; 6],
14 pub unit: &'a str,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct Record {
20 pub reference_utc: i64,
22 pub measured_utc: i64,
24 pub coefficient: i128,
26 pub scale: i8,
27 pub meter_status: Option<u32>,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Capture {
32 Inserted,
33 Duplicate,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Error {
38 EmptyIdentifier,
39 InvalidChannel,
40 InvalidWindow,
41 WrongChannel,
42 UnexpectedSlot,
43 Conflict,
44}
45
46impl fmt::Display for Error {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 f.write_str(match self {
49 Self::EmptyIdentifier => "supply profile and meter identifiers",
50 Self::InvalidChannel => {
51 "commission an electricity or gas OBIS channel with its unit, B=0 and F=255"
52 }
53 Self::InvalidWindow => {
54 "supply a nonempty representable registration window and an allowed period"
55 }
56 Self::WrongChannel => "meter, OBIS or unit does not match",
57 Self::UnexpectedSlot => "reference timestamp is outside the commissioned slot grid",
58 Self::Conflict => {
59 "a different record already uses this reference or measurement timestamp"
60 }
61 })
62 }
63}
64impl core::error::Error for Error {}
65
66pub struct Profile<'a, const N: usize> {
69 id: &'a str,
70 channel: Channel<'a>,
71 period: Period,
72 first: i64,
73 slots: [Option<Record>; N],
74}
75
76pub struct CaptureBatch<'p, 'a, const N: usize> {
78 profile: &'p mut Profile<'a, N>,
79 occupied: [bool; N],
80 committed: bool,
81}
82
83impl<const N: usize> CaptureBatch<'_, '_, N> {
84 pub fn capture(&mut self, channel: Channel<'_>, record: Record) -> Result<Capture, Error> {
86 self.profile.capture(channel, record)
87 }
88
89 pub fn period(&self) -> Period {
91 self.profile.period()
92 }
93}
94
95impl<const N: usize> Drop for CaptureBatch<'_, '_, N> {
96 fn drop(&mut self) {
97 if !self.committed {
98 for (slot, existed) in self.profile.slots.iter_mut().zip(&self.occupied) {
99 if !existed {
100 *slot = None;
101 }
102 }
103 }
104 }
105}
106
107impl<'a, const N: usize> Profile<'a, N> {
108 pub fn new(
110 id: &'a str,
111 channel: Channel<'a>,
112 period: Period,
113 first_utc: i64,
114 ) -> Result<Self, Error> {
115 if id.trim().is_empty() || channel.meter_id.trim().is_empty() {
116 return Err(Error::EmptyIdentifier);
117 }
118 if !matches!(channel.obis, [1 | 7, 0, _, _, _, 255]) || channel.unit.trim().is_empty() {
119 return Err(Error::InvalidChannel);
120 }
121 let last = N.checked_sub(1).ok_or(Error::InvalidWindow)?;
122 if (channel.obis[0] == 1 && period == Period::Hour)
123 || i128::from(first_utc) + last as i128 * i128::from(period.seconds())
124 > i128::from(i64::MAX)
125 {
126 return Err(Error::InvalidWindow);
127 }
128 Ok(Self {
129 id,
130 channel,
131 period,
132 first: first_utc,
133 slots: [None; N],
134 })
135 }
136
137 pub fn profile_id(&self) -> &'a str {
138 self.id
139 }
140 pub fn channel(&self) -> Channel<'a> {
141 self.channel
142 }
143
144 pub fn window(&self) -> core::ops::RangeInclusive<i64> {
146 let last = i128::from(self.first) + (N - 1) as i128 * i128::from(self.period.seconds());
148 self.first..=last as i64
149 }
150
151 pub fn period(&self) -> Period {
153 self.period
154 }
155
156 pub fn capture_batch<T, E>(
159 &mut self,
160 capture: impl FnOnce(&mut CaptureBatch<'_, '_, N>) -> Result<T, E>,
161 ) -> Result<T, E> {
162 let mut batch = CaptureBatch {
163 occupied: core::array::from_fn(|i| self.slots[i].is_some()),
164 profile: self,
165 committed: false,
166 };
167 let result = capture(&mut batch);
168 batch.committed = result.is_ok();
169 result
170 }
171
172 pub fn capture(&mut self, channel: Channel<'_>, record: Record) -> Result<Capture, Error> {
174 if channel != self.channel {
175 return Err(Error::WrongChannel);
176 }
177 let offset = i128::from(record.reference_utc) - i128::from(self.first);
178 let seconds = i128::from(self.period.seconds());
179 if offset < 0 || offset % seconds != 0 {
180 return Err(Error::UnexpectedSlot);
181 }
182 let index = usize::try_from(offset / seconds).map_err(|_| Error::UnexpectedSlot)?;
183 match self.slots.get(index).ok_or(Error::UnexpectedSlot)? {
184 Some(original) if *original == record => return Ok(Capture::Duplicate),
185 Some(_) => return Err(Error::Conflict),
186 None => {}
187 }
188 if self
189 .records()
190 .any(|r| r.measured_utc == record.measured_utc)
191 {
192 return Err(Error::Conflict);
193 }
194 self.slots[index] = Some(record);
195 Ok(Capture::Inserted)
196 }
197
198 pub fn records(&self) -> impl Iterator<Item = &Record> {
200 self.slots.iter().flatten()
201 }
202
203 pub fn missing(&self) -> impl Iterator<Item = i64> + '_ {
205 self.slots
206 .iter()
207 .enumerate()
208 .filter(|(_, r)| r.is_none())
209 .map(|(i, _)| {
210 (i128::from(self.first) + i as i128 * i128::from(self.period.seconds())) as i64
211 })
212 }
213}