flexpool-telemetry 0.3.0

flexpool live telemetry: quality, plausibility, a bounded store with quarter-hour aggregation, pool summaries and the sandbox simulator. No I/O; time is an input.
Documentation
//! Pool totals: only good values count, and every total says how many assets it includes (FR-008).

use serde::Serialize;

use crate::quality::Quality;
use crate::store::AssetNow;

/// Assets by quality.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
pub struct QualityCounts {
    /// Fresh and plausible.
    pub good: usize,
    /// Too old or questionable.
    pub stale: usize,
    /// Implausible or marked invalid.
    pub invalid: usize,
    /// Without connection or value.
    pub offline: usize,
}

/// A pool's live totals.
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize)]
pub struct PoolLive {
    /// Feed-in (positive power), kW.
    pub feed_in_kw: f64,
    /// Consumption (negative power, as a positive number), kW.
    pub consumption_kw: f64,
    /// Feed-in minus consumption, kW.
    pub net_kw: f64,
    /// Energy stored in batteries with a good state of charge, kWh.
    pub stored_kwh: f64,
    /// Assets in the pool.
    pub assets: usize,
    /// Assets whose power is in the totals (good ones).
    pub included: usize,
    /// Assets by quality.
    pub by_quality: QualityCounts,
}

/// Sums assets: `(state now, usable energy in kWh for batteries)`.
pub fn summarise<'a>(items: impl IntoIterator<Item = (&'a AssetNow, Option<f64>)>) -> PoolLive {
    let mut p = PoolLive::default();
    for (a, energy) in items {
        p.assets += 1;
        let counter = match a.quality {
            Quality::Good => &mut p.by_quality.good,
            Quality::Stale => &mut p.by_quality.stale,
            Quality::Invalid => &mut p.by_quality.invalid,
            Quality::Offline => &mut p.by_quality.offline,
        };
        *counter += 1;
        if let Some(power) = a.power.filter(|r| r.quality == Quality::Good) {
            p.included += 1;
            if power.value >= 0.0 {
                p.feed_in_kw += power.value;
            } else {
                p.consumption_kw -= power.value;
            }
        }
        if let (Some(soc), Some(kwh)) = (a.soc.filter(|r| r.quality == Quality::Good), energy) {
            p.stored_kwh += soc.value / 100.0 * kwh;
        }
    }
    p.net_kw = p.feed_in_kw - p.consumption_kw;
    p
}