Skip to main content

smgw_cls/fnn/
relay.rs

1//! Logical contacts for the FNN four-stage generation and consumption relay profile.
2//!
3//! Construct the initial desired state explicitly, for example from the last
4//! commissioned settings. Updating a desired state only computes a command.
5//! To interpret a separately supplied observation, use [`RelayContacts::decode`].
6//! The snapshot has no connection or timer input and retains its value until updated.
7//!
8//! Contact assignments follow [section 6 of the VDE FNN recommendation](https://www.vde.com/resource/blob/2380710/0220c532a4ecec2b29c25c52858290dc/vde-fnn-hinweis-schnittstellen-steuerungseinrichtung-data.pdf).
9
10use core::fmt;
11
12/// Allowed generation output as a percentage of reference power.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum GenerationStage {
15    /// All generation contacts inactive.
16    Percent100,
17    /// Only S1 active.
18    Percent60,
19    /// Only S2 active.
20    Percent30,
21    /// Only W3 active.
22    Percent0,
23}
24
25impl GenerationStage {
26    /// Select an exact relay stage. Other values, including nonfinite values, fail.
27    pub fn from_percent(percent: f64) -> Result<Self, RelayError> {
28        match percent {
29            100.0 => Ok(Self::Percent100),
30            60.0 => Ok(Self::Percent60),
31            30.0 => Ok(Self::Percent30),
32            0.0 => Ok(Self::Percent0),
33            _ => Err(RelayError::UnsupportedPercentage),
34        }
35    }
36
37    /// Return the allowed generation percentage.
38    pub const fn percent(self) -> u8 {
39        match self {
40            Self::Percent100 => 100,
41            Self::Percent60 => 60,
42            Self::Percent30 => 30,
43            Self::Percent0 => 0,
44        }
45    }
46}
47
48/// The W4 signal to the controlled load. The installation defines its dimmed power.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum ConsumptionMode {
51    /// Unrestricted consumption.
52    Released,
53    /// Request the commissioned reduced consumption level.
54    Dimmed,
55}
56
57/// A complete logical snapshot. Each setting is independent.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct RelayState {
60    /// Generation setting on S1, S2 and W3.
61    pub generation: GenerationStage,
62    /// Consumption setting on W4.
63    pub consumption: ConsumptionMode,
64}
65
66impl RelayState {
67    /// Initialize both settings explicitly.
68    pub const fn new(generation: GenerationStage, consumption: ConsumptionMode) -> Self {
69        Self {
70            generation,
71            consumption,
72        }
73    }
74
75    /// Encode all four desired logical contact signals in one snapshot.
76    pub const fn contacts(self) -> RelayContacts {
77        RelayContacts {
78            s1: matches!(self.generation, GenerationStage::Percent60),
79            s2: matches!(self.generation, GenerationStage::Percent30),
80            w3: matches!(self.generation, GenerationStage::Percent0),
81            w4: matches!(self.consumption, ConsumptionMode::Dimmed),
82        }
83    }
84}
85
86/// Logical activation signals. Field values use the FNN table's active polarity.
87/// A hardware adapter must interpret actual wiring and terminal polarity separately.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct RelayContacts {
90    /// S1 requests 60 percent generation.
91    pub s1: bool,
92    /// S2 requests 30 percent generation.
93    pub s2: bool,
94    /// W3 requests zero generation.
95    pub w3: bool,
96    /// W4 requests consumption dimming.
97    pub w4: bool,
98}
99
100impl RelayContacts {
101    /// Decode one observation. Simultaneous active generation signals have no
102    /// assigned stage in the four-stage profile.
103    pub const fn decode(self) -> Result<RelayState, RelayError> {
104        let generation = match (self.s1, self.s2, self.w3) {
105            (false, false, false) => GenerationStage::Percent100,
106            (true, false, false) => GenerationStage::Percent60,
107            (false, true, false) => GenerationStage::Percent30,
108            (false, false, true) => GenerationStage::Percent0,
109            _ => return Err(RelayError::ConflictingGenerationContacts),
110        };
111        Ok(RelayState::new(
112            generation,
113            if self.w4 {
114                ConsumptionMode::Dimmed
115            } else {
116                ConsumptionMode::Released
117            },
118        ))
119    }
120}
121
122/// An unsupported command or unassigned feedback pattern.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum RelayError {
125    /// The requested percentage has no exact generation stage.
126    UnsupportedPercentage,
127    /// More than one generation signal was active in the same snapshot.
128    ConflictingGenerationContacts,
129}
130
131impl fmt::Display for RelayError {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        f.write_str(match self {
134            Self::UnsupportedPercentage => "generation relay stages are 0, 30, 60 and 100 percent",
135            Self::ConflictingGenerationContacts => "multiple generation relay signals are active",
136        })
137    }
138}
139
140impl core::error::Error for RelayError {}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn each_stage_encodes_independently_of_w4() {
148        for (percent, signals) in [
149            (100, [false, false, false]),
150            (60, [true, false, false]),
151            (30, [false, true, false]),
152            (0, [false, false, true]),
153        ] {
154            for (mode, w4) in [
155                (ConsumptionMode::Released, false),
156                (ConsumptionMode::Dimmed, true),
157            ] {
158                let generation = GenerationStage::from_percent(f64::from(percent)).unwrap();
159                let state = RelayState::new(generation, mode);
160                let contacts = state.contacts();
161                assert_eq!([contacts.s1, contacts.s2, contacts.w3], signals);
162                assert_eq!(contacts.w4, w4);
163                assert_eq!(generation.percent(), percent);
164                assert_eq!(contacts.decode(), Ok(state));
165            }
166        }
167    }
168
169    #[test]
170    fn all_unassigned_generation_patterns_are_rejected_with_either_w4_state() {
171        for [s1, s2, w3] in [
172            [true, true, false],
173            [true, false, true],
174            [false, true, true],
175            [true, true, true],
176        ] {
177            for w4 in [false, true] {
178                assert_eq!(
179                    RelayContacts { s1, s2, w3, w4 }.decode(),
180                    Err(RelayError::ConflictingGenerationContacts)
181                );
182            }
183        }
184    }
185
186    #[test]
187    fn percentages_are_never_rounded_to_a_stage() {
188        for percent in [
189            f64::NAN,
190            f64::NEG_INFINITY,
191            f64::INFINITY,
192            -1.0,
193            29.999,
194            40.0,
195            100.001,
196        ] {
197            assert_eq!(
198                GenerationStage::from_percent(percent),
199                Err(RelayError::UnsupportedPercentage)
200            );
201        }
202    }
203}