1pub use crate::minute::Crossing;
8use crate::minute::Samples;
9use core::fmt;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum ActivePower {
14 Total,
15 L1,
16 L2,
17 L3,
18}
19
20impl ActivePower {
21 pub const fn obis(self) -> &'static str {
22 match self {
23 Self::Total => "1-0:16.7.0.255",
24 Self::L1 => "1-0:36.7.0.255",
25 Self::L2 => "1-0:56.7.0.255",
26 Self::L3 => "1-0:76.7.0.255",
27 }
28 }
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct Channel<'a> {
33 pub meter_id: &'a str,
34 pub quantity: ActivePower,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct Reading<'a> {
39 pub profile_id: &'a str,
40 pub channel: Channel<'a>,
41 pub sampled_utc: i64,
42 pub watts: i64,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct Notification<'a> {
48 pub reading: Reading<'a>,
49 pub periodic: bool,
50 pub crossing: Option<Crossing>,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum Error {
55 EmptyIdentifier,
56 WrongChannel,
57 UnexpectedSlot,
58}
59impl fmt::Display for Error {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 f.write_str(match self {
62 Self::EmptyIdentifier => "supply profile and meter identifiers",
63 Self::WrongChannel => "meter or active-power quantity does not match",
64 Self::UnexpectedSlot => "submit the next commissioned 60-second slot",
65 })
66 }
67}
68impl core::error::Error for Error {}
69
70pub struct Profile<'a> {
72 id: &'a str,
73 channel: Channel<'a>,
74 samples: Samples<i64>,
75}
76
77impl<'a> Profile<'a> {
78 pub fn new(
83 id: &'a str,
84 channel: Channel<'a>,
85 first_utc: i64,
86 periodic: bool,
87 threshold_w: Option<i64>,
88 ) -> Result<Self, Error> {
89 if id.trim().is_empty() || channel.meter_id.trim().is_empty() {
90 return Err(Error::EmptyIdentifier);
91 }
92 Ok(Self {
93 id,
94 channel,
95 samples: Samples::new(first_utc, periodic, threshold_w),
96 })
97 }
98
99 pub fn record(
102 &mut self,
103 channel: Channel<'_>,
104 sampled_utc: i64,
105 watts: Option<i64>,
106 ) -> Result<Option<Notification<'a>>, Error> {
107 if channel != self.channel {
108 return Err(Error::WrongChannel);
109 }
110 let event = self
111 .samples
112 .record(sampled_utc, watts, |w| w)
113 .map_err(|_| Error::UnexpectedSlot)?;
114 Ok(event.map(|(watts, crossing)| Notification {
115 reading: self.reading(sampled_utc, watts),
116 periodic: self.samples.periodic,
117 crossing,
118 }))
119 }
120
121 fn reading(&self, sampled_utc: i64, watts: i64) -> Reading<'a> {
122 Reading {
123 profile_id: self.id,
124 channel: self.channel,
125 sampled_utc,
126 watts,
127 }
128 }
129
130 pub fn on_demand(&self, now_utc: i64) -> Option<Reading<'a>> {
133 self.samples
134 .current(now_utc)
135 .map(|(utc, watts)| self.reading(utc, watts))
136 }
137}