1use core::{fmt, time::Duration};
4use eebus::{
5 model::{CmdData, FeatureType, Function, MeasurementDescriptionData, MeasurementId, Role},
6 ship::Ski,
7 spine::Engine,
8 usecases::monitoring::{
9 Measurand, MonitoringApplianceActor, MonitoringEvent, Reading, ReadingState, UnitId,
10 },
11 usecases::{mgcp, mpc},
12};
13use iec61850_kit::{
14 ObjectReference,
15 common::{Quality, TimeQuality, UtcTime, Validity},
16 proto::{
17 data::Value,
18 mms::{ConfirmedRequest, ObjectName, VariableAccess, VariableSpecification},
19 },
20 server::{Answer, DATA_ACCESS_NON_EXISTENT},
21};
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum MeasurementSource {
27 Mpc,
28 Mgcp,
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub struct InvalidMeasurementMapping;
34impl fmt::Display for InvalidMeasurementMapping {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 f.write_str(
37 "expected a logical device and node, a device and entity, and a positive maximum age",
38 )
39 }
40}
41impl std::error::Error for InvalidMeasurementMapping {}
42
43const UNAVAILABLE: i64 = 2; const INVALID: Quality = Quality {
45 validity: Validity::Invalid,
46 ..Quality::GOOD
47};
48
49pub struct PowerReadback {
52 domain: String,
53 node: String,
54 source: MeasurementSource,
55 peer: Ski,
56 unit: UnitId,
57 max_age: Duration,
58 described: bool,
59 latest: Option<Duration>,
60 source_timestamp: Option<Duration>,
61 watts: Option<f32>,
62 observed: Duration,
63 expires: Duration,
64 quality: Quality,
65}
66
67impl PowerReadback {
68 pub fn new(
72 domain: &str,
73 logical_node: &str,
74 source: MeasurementSource,
75 peer: Ski,
76 unit: UnitId,
77 max_age: Duration,
78 ) -> Result<Self, InvalidMeasurementMapping> {
79 let name = format!("{domain}/{logical_node}");
80 let r = ObjectReference::parse(&name).map_err(|_| InvalidMeasurementMapping)?;
81 if r.ld != domain
82 || r.ln != logical_node
83 || max_age.is_zero()
84 || unit.device.as_str().trim().is_empty()
85 || unit.entity.is_empty()
86 {
87 return Err(InvalidMeasurementMapping);
88 }
89 Ok(Self {
90 domain: domain.into(),
91 node: logical_node.into(),
92 source,
93 peer,
94 unit,
95 max_age,
96 described: false,
97 latest: None,
98 source_timestamp: None,
99 watts: None,
100 observed: Duration::ZERO,
101 expires: Duration::ZERO,
102 quality: INVALID,
103 })
104 }
105
106 pub fn commission(
111 &mut self,
112 peer: &Ski,
113 engine: &Engine,
114 actor: &MonitoringApplianceActor,
115 ) -> Result<(), InvalidMeasurementMapping> {
116 if *peer != self.peer {
117 return Err(InvalidMeasurementMapping);
118 }
119 self.disconnect();
120 let remote = engine
121 .peer(&self.unit.device)
122 .ok_or(InvalidMeasurementMapping)?;
123 let (descriptor, scenario) = match self.source {
124 MeasurementSource::Mpc => (&mpc::MONITORED_UNIT, 1),
125 MeasurementSource::Mgcp => (&mgcp::GRID_CONNECTION_POINT, 2),
126 };
127 let feature = actor
128 .units()
129 .find(|p| p.is_unit(&self.unit))
130 .and_then(|p| p.measurement.as_ref())
131 .ok_or(InvalidMeasurementMapping)?;
132 if UnitId::of(feature).as_ref() != Some(&self.unit)
133 || !remote
134 .use_cases_played(descriptor.name, descriptor.actor)
135 .any(|uc| {
136 uc.available
137 && uc.scenarios.contains(&scenario)
138 && remote
139 .address_of(uc, &FeatureType::Measurement, Role::Server)
140 .as_ref()
141 == Some(feature)
142 })
143 {
144 return Err(InvalidMeasurementMapping);
145 }
146 let mut ids = actor
147 .readings(&self.unit)
148 .ok_or(InvalidMeasurementMapping)?
149 .described()
150 .filter_map(|(id, kind)| (kind == Measurand::total_power()).then_some(id));
151 let id = ids.next().ok_or(InvalidMeasurementMapping)?;
152 let Some(CmdData::MeasurementDescriptionListData(list)) =
153 engine.remote_data(feature, &Function::MeasurementDescriptionListData)
154 else {
155 return Err(InvalidMeasurementMapping);
156 };
157 if ids.next().is_some()
158 || !watt_description(
159 list.measurement_description_data
160 .as_deref()
161 .unwrap_or_default(),
162 id,
163 )
164 {
165 return Err(InvalidMeasurementMapping);
166 }
167 self.described = true;
168 Ok(())
169 }
170
171 pub fn observe(
176 &mut self,
177 source: MeasurementSource,
178 peer: &Ski,
179 event: &MonitoringEvent,
180 utc: Duration,
181 now: Duration,
182 ) {
183 if self.source != source || self.peer != *peer {
184 return;
185 }
186 let readings = match event {
187 MonitoringEvent::Measured { unit, readings }
188 if unit == &self.unit && self.described =>
189 {
190 readings
191 }
192 _ => return,
193 };
194 let mut total = readings
195 .iter()
196 .filter(|r| r.measurand == Measurand::total_power());
197 let Some(reading) = total.next() else { return };
198 if total.next().is_some() || now < self.observed {
199 self.source_timestamp = None;
200 self.invalidate(INVALID);
201 return;
202 }
203 self.observed = now;
204 let Some(stamp) = source_time(reading, utc) else {
205 self.source_timestamp = None;
206 self.invalidate(INVALID);
207 return;
208 };
209 if self.latest.is_some_and(|previous| stamp < previous) {
210 return;
211 }
212 let duplicate = self.latest == Some(stamp);
213 self.latest = Some(stamp);
214 self.source_timestamp = Some(stamp);
215 let watts = reading.value.and_then(|raw| {
216 let rounded = raw as f32;
217 (rounded.is_finite() && (raw == 0.0 || rounded != 0.0)).then_some(rounded)
218 });
219 let Some(watts) = watts.filter(|_| reading.state == ReadingState::Normal) else {
220 self.invalidate(Quality {
221 out_of_range: reading.state == ReadingState::OutOfRange,
222 failure: reading.state == ReadingState::Error,
223 ..INVALID
224 });
225 return;
226 };
227 let age = utc - stamp;
228 if age >= self.max_age {
229 self.invalidate(Quality {
230 old_data: true,
231 ..INVALID
232 });
233 return;
234 }
235 let expiry = now.saturating_add(self.max_age - age);
236 if !duplicate {
237 self.expires = expiry;
238 self.watts = Some(watts);
239 self.quality = Quality::GOOD;
240 } else if self.watts.is_some_and(|old| old != watts) {
241 self.invalidate(Quality {
242 inconsistent: true,
243 ..INVALID
244 });
245 } else {
246 self.expires = self.expires.min(expiry);
247 }
248 }
249
250 pub fn disconnect(&mut self) {
253 self.described = false;
254 self.source_timestamp = None;
255 self.invalidate(INVALID);
256 }
257
258 fn invalidate(&mut self, quality: Quality) {
259 self.watts = None;
260 self.quality = quality;
261 }
262
263 pub fn answer_read(&self, request: &ConfirmedRequest<'_>, now: Duration) -> Answer {
267 let ConfirmedRequest::Read {
268 specification_with_result: false,
269 access: VariableAccess::ListOfVariable(vars),
270 } = request
271 else {
272 return Answer::DENIED;
273 };
274 let quality = if self.watts.is_some() && (now < self.observed || now >= self.expires) {
275 Quality {
276 old_data: true,
277 ..INVALID
278 }
279 } else {
280 self.quality
281 };
282 Answer::Read(
283 vars.iter()
284 .map(|var| {
285 let VariableSpecification::Name(ObjectName::DomainSpecific { domain, item }) =
286 var
287 else {
288 return Err(DATA_ACCESS_NON_EXISTENT);
289 };
290 let Some((node, path)) = item.split_once('$') else {
291 return Err(DATA_ACCESS_NON_EXISTENT);
292 };
293 if *domain != self.domain || node != self.node {
294 return Err(DATA_ACCESS_NON_EXISTENT);
295 }
296 match path {
297 "MX$TotW$mag$f" if quality == Quality::GOOD => {
298 self.watts.map(Value::Float32).ok_or(UNAVAILABLE)
299 }
300 "MX$TotW$mag$f" => Err(UNAVAILABLE),
301 "MX$TotW$q" => Ok(Value::quality(quality)),
302 "MX$TotW$t" => self
303 .source_timestamp
304 .map(|stamp| {
305 Value::UtcTime(UtcTime::from_unix(
306 stamp.as_secs() as u32,
307 stamp.subsec_nanos(),
308 TimeQuality::UNSYNCHRONIZED,
309 ))
310 })
311 .ok_or(UNAVAILABLE),
312 _ => Err(DATA_ACCESS_NON_EXISTENT),
313 }
314 })
315 .collect(),
316 )
317 }
318}
319
320fn watt_description(rows: &[MeasurementDescriptionData], id: MeasurementId) -> bool {
321 let mut matches = rows.iter().filter(|d| d.measurement_id == Some(id));
322 let Some(row) = matches.next() else {
323 return false;
324 };
325 let total = Measurand::total_power();
326 matches.next().is_none()
327 && row.unit == Some(total.unit())
328 && row.measurement_type == Some(total.measurement_type())
329 && row.scope_type == Some(total.scope_type())
330}
331
332fn source_time(reading: &Reading, utc: Duration) -> Option<Duration> {
333 let time = reading.taken_at()?.as_timestamp()?;
334 let stamp = Duration::new(time.unix_seconds()?.try_into().ok()?, time.nanosecond());
335 (stamp <= utc && stamp.as_secs() <= u32::MAX.into()).then_some(stamp)
336}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341 use eebus::model::{AbsoluteOrRelativeTime, ElectricalConnectionPhaseName};
342 use eebus::usecases::monitoring::Quantity;
343
344 const SKI: Ski = Ski::from_bytes([0x51; 20]);
345 const UTC: Duration = Duration::from_secs(100);
346 const NOW: Duration = Duration::from_secs(2);
347 const STAMP: &str = "1970-01-01T00:01:38.500Z";
348 const SOURCE: MeasurementSource = MeasurementSource::Mgcp;
349
350 fn unit() -> UnitId {
351 UnitId {
352 device: "grid-meter".into(),
353 entity: vec![2],
354 }
355 }
356
357 fn mapping() -> PowerReadback {
358 PowerReadback::new("LD0", "MMXU1", SOURCE, SKI, unit(), Duration::from_secs(5)).unwrap()
359 }
360
361 fn reading(stamp: &str) -> Reading {
362 Reading {
363 measurand: Measurand::total_power(),
364 state: ReadingState::Normal,
365 value: Some(-2700.0),
366 timestamp: Some(AbsoluteOrRelativeTime::from(stamp)),
367 }
368 }
369
370 fn describe(map: &mut PowerReadback) {
371 map.described = true; }
373
374 fn measured(r: Reading) -> MonitoringEvent {
375 MonitoringEvent::Measured {
376 unit: unit(),
377 readings: vec![r],
378 }
379 }
380
381 fn read(map: &PowerReadback, now: Duration) -> Vec<Result<Value, i64>> {
382 let vars = [
383 "MMXU1$MX$TotW$mag$f",
384 "MMXU1$MX$TotW$q",
385 "MMXU1$MX$TotW$t",
386 "MMXU2$MX$TotW$mag$f",
387 ]
388 .map(|item| {
389 VariableSpecification::Name(ObjectName::DomainSpecific {
390 domain: "LD0",
391 item,
392 })
393 });
394 let Answer::Read(result) = map.answer_read(
395 &ConfirmedRequest::Read {
396 specification_with_result: false,
397 access: VariableAccess::ListOfVariable(vars.into()),
398 },
399 now,
400 ) else {
401 panic!("expected read response")
402 };
403 assert_eq!(result[3], Err(DATA_ACCESS_NON_EXISTENT));
404 result
405 }
406
407 #[test]
408 fn only_described_exact_peer_source_and_entity_can_publish_total_power() {
409 let mut map = mapping();
410 let event = measured(reading(STAMP));
411 map.observe(SOURCE, &SKI, &event, UTC, NOW);
412 assert_eq!(read(&map, NOW)[0], Err(UNAVAILABLE));
413 describe(&mut map);
414 map.observe(MeasurementSource::Mpc, &SKI, &event, UTC, NOW);
415 map.observe(SOURCE, &Ski::from_bytes([9; 20]), &event, UTC, NOW);
416 let mut other = unit();
417 other.entity = vec![3];
418 map.observe(
419 SOURCE,
420 &SKI,
421 &MonitoringEvent::Measured {
422 unit: other,
423 readings: vec![reading(STAMP)],
424 },
425 UTC,
426 NOW,
427 );
428 let mut phase = reading(STAMP);
429 phase.measurand = Measurand::on(Quantity::Power, ElectricalConnectionPhaseName::A);
430 map.observe(SOURCE, &SKI, &measured(phase), UTC, NOW);
431 assert_eq!(read(&map, NOW)[0], Err(UNAVAILABLE));
432
433 map.observe(SOURCE, &SKI, &event, UTC, NOW);
434 let r = read(&map, NOW);
435 assert_eq!(r[0], Ok(Value::Float32(-2700.0)));
436 assert_eq!(r[1], Ok(Value::quality(Quality::GOOD)));
437 assert_eq!(
438 r[2],
439 Ok(Value::UtcTime(UtcTime::from_unix(
440 98,
441 500_000_000,
442 TimeQuality::UNSYNCHRONIZED
443 )))
444 );
445 }
446
447 #[test]
448 fn source_age_counts_and_duplicates_never_extend_expiry() {
449 let mut map = mapping();
450 describe(&mut map);
451 let event = measured(reading(STAMP));
452 map.observe(SOURCE, &SKI, &event, UTC, NOW);
453 let second = Duration::from_secs(1);
454 map.observe(SOURCE, &SKI, &event, UTC + second, NOW + second);
455 let expiry = NOW + Duration::from_millis(3500);
456 assert_eq!(
457 read(&map, expiry - Duration::from_nanos(1))[0],
458 Ok(Value::Float32(-2700.0))
459 );
460 let old = read(&map, expiry);
461 assert_eq!(old[0], Err(UNAVAILABLE));
462 assert_eq!(
463 old[1],
464 Ok(Value::quality(Quality {
465 old_data: true,
466 ..INVALID
467 }))
468 );
469 assert_eq!(read(&map, NOW)[0], Err(UNAVAILABLE)); }
471
472 #[test]
473 fn malformed_or_unresolvable_timestamp_never_falls_back_to_receipt() {
474 for stamp in [
475 "not-time",
476 "PT1S",
477 "-PT1S",
478 "1970-01-01T00:01:38",
479 "1970-01-01T00:01:41Z",
480 ] {
481 let mut map = mapping();
482 describe(&mut map);
483 map.observe(SOURCE, &SKI, &measured(reading(STAMP)), UTC, NOW);
484 for delta in [0, 1, 8] {
485 let delta = Duration::from_secs(delta);
486 map.observe(
487 SOURCE,
488 &SKI,
489 &measured(reading(stamp)),
490 UTC + delta,
491 NOW + delta,
492 );
493 if stamp == "1970-01-01T00:01:41Z" && !delta.is_zero() {
495 break;
496 }
497 let r = read(&map, NOW + delta);
498 assert_eq!(r[0], Err(UNAVAILABLE), "{stamp}");
499 assert_eq!(r[2], Err(UNAVAILABLE), "{stamp}");
500 }
501 }
502 let mut map = mapping();
503 describe(&mut map);
504 let mut missing = reading(STAMP);
505 missing.timestamp = None;
506 map.observe(SOURCE, &SKI, &measured(missing), UTC, NOW);
507 assert_eq!(read(&map, NOW)[0], Err(UNAVAILABLE));
508 }
509
510 #[test]
511 fn errors_out_of_range_duplicates_and_nonfinite_values_fail_closed() {
512 for (state, value) in [
513 (ReadingState::Error, Some(88.0)),
514 (ReadingState::OutOfRange, Some(88.0)),
515 (ReadingState::Normal, None),
516 (ReadingState::Normal, Some(f64::NAN)),
517 (ReadingState::Normal, Some(f64::MAX)),
518 (ReadingState::Normal, Some(f64::MIN_POSITIVE)),
519 ] {
520 let mut map = mapping();
521 describe(&mut map);
522 map.observe(SOURCE, &SKI, &measured(reading(STAMP)), UTC, NOW);
523 let mut bad = reading(STAMP);
524 bad.value = value;
525 bad.state = state;
526 map.observe(SOURCE, &SKI, &measured(bad), UTC, NOW);
527 let r = read(&map, NOW);
528 assert_eq!(r[0], Err(UNAVAILABLE));
529 assert_eq!(
530 r[1],
531 Ok(Value::quality(Quality {
532 out_of_range: state == ReadingState::OutOfRange,
533 failure: state == ReadingState::Error,
534 ..INVALID
535 }))
536 );
537 map.observe(SOURCE, &SKI, &measured(reading(STAMP)), UTC, NOW);
538 assert_eq!(read(&map, NOW)[0], Err(UNAVAILABLE));
539 }
540 let mut map = mapping();
541 describe(&mut map);
542 map.observe(
543 SOURCE,
544 &SKI,
545 &MonitoringEvent::Measured {
546 unit: unit(),
547 readings: vec![reading(STAMP), reading(STAMP)],
548 },
549 UTC,
550 NOW,
551 );
552 assert_eq!(read(&map, NOW)[0], Err(UNAVAILABLE));
553 }
554
555 #[test]
556 fn disconnect_requires_recommissioning_and_strictly_newer_sample() {
557 let mut map = mapping();
558 describe(&mut map);
559 map.observe(SOURCE, &SKI, &measured(reading(STAMP)), UTC, NOW);
560 map.disconnect();
561 let newer = measured(reading("1970-01-01T00:01:39Z"));
562 map.observe(SOURCE, &SKI, &newer, UTC, NOW);
563 assert_eq!(read(&map, NOW)[0], Err(UNAVAILABLE));
564 assert_eq!(read(&map, NOW)[2], Err(UNAVAILABLE));
565 describe(&mut map);
566 map.observe(SOURCE, &SKI, &measured(reading(STAMP)), UTC, NOW);
567 assert_eq!(read(&map, NOW)[0], Err(UNAVAILABLE));
568 map.observe(SOURCE, &SKI, &newer, UTC, NOW);
569 assert_eq!(read(&map, NOW)[0], Ok(Value::Float32(-2700.0)));
570 }
571}