1use alloc::string::String;
35use alloc::vec::Vec;
36
37use super::core::Registry;
38use crate::codec::{self, DecodeError, DecodeOptions, Strictness};
39use crate::message::{Message, MessageKind};
40use crate::types::common::{ControlType, EnergyManagementRole, ReceptionStatusValues};
41use crate::types::{Duration, Id, Timestamp, WireProfile};
42use crate::validate::{Phase, Report, Validate, rules};
43
44#[derive(Debug, Clone, PartialEq)]
46#[non_exhaustive]
47pub struct Observed {
48 pub sender: EnergyManagementRole,
50 pub kind: Option<MessageKind>,
52 pub message: Option<Message>,
54 pub pruned: Vec<String>,
56 pub report: Report,
58 pub status: ReceptionStatusValues,
68}
69
70impl Observed {
71 #[must_use]
73 pub fn is_clean(&self) -> bool {
74 self.report.is_empty()
75 }
76
77 #[must_use]
79 pub fn accepted(&self) -> bool {
80 self.status == ReceptionStatusValues::Ok
81 }
82
83 #[must_use]
85 pub fn diagnostic_label(&self) -> Option<String> {
86 self.report.diagnostic_label()
87 }
88}
89
90#[derive(Debug, Clone)]
102pub struct Analyzer {
103 registry: Registry,
104 profile: WireProfile,
105 strictness: Strictness,
106 phase: Phase,
107 seen: Vec<Id>,
108 skew_tolerance: Duration,
109 s2_connect: bool,
110 max_message_bytes: usize,
111}
112
113impl Default for Analyzer {
114 fn default() -> Self {
115 Self::new()
116 }
117}
118
119impl Analyzer {
120 #[must_use]
122 pub fn new() -> Self {
123 Self {
124 registry: Registry::default(),
125 profile: WireProfile::V1_0_0,
126 strictness: Strictness::Lenient,
127 phase: Phase::Connected,
132 seen: Vec::new(),
133 skew_tolerance: Duration::from_secs(30),
134 s2_connect: false,
135 max_message_bytes: DecodeOptions::DEFAULT_MAX_BYTES,
136 }
137 }
138
139 #[must_use]
144 pub const fn profile(mut self, profile: WireProfile) -> Self {
145 self.profile = profile;
146 self
147 }
148
149 #[must_use]
151 pub const fn strict(mut self) -> Self {
152 self.strictness = Strictness::Strict;
153 self
154 }
155
156 #[must_use]
158 pub const fn over_s2_connect(mut self) -> Self {
159 self.s2_connect = true;
160 self
161 }
162
163 #[must_use]
165 pub const fn skew_tolerance(mut self, tolerance: Duration) -> Self {
166 self.skew_tolerance = tolerance;
167 self
168 }
169
170 #[must_use]
172 pub const fn registry(&self) -> &Registry {
173 &self.registry
174 }
175
176 #[must_use]
178 pub const fn active_control_type(&self) -> Option<ControlType> {
179 self.phase.active_control_type()
180 }
181
182 #[must_use]
184 pub const fn phase(&self) -> Phase {
185 self.phase
186 }
187
188 pub fn observe(
194 &mut self,
195 sender: EnergyManagementRole,
196 text: &str,
197 now: Timestamp,
198 ) -> Observed {
199 let options = DecodeOptions {
200 strictness: self.strictness,
201 profile: self.profile,
202 max_bytes: self.max_message_bytes,
203 };
204 let _ = self.registry.activate_due(now);
207
208 match codec::decode_with(text, &options) {
209 Err(error) => Self::on_decode_error(sender, &error),
210 Ok(decoded) => {
211 let mut report = Report::new();
212 for path in &decoded.pruned {
213 report.push(
214 rules::UNKNOWN_PROPERTY,
215 path,
216 "property is not defined by the schema and was removed",
217 );
218 }
219 let kind = decoded.message.kind();
220 {
221 let ctx = self.registry.context(
222 self.profile,
223 sender,
224 self.phase,
225 self.s2_connect,
226 now,
227 &self.seen,
228 self.skew_tolerance,
229 );
230 report.extend(decoded.message.validate(&ctx));
231 }
232 let status = report.reception_status();
233 self.record(&decoded.message, now);
234 Observed {
235 sender,
236 kind: Some(kind),
237 message: Some(decoded.message),
238 pruned: decoded.pruned,
239 report,
240 status,
241 }
242 }
243 }
244 }
245
246 fn on_decode_error(sender: EnergyManagementRole, error: &DecodeError) -> Observed {
247 let mut report = Report::new();
248 report.push(
249 rules::DECODE_FAILED,
250 "",
251 alloc::string::ToString::to_string(error),
252 );
253 Observed {
254 sender,
255 kind: error.peek().and_then(|p| p.kind),
256 message: None,
257 pruned: Vec::new(),
258 report,
259 status: error.status_value(),
260 }
261 }
262
263 fn record(&mut self, message: &Message, now: Timestamp) {
265 match message {
266 Message::SelectControlType(select) => {
270 self.phase = Phase::selected(select.control_type);
271 }
272 Message::RevokeObject(revoke) => {
273 self.registry.revoke(revoke.object_type, revoke.object_id);
274 }
275 _ => self.registry.record(message, Some(now)),
276 }
277 if let Some(id) = message.id()
278 && !self.seen.contains(&id)
279 {
280 self.seen.push(id);
281 if self.seen.len() > Registry::MAX_TRACKED {
282 self.seen.remove(0);
283 }
284 }
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291 use crate::types::common::EnergyManagementRole::{Cem, Rm};
292 use alloc::string::ToString;
295 use alloc::vec;
296
297 fn at(s: &str) -> Timestamp {
298 s.parse().unwrap_or(Timestamp::UNIX_EPOCH)
299 }
300
301 const DETAILS: &str = r#"{"message_type":"ResourceManagerDetails","message_id":"d1",
302 "resource_id":"battery-1","roles":[{"role":"ENERGY_STORAGE","commodity":"ELECTRICITY"}],
303 "instruction_processing_delay":500,
304 "available_control_types":["FILL_RATE_BASED_CONTROL"],
305 "provides_forecast":false,
306 "provides_power_measurement_types":["ELECTRIC.POWER.3_PHASE_SYMMETRIC"]}"#;
307
308 const SYSTEM: &str = r#"{"message_type":"FRBC.SystemDescription","message_id":"s1",
309 "valid_from":"2024-01-01T00:00:00Z",
310 "actuators":[{"id":"actuator1","supported_commodities":["ELECTRICITY"],
311 "operation_modes":[{"id":"om1","elements":[{"fill_level_range":{"start_of_range":0,"end_of_range":100},
312 "fill_rate":{"start_of_range":0,"end_of_range":0.001},
313 "power_ranges":[{"start_of_range":0,"end_of_range":5000,
314 "commodity_quantity":"ELECTRIC.POWER.3_PHASE_SYMMETRIC"}]}],
315 "abnormal_condition_only":false}],
316 "transitions":[],"timers":[]}],
317 "storage":{"provides_leakage_behaviour":false,"provides_fill_level_target_profile":false,
318 "provides_usage_forecast":false,
319 "fill_level_range":{"start_of_range":0,"end_of_range":100}}}"#;
320
321 fn instruction(id: &str, actuator: &str) -> alloc::string::String {
322 alloc::format!(
323 r#"{{"message_type":"FRBC.Instruction","message_id":"{id}","id":"i-{id}",
324 "actuator_id":"{actuator}","operation_mode":"om1","operation_mode_factor":0.5,
325 "execution_time":"2024-01-01T12:00:00Z","abnormal_condition":false}}"#
326 )
327 }
328
329 fn opened() -> Analyzer {
331 let mut a = Analyzer::new();
332 let now = at("2024-01-01T12:00:00Z");
333 assert!(a.observe(Rm, DETAILS, now).is_clean());
334 assert!(
335 a.observe(
336 Cem,
337 r#"{"message_type":"SelectControlType","message_id":"c1",
338 "control_type":"FILL_RATE_BASED_CONTROL"}"#,
339 now
340 )
341 .is_clean()
342 );
343 assert_eq!(
344 a.active_control_type(),
345 Some(ControlType::FillRateBasedControl)
346 );
347 let observed = a.observe(Rm, SYSTEM, now);
348 assert!(observed.is_clean(), "{}", observed.report);
349 a
350 }
351
352 #[test]
353 fn an_instruction_is_checked_against_a_description_the_observer_only_watched() {
354 let mut a = opened();
358 let now = at("2024-01-01T12:00:01Z");
359
360 let good = a.observe(Cem, &instruction("m1", "actuator1"), now);
361 assert!(good.is_clean(), "{}", good.report);
362
363 let bad = a.observe(Cem, &instruction("m2", "nope"), now);
364 assert!(
365 bad.report.contains(rules::FRBC_UNKNOWN_ACTUATOR),
366 "{}",
367 bad.report
368 );
369 }
370
371 #[test]
372 fn the_state_table_applies_to_a_conversation_nobody_is_in() {
373 let mut a = Analyzer::new();
374 let now = at("2024-01-01T12:00:00Z");
375 let observed = a.observe(Cem, &instruction("m1", "actuator1"), now);
377 assert!(observed.report.contains(rules::NOT_ALLOWED_IN_STATE));
378
379 let observed = a.observe(
381 Rm,
382 r#"{"message_type":"SelectControlType","message_id":"c1",
383 "control_type":"FILL_RATE_BASED_CONTROL"}"#,
384 now,
385 );
386 assert!(observed.report.contains(rules::NOT_ALLOWED_FOR_ROLE));
387 }
388
389 #[test]
390 fn a_reused_instruction_identifier_is_seen_across_the_whole_conversation() {
391 let mut a = opened();
392 let now = at("2024-01-01T12:00:01Z");
393 let first = a.observe(Cem, &instruction("m1", "actuator1"), now);
394 assert!(first.is_clean(), "{}", first.report);
395 let text = instruction("m1", "actuator1").replace("\"m1\"", "\"m2\"");
397 let again = a.observe(Cem, &text, now);
398 assert!(
399 again.report.contains(rules::DUPLICATE_INSTRUCTION_ID),
400 "{}",
401 again.report
402 );
403 }
404
405 #[test]
406 fn a_vendor_extension_is_reported_rather_than_refused() {
407 let mut a = Analyzer::new();
408 let now = at("2024-01-01T12:00:00Z");
409 let observed = a.observe(
410 Rm,
411 r#"{"message_type":"FRBC.StorageStatus","message_id":"m1",
412 "present_fill_level":52.0,"acme_cell_temperature":31.4}"#,
413 now,
414 );
415 assert_eq!(observed.pruned, vec!["/acme_cell_temperature".to_string()]);
416 assert!(observed.report.contains(rules::UNKNOWN_PROPERTY));
417 assert!(observed.message.is_some(), "the message is still forwarded");
418
419 let mut a = Analyzer::new().strict();
422 let observed = a.observe(
423 Rm,
424 r#"{"message_type":"FRBC.StorageStatus","message_id":"m1",
425 "present_fill_level":52.0,"acme_cell_temperature":31.4}"#,
426 now,
427 );
428 assert!(observed.message.is_none());
429 assert!(observed.report.contains(rules::DECODE_FAILED));
430 assert_eq!(observed.kind, Some(MessageKind::FrbcStorageStatus));
431 }
432
433 #[test]
434 fn a_frame_that_is_not_s2_at_all_is_a_finding_and_not_the_end() {
435 let mut a = Analyzer::new();
436 let now = at("2024-01-01T12:00:00Z");
437 let observed = a.observe(Rm, "{ not json", now);
438 assert!(observed.report.contains(rules::DECODE_FAILED));
439 assert_eq!(observed.kind, None);
440 assert!(a.observe(Rm, DETAILS, now).is_clean());
442 }
443
444 #[test]
445 fn a_description_published_for_later_is_in_force_when_its_time_comes() {
446 let mut a = Analyzer::new();
447 let early = at("2024-01-01T12:00:00Z");
448 a.observe(
449 Cem,
450 r#"{"message_type":"SelectControlType","message_id":"c1",
451 "control_type":"FILL_RATE_BASED_CONTROL"}"#,
452 early,
453 );
454 let later = SYSTEM.replace("2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z");
455 assert!(a.observe(Rm, &later, early).is_clean());
456 assert!(a.registry().frbc.is_none());
460 let too_soon = a.observe(Cem, &instruction("m1", "actuator1"), early);
461 assert!(!too_soon.report.contains(rules::FRBC_UNKNOWN_ACTUATOR));
462
463 let after = at("2024-01-02T00:00:01Z");
466 let now_fine = a.observe(Cem, &instruction("m2", "actuator1"), after);
467 assert!(now_fine.is_clean(), "{}", now_fine.report);
468 assert!(a.registry().frbc.is_some());
469 let wrong = a.observe(Cem, &instruction("m3", "nope"), after);
470 assert!(wrong.report.contains(rules::FRBC_UNKNOWN_ACTUATOR));
471 }
472}