use alloc::string::String;
use alloc::vec::Vec;
use super::core::Registry;
use crate::codec::{self, DecodeError, DecodeOptions, Strictness};
use crate::message::{Message, MessageKind};
use crate::types::common::{ControlType, EnergyManagementRole, ReceptionStatusValues};
use crate::types::{Duration, Id, Timestamp, WireProfile};
use crate::validate::{Phase, Report, Validate, rules};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Observed {
pub sender: EnergyManagementRole,
pub kind: Option<MessageKind>,
pub message: Option<Message>,
pub pruned: Vec<String>,
pub report: Report,
pub status: ReceptionStatusValues,
}
impl Observed {
#[must_use]
pub fn is_clean(&self) -> bool {
self.report.is_empty()
}
#[must_use]
pub fn accepted(&self) -> bool {
self.status == ReceptionStatusValues::Ok
}
#[must_use]
pub fn diagnostic_label(&self) -> Option<String> {
self.report.diagnostic_label()
}
}
#[derive(Debug, Clone)]
pub struct Analyzer {
registry: Registry,
profile: WireProfile,
strictness: Strictness,
phase: Phase,
seen: Vec<Id>,
skew_tolerance: Duration,
s2_connect: bool,
max_message_bytes: usize,
}
impl Default for Analyzer {
fn default() -> Self {
Self::new()
}
}
impl Analyzer {
#[must_use]
pub fn new() -> Self {
Self {
registry: Registry::default(),
profile: WireProfile::V1_0_0,
strictness: Strictness::Lenient,
phase: Phase::Connected,
seen: Vec::new(),
skew_tolerance: Duration::from_secs(30),
s2_connect: false,
max_message_bytes: DecodeOptions::DEFAULT_MAX_BYTES,
}
}
#[must_use]
pub const fn profile(mut self, profile: WireProfile) -> Self {
self.profile = profile;
self
}
#[must_use]
pub const fn strict(mut self) -> Self {
self.strictness = Strictness::Strict;
self
}
#[must_use]
pub const fn over_s2_connect(mut self) -> Self {
self.s2_connect = true;
self
}
#[must_use]
pub const fn skew_tolerance(mut self, tolerance: Duration) -> Self {
self.skew_tolerance = tolerance;
self
}
#[must_use]
pub const fn registry(&self) -> &Registry {
&self.registry
}
#[must_use]
pub const fn active_control_type(&self) -> Option<ControlType> {
self.phase.active_control_type()
}
#[must_use]
pub const fn phase(&self) -> Phase {
self.phase
}
pub fn observe(
&mut self,
sender: EnergyManagementRole,
text: &str,
now: Timestamp,
) -> Observed {
let options = DecodeOptions {
strictness: self.strictness,
profile: self.profile,
max_bytes: self.max_message_bytes,
};
let _ = self.registry.activate_due(now);
match codec::decode_with(text, &options) {
Err(error) => Self::on_decode_error(sender, &error),
Ok(decoded) => {
let mut report = Report::new();
for path in &decoded.pruned {
report.push(
rules::UNKNOWN_PROPERTY,
path,
"property is not defined by the schema and was removed",
);
}
let kind = decoded.message.kind();
{
let ctx = self.registry.context(
self.profile,
sender,
self.phase,
self.s2_connect,
now,
&self.seen,
self.skew_tolerance,
);
report.extend(decoded.message.validate(&ctx));
}
let status = report.reception_status();
self.record(&decoded.message, now);
Observed {
sender,
kind: Some(kind),
message: Some(decoded.message),
pruned: decoded.pruned,
report,
status,
}
}
}
}
fn on_decode_error(sender: EnergyManagementRole, error: &DecodeError) -> Observed {
let mut report = Report::new();
report.push(
rules::DECODE_FAILED,
"",
alloc::string::ToString::to_string(error),
);
Observed {
sender,
kind: error.peek().and_then(|p| p.kind),
message: None,
pruned: Vec::new(),
report,
status: error.status_value(),
}
}
fn record(&mut self, message: &Message, now: Timestamp) {
match message {
Message::SelectControlType(select) => {
self.phase = Phase::selected(select.control_type);
}
Message::RevokeObject(revoke) => {
self.registry.revoke(revoke.object_type, revoke.object_id);
}
_ => self.registry.record(message, Some(now)),
}
if let Some(id) = message.id()
&& !self.seen.contains(&id)
{
self.seen.push(id);
if self.seen.len() > Registry::MAX_TRACKED {
self.seen.remove(0);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::common::EnergyManagementRole::{Cem, Rm};
use alloc::string::ToString;
use alloc::vec;
fn at(s: &str) -> Timestamp {
s.parse().unwrap_or(Timestamp::UNIX_EPOCH)
}
const DETAILS: &str = r#"{"message_type":"ResourceManagerDetails","message_id":"d1",
"resource_id":"battery-1","roles":[{"role":"ENERGY_STORAGE","commodity":"ELECTRICITY"}],
"instruction_processing_delay":500,
"available_control_types":["FILL_RATE_BASED_CONTROL"],
"provides_forecast":false,
"provides_power_measurement_types":["ELECTRIC.POWER.3_PHASE_SYMMETRIC"]}"#;
const SYSTEM: &str = r#"{"message_type":"FRBC.SystemDescription","message_id":"s1",
"valid_from":"2024-01-01T00:00:00Z",
"actuators":[{"id":"actuator1","supported_commodities":["ELECTRICITY"],
"operation_modes":[{"id":"om1","elements":[{"fill_level_range":{"start_of_range":0,"end_of_range":100},
"fill_rate":{"start_of_range":0,"end_of_range":0.001},
"power_ranges":[{"start_of_range":0,"end_of_range":5000,
"commodity_quantity":"ELECTRIC.POWER.3_PHASE_SYMMETRIC"}]}],
"abnormal_condition_only":false}],
"transitions":[],"timers":[]}],
"storage":{"provides_leakage_behaviour":false,"provides_fill_level_target_profile":false,
"provides_usage_forecast":false,
"fill_level_range":{"start_of_range":0,"end_of_range":100}}}"#;
fn instruction(id: &str, actuator: &str) -> alloc::string::String {
alloc::format!(
r#"{{"message_type":"FRBC.Instruction","message_id":"{id}","id":"i-{id}",
"actuator_id":"{actuator}","operation_mode":"om1","operation_mode_factor":0.5,
"execution_time":"2024-01-01T12:00:00Z","abnormal_condition":false}}"#
)
}
fn opened() -> Analyzer {
let mut a = Analyzer::new();
let now = at("2024-01-01T12:00:00Z");
assert!(a.observe(Rm, DETAILS, now).is_clean());
assert!(
a.observe(
Cem,
r#"{"message_type":"SelectControlType","message_id":"c1",
"control_type":"FILL_RATE_BASED_CONTROL"}"#,
now
)
.is_clean()
);
assert_eq!(
a.active_control_type(),
Some(ControlType::FillRateBasedControl)
);
let observed = a.observe(Rm, SYSTEM, now);
assert!(observed.is_clean(), "{}", observed.report);
a
}
#[test]
fn an_instruction_is_checked_against_a_description_the_observer_only_watched() {
let mut a = opened();
let now = at("2024-01-01T12:00:01Z");
let good = a.observe(Cem, &instruction("m1", "actuator1"), now);
assert!(good.is_clean(), "{}", good.report);
let bad = a.observe(Cem, &instruction("m2", "nope"), now);
assert!(
bad.report.contains(rules::FRBC_UNKNOWN_ACTUATOR),
"{}",
bad.report
);
}
#[test]
fn the_state_table_applies_to_a_conversation_nobody_is_in() {
let mut a = Analyzer::new();
let now = at("2024-01-01T12:00:00Z");
let observed = a.observe(Cem, &instruction("m1", "actuator1"), now);
assert!(observed.report.contains(rules::NOT_ALLOWED_IN_STATE));
let observed = a.observe(
Rm,
r#"{"message_type":"SelectControlType","message_id":"c1",
"control_type":"FILL_RATE_BASED_CONTROL"}"#,
now,
);
assert!(observed.report.contains(rules::NOT_ALLOWED_FOR_ROLE));
}
#[test]
fn a_reused_instruction_identifier_is_seen_across_the_whole_conversation() {
let mut a = opened();
let now = at("2024-01-01T12:00:01Z");
let first = a.observe(Cem, &instruction("m1", "actuator1"), now);
assert!(first.is_clean(), "{}", first.report);
let text = instruction("m1", "actuator1").replace("\"m1\"", "\"m2\"");
let again = a.observe(Cem, &text, now);
assert!(
again.report.contains(rules::DUPLICATE_INSTRUCTION_ID),
"{}",
again.report
);
}
#[test]
fn a_vendor_extension_is_reported_rather_than_refused() {
let mut a = Analyzer::new();
let now = at("2024-01-01T12:00:00Z");
let observed = a.observe(
Rm,
r#"{"message_type":"FRBC.StorageStatus","message_id":"m1",
"present_fill_level":52.0,"acme_cell_temperature":31.4}"#,
now,
);
assert_eq!(observed.pruned, vec!["/acme_cell_temperature".to_string()]);
assert!(observed.report.contains(rules::UNKNOWN_PROPERTY));
assert!(observed.message.is_some(), "the message is still forwarded");
let mut a = Analyzer::new().strict();
let observed = a.observe(
Rm,
r#"{"message_type":"FRBC.StorageStatus","message_id":"m1",
"present_fill_level":52.0,"acme_cell_temperature":31.4}"#,
now,
);
assert!(observed.message.is_none());
assert!(observed.report.contains(rules::DECODE_FAILED));
assert_eq!(observed.kind, Some(MessageKind::FrbcStorageStatus));
}
#[test]
fn a_frame_that_is_not_s2_at_all_is_a_finding_and_not_the_end() {
let mut a = Analyzer::new();
let now = at("2024-01-01T12:00:00Z");
let observed = a.observe(Rm, "{ not json", now);
assert!(observed.report.contains(rules::DECODE_FAILED));
assert_eq!(observed.kind, None);
assert!(a.observe(Rm, DETAILS, now).is_clean());
}
#[test]
fn a_description_published_for_later_is_in_force_when_its_time_comes() {
let mut a = Analyzer::new();
let early = at("2024-01-01T12:00:00Z");
a.observe(
Cem,
r#"{"message_type":"SelectControlType","message_id":"c1",
"control_type":"FILL_RATE_BASED_CONTROL"}"#,
early,
);
let later = SYSTEM.replace("2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z");
assert!(a.observe(Rm, &later, early).is_clean());
assert!(a.registry().frbc.is_none());
let too_soon = a.observe(Cem, &instruction("m1", "actuator1"), early);
assert!(!too_soon.report.contains(rules::FRBC_UNKNOWN_ACTUATOR));
let after = at("2024-01-02T00:00:01Z");
let now_fine = a.observe(Cem, &instruction("m2", "actuator1"), after);
assert!(now_fine.is_clean(), "{}", now_fine.report);
assert!(a.registry().frbc.is_some());
let wrong = a.observe(Cem, &instruction("m3", "nope"), after);
assert!(wrong.report.contains(rules::FRBC_UNKNOWN_ACTUATOR));
}
}