use std::collections::{BTreeMap, HashMap, VecDeque};
use flexpool_core::AssetId;
use serde::Serialize;
use crate::quality::{Flags, Quality, Quantity, Reading, classify};
use crate::{QUARTER_SECS, quarter_start};
pub const RECENT_SECS: i64 = 900;
pub const RECENT_MAX: usize = 900;
pub const QUARTERS_MAX: usize = 192;
pub const CLOCK_STEP_SECS: i64 = 60;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pushed {
Stored,
Dropped,
Reset,
Undeclared,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct QuarterAggregate {
pub start: i64,
pub mean_power_kw: Option<f64>,
pub last_soc: Option<f64>,
pub good_share: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Recent {
pub at: i64,
pub power_kw: Option<f64>,
pub soc: Option<f64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct AssetNow {
pub power: Option<Reading>,
pub soc: Option<Reading>,
pub offline_since: Option<i64>,
pub quality: Quality,
}
impl AssetNow {
#[must_use]
pub const fn offline(since: Option<i64>) -> Self {
Self {
power: None,
soc: None,
offline_since: since,
quality: Quality::Offline,
}
}
#[must_use]
pub fn from_readings(power: Option<Reading>, soc: Option<Reading>) -> Self {
Self {
power,
soc,
offline_since: None,
quality: power.map_or(Quality::Offline, |p| p.quality),
}
}
}
#[derive(Debug, Clone, Copy)]
struct Packed {
index: u32,
mean: f32,
soc: f32,
good: u16,
}
pub const QUARTER_BYTES: usize = size_of::<Packed>();
impl Packed {
fn pack(q: QuarterAggregate) -> Self {
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "quarters since 1970 fit u32; good seconds ≤ 900"
)]
Self {
index: (q.start / QUARTER_SECS) as u32,
mean: q.mean_power_kw.map_or(f32::NAN, |v| v as f32),
soc: q.last_soc.map_or(f32::NAN, |v| v as f32),
good: (q.good_share * 900.0).round() as u16,
}
}
fn unpack(self) -> QuarterAggregate {
let some = |v: f32| (!v.is_nan()).then_some(f64::from(v));
QuarterAggregate {
start: i64::from(self.index) * QUARTER_SECS,
mean_power_kw: some(self.mean),
last_soc: some(self.soc),
good_share: f64::from(self.good) / 900.0,
}
}
}
#[derive(Debug, Clone, Copy)]
struct Sample {
at: i64,
value: f32,
flags: Flags,
}
#[derive(Debug, Clone, Copy)]
struct Accumulator {
start: i64,
energy_kws: f64,
good_secs: i64,
last_soc: Option<f32>,
}
impl Accumulator {
const fn new(start: i64) -> Self {
Self {
start,
energy_kws: 0.0,
good_secs: 0,
last_soc: None,
}
}
fn finish(self) -> QuarterAggregate {
QuarterAggregate {
start: self.start,
#[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
mean_power_kw: (self.good_secs > 0).then(|| self.energy_kws / self.good_secs as f64),
last_soc: self.last_soc.map(f64::from),
#[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
good_share: (self.good_secs as f64 / QUARTER_SECS as f64).min(1.0),
}
}
}
#[derive(Debug, Clone)]
struct Series {
rated_kw: f64,
limit: i64,
latest: [Option<Sample>; 2],
recent: [VecDeque<(i64, f32)>; 2],
quarters: VecDeque<Packed>,
open: Option<Accumulator>,
held: Option<(i64, f32, i64)>,
offline_since: Option<i64>,
}
impl Series {
fn new(rated_kw: f64, limit: i64) -> Self {
Self {
rated_kw,
limit,
latest: [None, None],
recent: [VecDeque::new(), VecDeque::new()],
quarters: VecDeque::new(),
open: None,
held: None,
offline_since: None,
}
}
fn good_at_arrival(&self, q: Quantity, s: Sample) -> bool {
classify(
q,
f64::from(s.value),
s.at,
s.at,
self.limit,
s.flags,
self.rated_kw,
) == Quality::Good
}
fn accumulator(&mut self, start: i64) -> Option<&mut Accumulator> {
match self.open {
Some(acc) if acc.start > start => return None, Some(acc) if acc.start < start => {
self.quarters.push_back(Packed::pack(acc.finish()));
while self.quarters.len() >= QUARTERS_MAX {
self.quarters.pop_front();
}
self.open = Some(Accumulator::new(start));
}
Some(_) => {}
None => self.open = Some(Accumulator::new(start)),
}
self.open.as_mut()
}
fn hold(&mut self, mut from: i64, to: i64, v: f32) {
while from < to {
let q = quarter_start(from);
let end = (q + QUARTER_SECS).min(to);
if let Some(acc) = self.accumulator(q) {
#[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
let secs = (end - from) as f64;
acc.energy_kws += f64::from(v) * secs;
acc.good_secs += end - from;
}
from = end;
}
}
fn credit(&mut self, to: i64) {
if let Some((from, v, until)) = self.held {
let end = to.min(until);
if end > from {
self.hold(from, end, v);
self.held = (end < until).then_some((end, v, until));
}
}
}
fn push(&mut self, q: Quantity, s: Sample) -> Pushed {
let i = q.index();
if let Some(l) = self.latest[i]
&& s.at < l.at
{
if l.at - s.at <= CLOCK_STEP_SECS {
return Pushed::Dropped; }
*self = Self::new(self.rated_kw, self.limit);
self.push(q, s);
return Pushed::Reset;
}
self.latest[i] = Some(s);
let ring = &mut self.recent[i];
while ring.front().is_some_and(|(t, _)| *t <= s.at - RECENT_SECS)
|| ring.len() >= RECENT_MAX
{
ring.pop_front();
}
ring.push_back((s.at, s.value));
let good = self.good_at_arrival(q, s);
self.credit(s.at);
match q {
Quantity::Power => {
self.held = good.then_some((s.at, s.value, s.at + self.limit));
if good {
let _ = self.accumulator(quarter_start(s.at));
}
}
Quantity::Soc => {
if good && let Some(acc) = self.accumulator(quarter_start(s.at)) {
acc.last_soc = Some(s.value);
}
}
}
Pushed::Stored
}
fn reading(&self, q: Quantity, now: i64) -> Option<Reading> {
self.latest[q.index()].map(|s| Reading {
value: f64::from(s.value),
at: s.at,
quality: classify(
q,
f64::from(s.value),
s.at,
now,
self.limit,
s.flags,
self.rated_kw,
),
})
}
}
#[derive(Debug, Clone, Default)]
pub struct Store {
series: HashMap<AssetId, Series>,
}
impl Store {
pub fn new(assets: impl IntoIterator<Item = (AssetId, f64, i64)>) -> Self {
Self {
series: assets
.into_iter()
.map(|(id, rated, limit)| (id, Series::new(rated, limit)))
.collect(),
}
}
#[must_use]
pub fn limit(&self, asset: &AssetId) -> Option<i64> {
self.series.get(asset).map(|s| s.limit)
}
pub fn set_limit(&mut self, asset: &AssetId, limit: i64) -> bool {
self.series
.get_mut(asset)
.map(|s| s.limit = limit)
.is_some()
}
pub fn push(
&mut self,
asset: &AssetId,
quantity: Quantity,
value: f64,
at: i64,
flags: Flags,
) -> Pushed {
let Some(series) = self.series.get_mut(asset) else {
return Pushed::Undeclared;
};
#[expect(
clippy::cast_possible_truncation,
reason = "measurements fit f32; plausibility runs on the stored value"
)]
let value = value as f32;
series.offline_since = None;
series.push(quantity, Sample { at, value, flags })
}
pub fn set_offline(&mut self, asset: &AssetId, since: Option<i64>) {
if let Some(s) = self.series.get_mut(asset) {
match since {
Some(t) => {
s.credit(t);
s.held = None;
s.offline_since.get_or_insert(t);
}
None => s.offline_since = None,
}
}
}
#[must_use]
pub fn now(&self, asset: &AssetId, now: i64) -> Option<AssetNow> {
let s = self.series.get(asset)?;
if s.offline_since.is_some() {
return Some(AssetNow::offline(s.offline_since));
}
Some(AssetNow::from_readings(
s.reading(Quantity::Power, now),
s.reading(Quantity::Soc, now),
))
}
#[must_use]
pub fn quarters(&self, asset: &AssetId, from: i64, to: i64, now: i64) -> Vec<QuarterAggregate> {
let Some(s) = self.series.get(asset) else {
return Vec::new();
};
let mut view = s.clone();
view.credit(now);
view.quarters
.iter()
.map(|p| p.unpack())
.chain(view.open.map(Accumulator::finish))
.filter(|q| q.start >= from && q.start < to && q.start <= now)
.collect()
}
#[must_use]
pub fn recent(&self, asset: &AssetId, now: i64) -> Vec<Recent> {
let Some(s) = self.series.get(asset) else {
return Vec::new();
};
let mut by_time: BTreeMap<i64, Recent> = BTreeMap::new();
for q in Quantity::ALL {
for &(at, v) in &s.recent[q.index()] {
if at <= now - RECENT_SECS || at > now {
continue;
}
let r = by_time.entry(at).or_insert(Recent {
at,
power_kw: None,
soc: None,
});
match q {
Quantity::Power => r.power_kw = Some(f64::from(v)),
Quantity::Soc => r.soc = Some(f64::from(v)),
}
}
}
by_time.into_values().collect()
}
#[must_use]
pub fn held(&self, asset: &AssetId) -> Option<(usize, usize, usize)> {
self.series.get(asset).map(|s| {
(
s.recent[0].len(),
s.recent[1].len(),
s.quarters.len() + usize::from(s.open.is_some()),
)
})
}
}