Skip to main content

smgw_cls/bridge/
relay.rs

1//! Commissioned IEC controls and independent contact feedback for a simulated relay bank.
2use super::{BridgeError, admit_operate, percentage, validate_controls, validate_reference};
3use crate::fnn::relay::{ConsumptionMode, GenerationStage, RelayContacts, RelayState};
4use core::time::Duration;
5use iec61850_kit::{
6    Fc,
7    proto::{
8        data::Value,
9        mms::{ConfirmedRequest, ObjectName, VariableAccess, VariableSpecification},
10    },
11    server::{Answer, ControlEvent, DATA_ACCESS_NON_EXISTENT},
12};
13
14const TEMPORARILY_UNAVAILABLE: i64 = 2; // MMS DataAccessError
15
16/// Maps two authorized Operate events into a caller-owned command snapshot.
17/// The consumption control uses true for dimming and false for release.
18pub struct RelayBridge {
19    generation: String,
20    consumption: String,
21}
22
23impl RelayBridge {
24    /// Configure two distinct control object references from the installation's SCL model.
25    pub fn new(generation: &str, consumption: &str) -> Result<Self, BridgeError> {
26        validate_controls(generation, consumption)?;
27        Ok(Self {
28            generation: generation.into(),
29            consumption: consumption.into(),
30        })
31    }
32
33    /// Update only the addressed function after all checks pass. The caller
34    /// authenticates and authorizes the event before invoking this method.
35    pub fn apply(
36        &self,
37        desired: &mut RelayState,
38        event: &ControlEvent,
39        expires_at: Duration,
40        now: Duration,
41    ) -> Result<(), BridgeError> {
42        admit_operate(event, expires_at, now)?;
43        if event.object == self.generation {
44            desired.generation = GenerationStage::from_percent(percentage(&event.request.ctl_val)?)
45                .map_err(|_| BridgeError::InvalidValue)?;
46        } else if event.object == self.consumption {
47            let Value::Boolean(dimmed) = event.request.ctl_val else {
48                return Err(BridgeError::InvalidValue);
49            };
50            desired.consumption = if dimmed {
51                ConsumptionMode::Dimmed
52            } else {
53                ConsumptionMode::Released
54            };
55        } else {
56            return Err(BridgeError::UnmappedControl);
57        }
58        Ok(())
59    }
60}
61
62/// Four independently observed Boolean status points in S1, S2, W3, W4 order.
63pub struct RelayFeedback {
64    references: [String; 4],
65}
66
67impl RelayFeedback {
68    /// Configure unique MMS status leaf names for the four logical contact indications.
69    pub fn new(s1: &str, s2: &str, w3: &str, w4: &str) -> Result<Self, BridgeError> {
70        let names = [s1, s2, w3, w4];
71        for (i, name) in names.iter().enumerate() {
72            validate_reference(name, Fc::ST, 2)?;
73            if names[..i].contains(name) {
74                return Err(BridgeError::InvalidMapping);
75            }
76        }
77        Ok(Self {
78            references: names.map(String::from),
79        })
80    }
81
82    /// Answer direct named reads using fresh, independently sampled indications.
83    /// Supply None when feedback is unavailable or stale. Conflicting observed
84    /// generation bits are reported individually to preserve the fault indication.
85    pub fn answer_read(
86        &self,
87        request: &ConfirmedRequest<'_>,
88        observed: Option<RelayContacts>,
89    ) -> Answer {
90        let ConfirmedRequest::Read {
91            specification_with_result: false,
92            access: VariableAccess::ListOfVariable(vars),
93        } = request
94        else {
95            return Answer::DENIED;
96        };
97        let bits = observed.map(|v| [v.s1, v.s2, v.w3, v.w4]);
98        Answer::Read(
99            vars.iter()
100                .map(|var| {
101                    let VariableSpecification::Name(ObjectName::DomainSpecific { domain, item }) =
102                        var
103                    else {
104                        return Err(DATA_ACCESS_NON_EXISTENT);
105                    };
106                    let index = self
107                        .references
108                        .iter()
109                        .position(|name| name.split_once('/') == Some((*domain, *item)))
110                        .ok_or(DATA_ACCESS_NON_EXISTENT)?;
111                    bits.map(|b| Value::Boolean(b[index]))
112                        .ok_or(TEMPORARILY_UNAVAILABLE)
113                })
114                .collect(),
115        )
116    }
117}