Skip to main content

flexpool_telemetry/
quality.rs

1//! Quality: whether a value can be trusted now.
2
3use serde::{Deserialize, Serialize};
4
5/// What is measured.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
7#[serde(rename_all = "lowercase")]
8pub enum Quantity {
9    /// Active power in kW, generator convention (feed-in positive).
10    Power,
11    /// Battery state of charge in percent.
12    Soc,
13}
14
15impl Quantity {
16    /// Both quantities, in a stable order.
17    pub const ALL: [Self; 2] = [Self::Power, Self::Soc];
18
19    /// The quantity as written in files and the API.
20    #[must_use]
21    pub const fn as_str(self) -> &'static str {
22        match self {
23            Self::Power => "power",
24            Self::Soc => "soc",
25        }
26    }
27
28    /// Parses a quantity.
29    #[must_use]
30    pub fn parse(s: &str) -> Option<Self> {
31        Self::ALL.into_iter().find(|q| q.as_str() == s)
32    }
33
34    pub(crate) const fn index(self) -> usize {
35        match self {
36            Self::Power => 0,
37            Self::Soc => 1,
38        }
39    }
40}
41
42/// How far a value can be trusted, from best to worst.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
44#[serde(rename_all = "lowercase")]
45pub enum Quality {
46    /// Fresh and plausible.
47    Good,
48    /// Older than its limit, or marked questionable by the source.
49    Stale,
50    /// Outside physical limits, or marked invalid by the source.
51    Invalid,
52    /// No connection or no value.
53    Offline,
54}
55
56impl Quality {
57    /// Every quality, best first.
58    pub const ALL: [Self; 4] = [Self::Good, Self::Stale, Self::Invalid, Self::Offline];
59
60    /// The quality as written in the API.
61    #[must_use]
62    pub const fn as_str(self) -> &'static str {
63        match self {
64            Self::Good => "good",
65            Self::Stale => "stale",
66            Self::Invalid => "invalid",
67            Self::Offline => "offline",
68        }
69    }
70
71    /// Parses a quality.
72    #[must_use]
73    pub fn parse(s: &str) -> Option<Self> {
74        Self::ALL.into_iter().find(|q| q.as_str() == s)
75    }
76}
77
78/// Quality flags a source attaches to a value (IEC 104: IV → invalid; NT, SB, BL, OV → questionable).
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
80pub struct Flags {
81    /// The source says the value is invalid.
82    pub invalid: bool,
83    /// The source says the value is not topical, substituted, blocked or overflowed.
84    pub questionable: bool,
85}
86
87/// One value with its source time and its quality at the instant it was read.
88#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
89pub struct Reading {
90    /// The value (kW or %).
91    pub value: f64,
92    /// Source time, Unix seconds.
93    pub at: i64,
94    /// Quality at the instant of reading.
95    pub quality: Quality,
96}
97
98/// Power beyond this multiple of the rated power is physically implausible (SR-002).
99pub const POWER_LIMIT_FACTOR: f64 = 1.1;
100
101/// Whether `value` is physically possible for `quantity` on an asset rated `rated_kw`.
102#[must_use]
103pub fn plausible(quantity: Quantity, value: f64, rated_kw: f64) -> bool {
104    value.is_finite()
105        && match quantity {
106            Quantity::Power => value.abs() <= rated_kw * POWER_LIMIT_FACTOR,
107            Quantity::Soc => (0.0..=100.0).contains(&value),
108        }
109}
110
111/// The stale limit for a source read every `poll_secs`: three intervals, at least 10 s.
112#[must_use]
113pub fn stale_limit(poll_secs: u32) -> i64 {
114    (i64::from(poll_secs) * 3).max(10)
115}
116
117/// A source time this far ahead of `now` cannot be trusted (a clock stepped back, or a device ahead).
118pub const FUTURE_TOLERANCE_SECS: i64 = 5;
119
120/// The quality of `value`, taken at `at`, when read at `now`. A value from the future is stale.
121#[must_use]
122pub fn classify(
123    quantity: Quantity,
124    value: f64,
125    at: i64,
126    now: i64,
127    limit: i64,
128    flags: Flags,
129    rated_kw: f64,
130) -> Quality {
131    if flags.invalid || !plausible(quantity, value, rated_kw) {
132        Quality::Invalid
133    } else if flags.questionable || now - at > limit || at - now > FUTURE_TOLERANCE_SECS {
134        Quality::Stale
135    } else {
136        Quality::Good
137    }
138}