flexpool_telemetry/
quality.rs1use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
7#[serde(rename_all = "lowercase")]
8pub enum Quantity {
9 Power,
11 Soc,
13}
14
15impl Quantity {
16 pub const ALL: [Self; 2] = [Self::Power, Self::Soc];
18
19 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
44#[serde(rename_all = "lowercase")]
45pub enum Quality {
46 Good,
48 Stale,
50 Invalid,
52 Offline,
54}
55
56impl Quality {
57 pub const ALL: [Self; 4] = [Self::Good, Self::Stale, Self::Invalid, Self::Offline];
59
60 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
80pub struct Flags {
81 pub invalid: bool,
83 pub questionable: bool,
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
89pub struct Reading {
90 pub value: f64,
92 pub at: i64,
94 pub quality: Quality,
96}
97
98pub const POWER_LIMIT_FACTOR: f64 = 1.1;
100
101#[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#[must_use]
113pub fn stale_limit(poll_secs: u32) -> i64 {
114 (i64::from(poll_secs) * 3).max(10)
115}
116
117pub const FUTURE_TOLERANCE_SECS: i64 = 5;
119
120#[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}