Skip to main content

s2_kit/validate/
state.rs

1//! The normative table of what may be sent when.
2//!
3//! `S2C §State of communication` gives it as a table with one row per state and one
4//! column per role. This module is that table, and it is the only place the rule lives:
5//! the session engines consult it rather than carrying a second copy.
6//!
7//! ```text
8//! WebSocketConnected ──SelectControlType(ct)──▶ ControlTypeActivated(ct)
9//!         ▲                                             │
10//!         └──────── SelectControlType(NO_SELECTION) ─────┘
11//! ```
12
13use crate::message::MessageKind;
14use crate::types::common::{ControlType, EnergyManagementRole};
15
16/// Whether a message may be sent, and if not, why not.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum Allowance {
19    /// It may.
20    Yes,
21    /// Not in this state.
22    WrongState,
23    /// Not from this role.
24    WrongRole,
25}
26
27impl Allowance {
28    /// Whether the message is allowed.
29    #[must_use]
30    pub const fn is_allowed(self) -> bool {
31        matches!(self, Allowance::Yes)
32    }
33}
34
35/// The control type that is active, if any.
36///
37/// `None` and `Some(NO_SELECTION)` mean the same thing — the session is in the
38/// `WebSocketConnected` state — and so does `Some(NOT_CONTROLABLE)`, which is a legal
39/// *selection* after which only measurements and forecasts flow.
40#[must_use]
41pub fn allowed(
42    active: Option<ControlType>,
43    sender: EnergyManagementRole,
44    kind: MessageKind,
45) -> Allowance {
46    use MessageKind as K;
47
48    if let Some(expected) = kind.sender()
49        && expected != sender
50    {
51        return Allowance::WrongRole;
52    }
53
54    let active = active.filter(|c| c.is_controllable());
55
56    // The arms below are grouped by *reason*, not by outcome, so several share a body on
57    // purpose: collapsing them would lose the row of the standard's table each belongs to.
58    #[allow(clippy::match_same_arms)]
59    match kind {
60        // Never state-dependent: either side, at any point.
61        K::ReceptionStatus | K::SessionRequest => Allowance::Yes,
62
63        // The handshake belongs to the start of a session. Under S2 Connect it does not
64        // happen at all, which is a warning rather than a state error (E9 / S2-STATE-003).
65        K::Handshake | K::HandshakeResponse => {
66            if active.is_none() {
67                Allowance::Yes
68            } else {
69                Allowance::WrongState
70            }
71        }
72
73        // The RM's standing capabilities, and the CEM's ability to change its mind.
74        // `S2C`: measurements and forecasts "can always be used, even if no Control Type
75        // has been activated".
76        K::ResourceManagerDetails
77        | K::PowerMeasurement
78        | K::PowerForecast
79        | K::SelectControlType => Allowance::Yes,
80
81        // Only meaningful once something can be instructed.
82        K::InstructionStatusUpdate | K::RevokeObject => {
83            if active.is_some() {
84                Allowance::Yes
85            } else {
86                Allowance::WrongState
87            }
88        }
89
90        // Everything else belongs to exactly one control type.
91        _ => match (kind.control_type(), active) {
92            (Some(needed), Some(current)) if needed == current => Allowance::Yes,
93            _ => Allowance::WrongState,
94        },
95    }
96}
97
98/// Every message the role may send in the state, for documentation and tests.
99#[must_use]
100pub fn allowed_kinds(
101    active: Option<ControlType>,
102    sender: EnergyManagementRole,
103) -> alloc::vec::Vec<MessageKind> {
104    MessageKind::ALL
105        .iter()
106        .copied()
107        .filter(|k| allowed(active, sender, *k).is_allowed())
108        .collect()
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use EnergyManagementRole::{Cem, Rm};
115    use alloc::vec::Vec;
116
117    fn names(active: Option<ControlType>, sender: EnergyManagementRole) -> Vec<&'static str> {
118        let mut v: Vec<_> = allowed_kinds(active, sender)
119            .into_iter()
120            .map(crate::message::MessageKind::as_str)
121            .collect();
122        v.sort_unstable();
123        v
124    }
125
126    #[test]
127    fn the_websocket_connected_row_is_the_standards_own() {
128        // `S2C §State of communication`, row "WebSocket Connected". The handshake
129        // messages are added because a bare-WebSocket session exchanges them here.
130        assert_eq!(
131            names(None, Cem),
132            alloc::vec![
133                "Handshake",
134                "HandshakeResponse",
135                "ReceptionStatus",
136                "SelectControlType",
137                "SessionRequest",
138            ]
139        );
140        assert_eq!(
141            names(None, Rm),
142            alloc::vec![
143                "Handshake",
144                "PowerForecast",
145                "PowerMeasurement",
146                "ReceptionStatus",
147                "ResourceManagerDetails",
148                "SessionRequest",
149            ]
150        );
151    }
152
153    #[test]
154    fn the_frbc_row_is_the_standards_own() {
155        assert_eq!(
156            names(Some(ControlType::FillRateBasedControl), Cem),
157            alloc::vec![
158                "FRBC.Instruction",
159                "ReceptionStatus",
160                "RevokeObject",
161                "SelectControlType",
162                "SessionRequest",
163            ]
164        );
165        assert_eq!(
166            names(Some(ControlType::FillRateBasedControl), Rm),
167            alloc::vec![
168                "FRBC.ActuatorStatus",
169                "FRBC.FillLevelTargetProfile",
170                "FRBC.LeakageBehaviour",
171                "FRBC.StorageStatus",
172                "FRBC.SystemDescription",
173                "FRBC.TimerStatus",
174                "FRBC.UsageForecast",
175                "InstructionStatusUpdate",
176                "PowerForecast",
177                "PowerMeasurement",
178                "ReceptionStatus",
179                "ResourceManagerDetails",
180                "RevokeObject",
181                "SessionRequest",
182            ]
183        );
184    }
185
186    #[test]
187    fn the_pebc_row_is_the_standards_own() {
188        assert_eq!(
189            names(Some(ControlType::PowerEnvelopeBasedControl), Cem),
190            alloc::vec![
191                "PEBC.Instruction",
192                "ReceptionStatus",
193                "RevokeObject",
194                "SelectControlType",
195                "SessionRequest",
196            ]
197        );
198        assert_eq!(
199            names(Some(ControlType::PowerEnvelopeBasedControl), Rm),
200            alloc::vec![
201                "InstructionStatusUpdate",
202                "PEBC.EnergyConstraint",
203                "PEBC.PowerConstraints",
204                "PowerForecast",
205                "PowerMeasurement",
206                "ReceptionStatus",
207                "ResourceManagerDetails",
208                "RevokeObject",
209                "SessionRequest",
210            ]
211        );
212    }
213
214    #[test]
215    fn selecting_not_controlable_leaves_the_session_where_it_was() {
216        // "NOT_CONTROLABLE" is a real selection, but nothing control-type specific may
217        // follow it: docs `learn/examples/nocontrol`.
218        assert_eq!(
219            names(Some(ControlType::NotControllable), Rm),
220            names(None, Rm)
221        );
222        assert_eq!(names(Some(ControlType::NoSelection), Rm), names(None, Rm));
223    }
224
225    #[test]
226    fn a_control_type_message_in_the_wrong_control_type_is_a_state_error() {
227        assert_eq!(
228            allowed(
229                Some(ControlType::PowerEnvelopeBasedControl),
230                Cem,
231                MessageKind::FrbcInstruction
232            ),
233            Allowance::WrongState
234        );
235        assert_eq!(
236            allowed(None, Cem, MessageKind::FrbcInstruction),
237            Allowance::WrongState
238        );
239    }
240
241    #[test]
242    fn a_message_from_the_wrong_role_is_a_role_error() {
243        // An RM does not instruct, and a CEM does not describe itself as a resource.
244        assert_eq!(
245            allowed(
246                Some(ControlType::FillRateBasedControl),
247                Rm,
248                MessageKind::FrbcInstruction
249            ),
250            Allowance::WrongRole
251        );
252        assert_eq!(
253            allowed(None, Cem, MessageKind::ResourceManagerDetails),
254            Allowance::WrongRole
255        );
256        assert_eq!(
257            allowed(None, Rm, MessageKind::SelectControlType),
258            Allowance::WrongRole
259        );
260    }
261
262    #[test]
263    fn revocation_is_accepted_from_both_roles() {
264        // E6: the state table lists RevokeObject only for the RM, but RevokableObjects
265        // contains every instruction type, which only a CEM sends. Refusing the CEM's
266        // revocation would make most of that enum unreachable.
267        for role in [Cem, Rm] {
268            assert_eq!(
269                allowed(
270                    Some(ControlType::FillRateBasedControl),
271                    role,
272                    MessageKind::RevokeObject
273                ),
274                Allowance::Yes
275            );
276        }
277    }
278
279    #[test]
280    fn instruction_statuses_need_something_to_be_about() {
281        assert_eq!(
282            allowed(None, Rm, MessageKind::InstructionStatusUpdate),
283            Allowance::WrongState
284        );
285        assert_eq!(
286            allowed(
287                Some(ControlType::OperationModeBasedControl),
288                Rm,
289                MessageKind::InstructionStatusUpdate
290            ),
291            Allowance::Yes
292        );
293    }
294
295    #[test]
296    fn every_message_is_allowed_somewhere() {
297        // A message no state and no role can send would be a hole in the table.
298        for kind in MessageKind::ALL {
299            let reachable = [
300                None,
301                Some(ControlType::PowerEnvelopeBasedControl),
302                Some(ControlType::PowerProfileBasedControl),
303                Some(ControlType::OperationModeBasedControl),
304                Some(ControlType::FillRateBasedControl),
305                Some(ControlType::DemandDrivenBasedControl),
306            ]
307            .into_iter()
308            .any(|active| {
309                [Cem, Rm]
310                    .into_iter()
311                    .any(|role| allowed(active, role, *kind).is_allowed())
312            });
313            assert!(reachable, "{kind} can never be sent");
314        }
315    }
316}