flexpool-telemetry 0.5.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
//! Quality: whether a value can be trusted now.

use serde::{Deserialize, Serialize};

/// What is measured.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Quantity {
    /// Active power in kW, generator convention (feed-in positive).
    Power,
    /// Battery state of charge in percent.
    Soc,
}

impl Quantity {
    /// Both quantities, in a stable order.
    pub const ALL: [Self; 2] = [Self::Power, Self::Soc];

    /// The quantity as written in files and the API.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Power => "power",
            Self::Soc => "soc",
        }
    }

    /// Parses a quantity.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|q| q.as_str() == s)
    }

    pub(crate) const fn index(self) -> usize {
        match self {
            Self::Power => 0,
            Self::Soc => 1,
        }
    }
}

/// How far a value can be trusted, from best to worst.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Quality {
    /// Fresh and plausible.
    Good,
    /// Older than its limit, or marked questionable by the source.
    Stale,
    /// Outside physical limits, or marked invalid by the source.
    Invalid,
    /// No connection or no value.
    Offline,
}

impl Quality {
    /// Every quality, best first.
    pub const ALL: [Self; 4] = [Self::Good, Self::Stale, Self::Invalid, Self::Offline];

    /// The quality as written in the API.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Good => "good",
            Self::Stale => "stale",
            Self::Invalid => "invalid",
            Self::Offline => "offline",
        }
    }

    /// Parses a quality.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|q| q.as_str() == s)
    }
}

/// Quality flags a source attaches to a value (IEC 104: IV → invalid; NT, SB, BL, OV → questionable).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Flags {
    /// The source says the value is invalid.
    pub invalid: bool,
    /// The source says the value is not topical, substituted, blocked or overflowed.
    pub questionable: bool,
}

/// One value with its source time and its quality at the instant it was read.
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Reading {
    /// The value (kW or %).
    pub value: f64,
    /// Source time, Unix seconds.
    pub at: i64,
    /// Quality at the instant of reading.
    pub quality: Quality,
}

/// Power beyond this multiple of the rated power is physically implausible (SR-002).
pub const POWER_LIMIT_FACTOR: f64 = 1.1;

/// Whether `value` is physically possible for `quantity` on an asset rated `rated_kw`.
#[must_use]
pub fn plausible(quantity: Quantity, value: f64, rated_kw: f64) -> bool {
    value.is_finite()
        && match quantity {
            Quantity::Power => value.abs() <= rated_kw * POWER_LIMIT_FACTOR,
            Quantity::Soc => (0.0..=100.0).contains(&value),
        }
}

/// The stale limit for a source read every `poll_secs`: three intervals, at least 10 s.
#[must_use]
pub fn stale_limit(poll_secs: u32) -> i64 {
    (i64::from(poll_secs) * 3).max(10)
}

/// A source time this far ahead of `now` cannot be trusted (a clock stepped back, or a device ahead).
pub const FUTURE_TOLERANCE_SECS: i64 = 5;

/// The quality of `value`, taken at `at`, when read at `now`. A value from the future is stale.
#[must_use]
pub fn classify(
    quantity: Quantity,
    value: f64,
    at: i64,
    now: i64,
    limit: i64,
    flags: Flags,
    rated_kw: f64,
) -> Quality {
    if flags.invalid || !plausible(quantity, value, rated_kw) {
        Quality::Invalid
    } else if flags.questionable || now - at > limit || at - now > FUTURE_TOLERANCE_SECS {
        Quality::Stale
    } else {
        Quality::Good
    }
}