use alloc::string::String;
use alloc::vec::Vec;
use bon::Builder;
use serde::{Deserialize, Serialize};
use super::common::{PowerRange, Timer, Transition};
use super::{Duration, Id, NumberRange, Timestamp};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
#[builder(on(String, into))]
pub struct StorageDescription {
#[serde(skip_serializing_if = "Option::is_none")]
pub diagnostic_label: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fill_level_label: Option<String>,
pub provides_leakage_behaviour: bool,
pub provides_fill_level_target_profile: bool,
pub provides_usage_forecast: bool,
pub fill_level_range: NumberRange,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
pub struct OperationModeElement {
pub fill_level_range: NumberRange,
pub fill_rate: NumberRange,
pub power_ranges: Vec<PowerRange>,
#[serde(skip_serializing_if = "Option::is_none")]
pub running_costs: Option<NumberRange>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
#[builder(on(String, into))]
pub struct OperationMode {
pub id: Id,
#[serde(skip_serializing_if = "Option::is_none")]
pub diagnostic_label: Option<String>,
pub elements: Vec<OperationModeElement>,
pub abnormal_condition_only: bool,
}
impl OperationMode {
#[must_use]
pub fn element_at(&self, fill_level: f64) -> Option<&OperationModeElement> {
self.elements
.iter()
.find(|e| e.fill_level_range.contains(fill_level))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
#[builder(on(String, into))]
pub struct ActuatorDescription {
pub id: Id,
#[serde(skip_serializing_if = "Option::is_none")]
pub diagnostic_label: Option<String>,
pub supported_commodities: Vec<super::common::Commodity>,
pub operation_modes: Vec<OperationMode>,
pub transitions: Vec<Transition>,
pub timers: Vec<Timer>,
}
impl ActuatorDescription {
#[must_use]
pub fn operation_mode(&self, id: &Id) -> Option<&OperationMode> {
self.operation_modes.iter().find(|m| m.id == *id)
}
#[must_use]
pub fn timer(&self, id: &Id) -> Option<&Timer> {
self.timers.iter().find(|t| t.id == *id)
}
#[must_use]
pub fn transition(&self, from: &Id, to: &Id) -> Option<&Transition> {
self.transitions
.iter()
.find(|t| t.from == *from && t.to == *to)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FillLevelTargetProfileElement {
pub duration: Duration,
pub fill_level_range: NumberRange,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LeakageBehaviourElement {
pub fill_level_range: NumberRange,
pub leakage_rate: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
pub struct UsageForecastElement {
pub duration: Duration,
#[serde(skip_serializing_if = "Option::is_none")]
pub usage_rate_upper_limit: Option<f64>,
#[serde(
rename = "usage_rate_upper_95PPR",
skip_serializing_if = "Option::is_none"
)]
pub usage_rate_upper_95ppr: Option<f64>,
#[serde(
rename = "usage_rate_upper_68PPR",
skip_serializing_if = "Option::is_none"
)]
pub usage_rate_upper_68ppr: Option<f64>,
pub usage_rate_expected: f64,
#[serde(
rename = "usage_rate_lower_68PPR",
skip_serializing_if = "Option::is_none"
)]
pub usage_rate_lower_68ppr: Option<f64>,
#[serde(
rename = "usage_rate_lower_95PPR",
skip_serializing_if = "Option::is_none"
)]
pub usage_rate_lower_95ppr: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub usage_rate_lower_limit: Option<f64>,
}
impl UsageForecastElement {
#[must_use]
pub fn bands_ascending(&self) -> [(&'static str, Option<f64>); 7] {
[
("usage_rate_lower_limit", self.usage_rate_lower_limit),
("usage_rate_lower_95PPR", self.usage_rate_lower_95ppr),
("usage_rate_lower_68PPR", self.usage_rate_lower_68ppr),
("usage_rate_expected", Some(self.usage_rate_expected)),
("usage_rate_upper_68PPR", self.usage_rate_upper_68ppr),
("usage_rate_upper_95PPR", self.usage_rate_upper_95ppr),
("usage_rate_upper_limit", self.usage_rate_upper_limit),
]
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
pub struct SystemDescription {
#[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
pub message_id: Id,
pub valid_from: Timestamp,
pub actuators: Vec<ActuatorDescription>,
pub storage: StorageDescription,
}
impl SystemDescription {
#[must_use]
pub fn actuator(&self, id: &Id) -> Option<&ActuatorDescription> {
self.actuators.iter().find(|a| a.id == *id)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
pub struct StorageStatus {
#[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
pub message_id: Id,
pub present_fill_level: f64,
}
impl StorageStatus {
#[cfg(feature = "uuid")]
#[must_use]
pub fn new(present_fill_level: f64) -> Self {
Self {
message_id: Id::generate(),
present_fill_level,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
pub struct ActuatorStatus {
#[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
pub message_id: Id,
pub actuator_id: Id,
pub active_operation_mode_id: Id,
pub operation_mode_factor: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub previous_operation_mode_id: Option<Id>,
#[serde(skip_serializing_if = "Option::is_none")]
pub transition_timestamp: Option<Timestamp>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
pub struct TimerStatus {
#[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
pub message_id: Id,
pub timer_id: Id,
pub actuator_id: Id,
pub finished_at: Timestamp,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
pub struct LeakageBehaviour {
#[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
pub message_id: Id,
pub valid_from: Timestamp,
pub elements: Vec<LeakageBehaviourElement>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
pub struct UsageForecast {
#[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
pub message_id: Id,
pub start_time: Timestamp,
pub elements: Vec<UsageForecastElement>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
pub struct FillLevelTargetProfile {
#[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
pub message_id: Id,
pub start_time: Timestamp,
pub elements: Vec<FillLevelTargetProfileElement>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[serde(deny_unknown_fields)]
pub struct Instruction {
#[cfg_attr(feature = "uuid", builder(default = Id::generate()))]
pub message_id: Id,
pub id: Id,
pub actuator_id: Id,
pub operation_mode: Id,
pub operation_mode_factor: f64,
pub execution_time: Timestamp,
pub abnormal_condition: bool,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::common::CommodityQuantity;
#[test]
fn the_ev_example_from_the_docs_round_trips() {
let json = r#"{
"id": "om2",
"diagnostic_label": "Charging",
"elements": [
{
"fill_level_range": { "start_of_range": 0, "end_of_range": 100 },
"fill_rate": { "start_of_range": 0.00065, "end_of_range": 0.0051 },
"power_ranges": [
{
"start_of_range": 1400,
"end_of_range": 11000,
"commodity_quantity": "ELECTRIC.POWER.3_PHASE_SYMMETRIC"
}
]
}
],
"abnormal_condition_only": false
}"#;
let mode: OperationMode = serde_json::from_str(json).unwrap();
assert_eq!(mode.id, "om2");
let element = mode.element_at(50.0).unwrap();
assert_eq!(element.power_ranges.len(), 1);
assert!((element.fill_rate.at_factor(0.0) - 0.000_65).abs() < 1e-12);
assert!((element.power_ranges.first().unwrap().at_factor(0.0) - 1400.0).abs() < 1e-9);
assert!(mode.element_at(101.0).is_none());
}
#[test]
fn a_small_fill_rate_survives_the_json_round_trip() {
let original = 0.001_319_444_444_444_444_3_f64;
let element = LeakageBehaviourElement {
fill_level_range: NumberRange::new(0.0, 100.0),
leakage_rate: original,
};
let json = serde_json::to_string(&element).unwrap();
let back: LeakageBehaviourElement = serde_json::from_str(&json).unwrap();
assert_eq!(
back.leakage_rate.to_bits(),
original.to_bits(),
"fill rates must round-trip bit for bit"
);
}
#[test]
fn instruction_keeps_the_operation_mode_field_name() {
let instruction = Instruction {
message_id: Id::new_const("m1"),
id: Id::new_const("instr0"),
actuator_id: Id::new_const("actuator1"),
operation_mode: Id::new_const("om1"),
operation_mode_factor: 1.0,
execution_time: Timestamp::UNIX_EPOCH,
abnormal_condition: false,
};
let json = serde_json::to_string(&instruction).unwrap();
assert!(json.contains(r#""operation_mode":"om1""#));
assert!(!json.contains("operation_mode_id"));
}
#[test]
fn usage_and_leakage_rates_are_positive_when_the_level_falls() {
let e = UsageForecastElement::builder()
.duration(Duration::from_secs(900))
.usage_rate_expected(0.5)
.build();
assert!(
e.usage_rate_expected > 0.0,
"positive means the store drains"
);
let bands: Vec<_> = e.bands_ascending().iter().filter_map(|(_, v)| *v).collect();
assert_eq!(bands, alloc::vec![0.5]);
}
#[test]
fn power_range_interpolates_between_its_ends() {
let r = PowerRange::new(500.0, 2000.0, CommodityQuantity::ElectricPowerL1);
assert!((r.at_factor(1.0) - 2000.0).abs() < 1e-9);
assert_eq!(r.range(), NumberRange::new(500.0, 2000.0));
}
}