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::{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 active: Option<ControlType>,
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 active: None,
128 seen: Vec::new(),
129 skew_tolerance: Duration::from_secs(30),
130 s2_connect: false,
131 max_message_bytes: DecodeOptions::DEFAULT_MAX_BYTES,
132 }
133 }
134
135 #[must_use]
140 pub const fn profile(mut self, profile: WireProfile) -> Self {
141 self.profile = profile;
142 self
143 }
144
145 #[must_use]
147 pub const fn strict(mut self) -> Self {
148 self.strictness = Strictness::Strict;
149 self
150 }
151
152 #[must_use]
154 pub const fn over_s2_connect(mut self) -> Self {
155 self.s2_connect = true;
156 self
157 }
158
159 #[must_use]
161 pub const fn skew_tolerance(mut self, tolerance: Duration) -> Self {
162 self.skew_tolerance = tolerance;
163 self
164 }
165
166 #[must_use]
168 pub const fn registry(&self) -> &Registry {
169 &self.registry
170 }
171
172 #[must_use]
174 pub const fn active_control_type(&self) -> Option<ControlType> {
175 self.active
176 }
177
178 pub fn observe(
184 &mut self,
185 sender: EnergyManagementRole,
186 text: &str,
187 now: Timestamp,
188 ) -> Observed {
189 let options = DecodeOptions {
190 strictness: self.strictness,
191 profile: self.profile,
192 max_bytes: self.max_message_bytes,
193 };
194 let _ = self.registry.activate_due(now);
197
198 match codec::decode_with(text, &options) {
199 Err(error) => Self::on_decode_error(sender, &error),
200 Ok(decoded) => {
201 let mut report = Report::new();
202 for path in &decoded.pruned {
203 report.push(
204 rules::UNKNOWN_PROPERTY,
205 path,
206 "property is not defined by the schema and was removed",
207 );
208 }
209 let kind = decoded.message.kind();
210 {
211 let ctx = self.registry.context(
212 self.profile,
213 sender,
214 self.active,
215 self.s2_connect,
216 now,
217 &self.seen,
218 self.skew_tolerance,
219 );
220 report.extend(decoded.message.validate(&ctx));
221 }
222 let status = report.reception_status();
223 self.record(&decoded.message, now);
224 Observed {
225 sender,
226 kind: Some(kind),
227 message: Some(decoded.message),
228 pruned: decoded.pruned,
229 report,
230 status,
231 }
232 }
233 }
234 }
235
236 fn on_decode_error(sender: EnergyManagementRole, error: &DecodeError) -> Observed {
237 let mut report = Report::new();
238 report.push(
239 rules::DECODE_FAILED,
240 "",
241 alloc::string::ToString::to_string(error),
242 );
243 Observed {
244 sender,
245 kind: error.peek().and_then(|p| p.kind),
246 message: None,
247 pruned: Vec::new(),
248 report,
249 status: error.status_value(),
250 }
251 }
252
253 fn record(&mut self, message: &Message, now: Timestamp) {
255 match message {
256 Message::SelectControlType(select) => {
260 self.active = (select.control_type != ControlType::NoSelection)
261 .then_some(select.control_type);
262 }
263 Message::RevokeObject(revoke) => {
264 self.registry.revoke(revoke.object_type, revoke.object_id);
265 }
266 _ => self.registry.record(message, Some(now)),
267 }
268 if let Some(id) = message.id()
269 && !self.seen.contains(&id)
270 {
271 self.seen.push(id);
272 if self.seen.len() > Registry::MAX_TRACKED {
273 self.seen.remove(0);
274 }
275 }
276 }
277}
278
279#[cfg(test)]
280mod tests {
281 use super::*;
282 use crate::types::common::EnergyManagementRole::{Cem, Rm};
283 use alloc::string::ToString;
286 use alloc::vec;
287
288 fn at(s: &str) -> Timestamp {
289 s.parse().unwrap_or(Timestamp::UNIX_EPOCH)
290 }
291
292 const DETAILS: &str = r#"{"message_type":"ResourceManagerDetails","message_id":"d1",
293 "resource_id":"battery-1","roles":[{"role":"ENERGY_STORAGE","commodity":"ELECTRICITY"}],
294 "instruction_processing_delay":500,
295 "available_control_types":["FILL_RATE_BASED_CONTROL"],
296 "provides_forecast":false,
297 "provides_power_measurement_types":["ELECTRIC.POWER.3_PHASE_SYMMETRIC"]}"#;
298
299 const SYSTEM: &str = r#"{"message_type":"FRBC.SystemDescription","message_id":"s1",
300 "valid_from":"2024-01-01T00:00:00Z",
301 "actuators":[{"id":"actuator1","supported_commodities":["ELECTRICITY"],
302 "operation_modes":[{"id":"om1","elements":[{"fill_level_range":{"start_of_range":0,"end_of_range":100},
303 "fill_rate":{"start_of_range":0,"end_of_range":0.001},
304 "power_ranges":[{"start_of_range":0,"end_of_range":5000,
305 "commodity_quantity":"ELECTRIC.POWER.3_PHASE_SYMMETRIC"}]}],
306 "abnormal_condition_only":false}],
307 "transitions":[],"timers":[]}],
308 "storage":{"provides_leakage_behaviour":false,"provides_fill_level_target_profile":false,
309 "provides_usage_forecast":false,
310 "fill_level_range":{"start_of_range":0,"end_of_range":100}}}"#;
311
312 fn instruction(id: &str, actuator: &str) -> alloc::string::String {
313 alloc::format!(
314 r#"{{"message_type":"FRBC.Instruction","message_id":"{id}","id":"i-{id}",
315 "actuator_id":"{actuator}","operation_mode":"om1","operation_mode_factor":0.5,
316 "execution_time":"2024-01-01T12:00:00Z","abnormal_condition":false}}"#
317 )
318 }
319
320 fn opened() -> Analyzer {
322 let mut a = Analyzer::new();
323 let now = at("2024-01-01T12:00:00Z");
324 assert!(a.observe(Rm, DETAILS, now).is_clean());
325 assert!(
326 a.observe(
327 Cem,
328 r#"{"message_type":"SelectControlType","message_id":"c1",
329 "control_type":"FILL_RATE_BASED_CONTROL"}"#,
330 now
331 )
332 .is_clean()
333 );
334 assert_eq!(
335 a.active_control_type(),
336 Some(ControlType::FillRateBasedControl)
337 );
338 let observed = a.observe(Rm, SYSTEM, now);
339 assert!(observed.is_clean(), "{}", observed.report);
340 a
341 }
342
343 #[test]
344 fn an_instruction_is_checked_against_a_description_the_observer_only_watched() {
345 let mut a = opened();
349 let now = at("2024-01-01T12:00:01Z");
350
351 let good = a.observe(Cem, &instruction("m1", "actuator1"), now);
352 assert!(good.is_clean(), "{}", good.report);
353
354 let bad = a.observe(Cem, &instruction("m2", "nope"), now);
355 assert!(
356 bad.report.contains(rules::FRBC_UNKNOWN_ACTUATOR),
357 "{}",
358 bad.report
359 );
360 }
361
362 #[test]
363 fn the_state_table_applies_to_a_conversation_nobody_is_in() {
364 let mut a = Analyzer::new();
365 let now = at("2024-01-01T12:00:00Z");
366 let observed = a.observe(Cem, &instruction("m1", "actuator1"), now);
368 assert!(observed.report.contains(rules::NOT_ALLOWED_IN_STATE));
369
370 let observed = a.observe(
372 Rm,
373 r#"{"message_type":"SelectControlType","message_id":"c1",
374 "control_type":"FILL_RATE_BASED_CONTROL"}"#,
375 now,
376 );
377 assert!(observed.report.contains(rules::NOT_ALLOWED_FOR_ROLE));
378 }
379
380 #[test]
381 fn a_reused_instruction_identifier_is_seen_across_the_whole_conversation() {
382 let mut a = opened();
383 let now = at("2024-01-01T12:00:01Z");
384 let first = a.observe(Cem, &instruction("m1", "actuator1"), now);
385 assert!(first.is_clean(), "{}", first.report);
386 let text = instruction("m1", "actuator1").replace("\"m1\"", "\"m2\"");
388 let again = a.observe(Cem, &text, now);
389 assert!(
390 again.report.contains(rules::DUPLICATE_INSTRUCTION_ID),
391 "{}",
392 again.report
393 );
394 }
395
396 #[test]
397 fn a_vendor_extension_is_reported_rather_than_refused() {
398 let mut a = Analyzer::new();
399 let now = at("2024-01-01T12:00:00Z");
400 let observed = a.observe(
401 Rm,
402 r#"{"message_type":"FRBC.StorageStatus","message_id":"m1",
403 "present_fill_level":52.0,"acme_cell_temperature":31.4}"#,
404 now,
405 );
406 assert_eq!(observed.pruned, vec!["/acme_cell_temperature".to_string()]);
407 assert!(observed.report.contains(rules::UNKNOWN_PROPERTY));
408 assert!(observed.message.is_some(), "the message is still forwarded");
409
410 let mut a = Analyzer::new().strict();
413 let observed = a.observe(
414 Rm,
415 r#"{"message_type":"FRBC.StorageStatus","message_id":"m1",
416 "present_fill_level":52.0,"acme_cell_temperature":31.4}"#,
417 now,
418 );
419 assert!(observed.message.is_none());
420 assert!(observed.report.contains(rules::DECODE_FAILED));
421 assert_eq!(observed.kind, Some(MessageKind::FrbcStorageStatus));
422 }
423
424 #[test]
425 fn a_frame_that_is_not_s2_at_all_is_a_finding_and_not_the_end() {
426 let mut a = Analyzer::new();
427 let now = at("2024-01-01T12:00:00Z");
428 let observed = a.observe(Rm, "{ not json", now);
429 assert!(observed.report.contains(rules::DECODE_FAILED));
430 assert_eq!(observed.kind, None);
431 assert!(a.observe(Rm, DETAILS, now).is_clean());
433 }
434
435 #[test]
436 fn a_description_published_for_later_is_in_force_when_its_time_comes() {
437 let mut a = Analyzer::new();
438 let early = at("2024-01-01T12:00:00Z");
439 a.observe(
440 Cem,
441 r#"{"message_type":"SelectControlType","message_id":"c1",
442 "control_type":"FILL_RATE_BASED_CONTROL"}"#,
443 early,
444 );
445 let later = SYSTEM.replace("2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z");
446 assert!(a.observe(Rm, &later, early).is_clean());
447 assert!(a.registry().frbc.is_none());
451 let too_soon = a.observe(Cem, &instruction("m1", "actuator1"), early);
452 assert!(!too_soon.report.contains(rules::FRBC_UNKNOWN_ACTUATOR));
453
454 let after = at("2024-01-02T00:00:01Z");
457 let now_fine = a.observe(Cem, &instruction("m2", "actuator1"), after);
458 assert!(now_fine.is_clean(), "{}", now_fine.report);
459 assert!(a.registry().frbc.is_some());
460 let wrong = a.observe(Cem, &instruction("m3", "nope"), after);
461 assert!(wrong.report.contains(rules::FRBC_UNKNOWN_ACTUATOR));
462 }
463}