1use std::collections::{BTreeMap, HashMap, VecDeque};
6
7use flexpool_core::AssetId;
8use serde::Serialize;
9
10use crate::quality::{Flags, Quality, Quantity, Reading, classify};
11use crate::{QUARTER_SECS, quarter_start};
12
13pub const RECENT_SECS: i64 = 900;
15pub const RECENT_MAX: usize = 900;
17pub const QUARTERS_MAX: usize = 192;
19pub const CLOCK_STEP_SECS: i64 = 60;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Pushed {
26 Stored,
28 Dropped,
30 Reset,
32 Undeclared,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
38pub struct QuarterAggregate {
39 pub start: i64,
41 pub mean_power_kw: Option<f64>,
43 pub last_soc: Option<f64>,
45 pub good_share: f64,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
51pub struct Recent {
52 pub at: i64,
54 pub power_kw: Option<f64>,
56 pub soc: Option<f64>,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
62pub struct AssetNow {
63 pub power: Option<Reading>,
65 pub soc: Option<Reading>,
67 pub offline_since: Option<i64>,
69 pub quality: Quality,
71}
72
73impl AssetNow {
74 #[must_use]
76 pub const fn offline(since: Option<i64>) -> Self {
77 Self {
78 power: None,
79 soc: None,
80 offline_since: since,
81 quality: Quality::Offline,
82 }
83 }
84
85 #[must_use]
87 pub fn from_readings(power: Option<Reading>, soc: Option<Reading>) -> Self {
88 Self {
89 power,
90 soc,
91 offline_since: None,
92 quality: power.map_or(Quality::Offline, |p| p.quality),
93 }
94 }
95}
96
97#[derive(Debug, Clone, Copy)]
99struct Packed {
100 index: u32,
102 mean: f32,
104 soc: f32,
106 good: u16,
108}
109
110pub const QUARTER_BYTES: usize = size_of::<Packed>();
112
113impl Packed {
114 fn pack(q: QuarterAggregate) -> Self {
115 #[expect(
116 clippy::cast_possible_truncation,
117 clippy::cast_sign_loss,
118 reason = "quarters since 1970 fit u32; good seconds ≤ 900"
119 )]
120 Self {
121 index: (q.start / QUARTER_SECS) as u32,
122 mean: q.mean_power_kw.map_or(f32::NAN, |v| v as f32),
123 soc: q.last_soc.map_or(f32::NAN, |v| v as f32),
124 good: (q.good_share * 900.0).round() as u16,
125 }
126 }
127
128 fn unpack(self) -> QuarterAggregate {
129 let some = |v: f32| (!v.is_nan()).then_some(f64::from(v));
130 QuarterAggregate {
131 start: i64::from(self.index) * QUARTER_SECS,
132 mean_power_kw: some(self.mean),
133 last_soc: some(self.soc),
134 good_share: f64::from(self.good) / 900.0,
135 }
136 }
137}
138
139#[derive(Debug, Clone, Copy)]
140struct Sample {
141 at: i64,
142 value: f32,
143 flags: Flags,
144}
145
146#[derive(Debug, Clone, Copy)]
147struct Accumulator {
148 start: i64,
149 energy_kws: f64,
150 good_secs: i64,
151 last_soc: Option<f32>,
152}
153
154impl Accumulator {
155 const fn new(start: i64) -> Self {
156 Self {
157 start,
158 energy_kws: 0.0,
159 good_secs: 0,
160 last_soc: None,
161 }
162 }
163
164 fn finish(self) -> QuarterAggregate {
165 QuarterAggregate {
166 start: self.start,
167 #[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
168 mean_power_kw: (self.good_secs > 0).then(|| self.energy_kws / self.good_secs as f64),
169 last_soc: self.last_soc.map(f64::from),
170 #[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
171 good_share: (self.good_secs as f64 / QUARTER_SECS as f64).min(1.0),
172 }
173 }
174}
175
176#[derive(Debug, Clone)]
177struct Series {
178 rated_kw: f64,
179 limit: i64,
180 latest: [Option<Sample>; 2],
181 recent: [VecDeque<(i64, f32)>; 2],
182 quarters: VecDeque<Packed>,
183 open: Option<Accumulator>,
184 held: Option<(i64, f32, i64)>,
186 offline_since: Option<i64>,
187}
188
189impl Series {
190 fn new(rated_kw: f64, limit: i64) -> Self {
191 Self {
192 rated_kw,
193 limit,
194 latest: [None, None],
195 recent: [VecDeque::new(), VecDeque::new()],
196 quarters: VecDeque::new(),
197 open: None,
198 held: None,
199 offline_since: None,
200 }
201 }
202
203 fn good_at_arrival(&self, q: Quantity, s: Sample) -> bool {
204 classify(
205 q,
206 f64::from(s.value),
207 s.at,
208 s.at,
209 self.limit,
210 s.flags,
211 self.rated_kw,
212 ) == Quality::Good
213 }
214
215 fn accumulator(&mut self, start: i64) -> Option<&mut Accumulator> {
217 match self.open {
218 Some(acc) if acc.start > start => return None, Some(acc) if acc.start < start => {
220 self.quarters.push_back(Packed::pack(acc.finish()));
221 while self.quarters.len() >= QUARTERS_MAX {
223 self.quarters.pop_front();
224 }
225 self.open = Some(Accumulator::new(start));
226 }
227 Some(_) => {}
228 None => self.open = Some(Accumulator::new(start)),
229 }
230 self.open.as_mut()
231 }
232
233 fn hold(&mut self, mut from: i64, to: i64, v: f32) {
235 while from < to {
236 let q = quarter_start(from);
237 let end = (q + QUARTER_SECS).min(to);
238 if let Some(acc) = self.accumulator(q) {
239 #[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
240 let secs = (end - from) as f64;
241 acc.energy_kws += f64::from(v) * secs;
242 acc.good_secs += end - from;
243 }
244 from = end;
245 }
246 }
247
248 fn credit(&mut self, to: i64) {
250 if let Some((from, v, until)) = self.held {
251 let end = to.min(until);
252 if end > from {
253 self.hold(from, end, v);
254 self.held = (end < until).then_some((end, v, until));
255 }
256 }
257 }
258
259 fn push(&mut self, q: Quantity, s: Sample) -> Pushed {
260 let i = q.index();
261 if let Some(l) = self.latest[i]
262 && s.at < l.at
263 {
264 if l.at - s.at <= CLOCK_STEP_SECS {
265 return Pushed::Dropped; }
267 *self = Self::new(self.rated_kw, self.limit);
269 self.push(q, s);
270 return Pushed::Reset;
271 }
272 self.latest[i] = Some(s);
273 let ring = &mut self.recent[i];
274 while ring.front().is_some_and(|(t, _)| *t <= s.at - RECENT_SECS)
275 || ring.len() >= RECENT_MAX
276 {
277 ring.pop_front();
278 }
279 ring.push_back((s.at, s.value));
280 let good = self.good_at_arrival(q, s);
281 self.credit(s.at);
284 match q {
285 Quantity::Power => {
286 self.held = good.then_some((s.at, s.value, s.at + self.limit));
287 if good {
288 let _ = self.accumulator(quarter_start(s.at));
290 }
291 }
292 Quantity::Soc => {
293 if good && let Some(acc) = self.accumulator(quarter_start(s.at)) {
294 acc.last_soc = Some(s.value);
295 }
296 }
297 }
298 Pushed::Stored
299 }
300
301 fn reading(&self, q: Quantity, now: i64) -> Option<Reading> {
302 self.latest[q.index()].map(|s| Reading {
303 value: f64::from(s.value),
304 at: s.at,
305 quality: classify(
306 q,
307 f64::from(s.value),
308 s.at,
309 now,
310 self.limit,
311 s.flags,
312 self.rated_kw,
313 ),
314 })
315 }
316}
317
318#[derive(Debug, Clone, Default)]
320pub struct Store {
321 series: HashMap<AssetId, Series>,
322}
323
324impl Store {
325 pub fn new(assets: impl IntoIterator<Item = (AssetId, f64, i64)>) -> Self {
327 Self {
328 series: assets
329 .into_iter()
330 .map(|(id, rated, limit)| (id, Series::new(rated, limit)))
331 .collect(),
332 }
333 }
334
335 #[must_use]
337 pub fn limit(&self, asset: &AssetId) -> Option<i64> {
338 self.series.get(asset).map(|s| s.limit)
339 }
340
341 pub fn set_limit(&mut self, asset: &AssetId, limit: i64) -> bool {
343 self.series
344 .get_mut(asset)
345 .map(|s| s.limit = limit)
346 .is_some()
347 }
348
349 pub fn push(
351 &mut self,
352 asset: &AssetId,
353 quantity: Quantity,
354 value: f64,
355 at: i64,
356 flags: Flags,
357 ) -> Pushed {
358 let Some(series) = self.series.get_mut(asset) else {
359 return Pushed::Undeclared;
360 };
361 #[expect(
362 clippy::cast_possible_truncation,
363 reason = "measurements fit f32; plausibility runs on the stored value"
364 )]
365 let value = value as f32;
366 series.offline_since = None;
367 series.push(quantity, Sample { at, value, flags })
368 }
369
370 pub fn set_offline(&mut self, asset: &AssetId, since: Option<i64>) {
373 if let Some(s) = self.series.get_mut(asset) {
374 match since {
375 Some(t) => {
376 s.credit(t);
377 s.held = None;
378 s.offline_since.get_or_insert(t);
379 }
380 None => s.offline_since = None,
381 }
382 }
383 }
384
385 #[must_use]
387 pub fn now(&self, asset: &AssetId, now: i64) -> Option<AssetNow> {
388 let s = self.series.get(asset)?;
389 if s.offline_since.is_some() {
390 return Some(AssetNow::offline(s.offline_since));
391 }
392 Some(AssetNow::from_readings(
393 s.reading(Quantity::Power, now),
394 s.reading(Quantity::Soc, now),
395 ))
396 }
397
398 #[must_use]
400 pub fn quarters(&self, asset: &AssetId, from: i64, to: i64, now: i64) -> Vec<QuarterAggregate> {
401 let Some(s) = self.series.get(asset) else {
402 return Vec::new();
403 };
404 let mut view = s.clone();
405 view.credit(now);
406 view.quarters
407 .iter()
408 .map(|p| p.unpack())
409 .chain(view.open.map(Accumulator::finish))
410 .filter(|q| q.start >= from && q.start < to && q.start <= now)
411 .collect()
412 }
413
414 #[must_use]
416 pub fn recent(&self, asset: &AssetId, now: i64) -> Vec<Recent> {
417 let Some(s) = self.series.get(asset) else {
418 return Vec::new();
419 };
420 let mut by_time: BTreeMap<i64, Recent> = BTreeMap::new();
421 for q in Quantity::ALL {
422 for &(at, v) in &s.recent[q.index()] {
423 if at <= now - RECENT_SECS || at > now {
424 continue;
425 }
426 let r = by_time.entry(at).or_insert(Recent {
427 at,
428 power_kw: None,
429 soc: None,
430 });
431 match q {
432 Quantity::Power => r.power_kw = Some(f64::from(v)),
433 Quantity::Soc => r.soc = Some(f64::from(v)),
434 }
435 }
436 }
437 by_time.into_values().collect()
438 }
439
440 #[must_use]
442 pub fn held(&self, asset: &AssetId) -> Option<(usize, usize, usize)> {
443 self.series.get(asset).map(|s| {
444 (
445 s.recent[0].len(),
446 s.recent[1].len(),
447 s.quarters.len() + usize::from(s.open.is_some()),
448 )
449 })
450 }
451}