use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Quantity {
Power,
Soc,
}
impl Quantity {
pub const ALL: [Self; 2] = [Self::Power, Self::Soc];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Power => "power",
Self::Soc => "soc",
}
}
#[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,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Quality {
Good,
Stale,
Invalid,
Offline,
}
impl Quality {
pub const ALL: [Self; 4] = [Self::Good, Self::Stale, Self::Invalid, Self::Offline];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Good => "good",
Self::Stale => "stale",
Self::Invalid => "invalid",
Self::Offline => "offline",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|q| q.as_str() == s)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Flags {
pub invalid: bool,
pub questionable: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Reading {
pub value: f64,
pub at: i64,
pub quality: Quality,
}
pub const POWER_LIMIT_FACTOR: f64 = 1.1;
#[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),
}
}
#[must_use]
pub fn stale_limit(poll_secs: u32) -> i64 {
(i64::from(poll_secs) * 3).max(10)
}
pub const FUTURE_TOLERANCE_SECS: i64 = 5;
#[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
}
}