Skip to main content

s2_kit/
message.rs

1//! [`Message`] — every S2 message, in one enum.
2//!
3//! S2 JSON v1.0.0 defines 36 messages. Each carries a `message_type` discriminator and,
4//! with one exception, a `message_id`; the exception is `ReceptionStatus`, which names
5//! the message it is about instead and is never itself acknowledged.
6//!
7//! [`MessageKind`] is the same set without the payloads: a fieldless `Copy` enum that is
8//! the key of the session state table, the unit of the allowed-message rules, and what a
9//! log line should carry.
10
11use alloc::boxed::Box;
12use serde::{Deserialize, Serialize};
13
14use crate::types::common::{
15    ControlType, EnergyManagementRole, Handshake, HandshakeResponse, InstructionStatusUpdate,
16    PowerForecast, PowerMeasurement, ReceptionStatus, ResourceManagerDetails, RevokeObject,
17    SelectControlType, SessionRequest,
18};
19use crate::types::{Id, ddbc, frbc, ombc, pebc, ppbc};
20
21/// Any S2 message.
22///
23/// The enum is internally tagged by `message_type`, exactly as the wire is, so
24/// serialising a `Message` produces a complete S2 message and deserialising one accepts
25/// any of the 36.
26///
27/// ```
28/// use s2_kit::{Message, types::frbc};
29///
30/// let json = r#"{"message_type":"FRBC.StorageStatus",
31///                "message_id":"aaaaaaaa-0000-0000-0000-000000000001",
32///                "present_fill_level":52.0}"#;
33/// let message: Message = serde_json::from_str(json)?;
34/// match &message {
35///     Message::FrbcStorageStatus(s) => assert_eq!(s.present_fill_level, 52.0),
36///     _ => unreachable!(),
37/// }
38/// # Ok::<(), serde_json::Error>(())
39/// ```
40///
41/// Large payloads are boxed so that the enum stays small enough to pass by value and to
42/// keep a queue of pending messages compact; [`From`] is implemented for every payload
43/// type and does the boxing for you.
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45#[serde(tag = "message_type")]
46#[non_exhaustive]
47pub enum Message {
48    // --- common -----------------------------------------------------------
49    /// A node announcing its role and the versions it speaks.
50    #[serde(rename = "Handshake")]
51    Handshake(Handshake),
52    /// The CEM's choice of version.
53    #[serde(rename = "HandshakeResponse")]
54    HandshakeResponse(HandshakeResponse),
55    /// Everything static about a resource.
56    #[serde(rename = "ResourceManagerDetails")]
57    ResourceManagerDetails(Box<ResourceManagerDetails>),
58    /// The CEM activating a control type.
59    #[serde(rename = "SelectControlType")]
60    SelectControlType(SelectControlType),
61    /// Either side asking for the session to end or restart.
62    #[serde(rename = "SessionRequest")]
63    SessionRequest(SessionRequest),
64    /// The answer every other message gets.
65    #[serde(rename = "ReceptionStatus")]
66    ReceptionStatus(ReceptionStatus),
67    /// What became of an instruction.
68    #[serde(rename = "InstructionStatusUpdate")]
69    InstructionStatusUpdate(InstructionStatusUpdate),
70    /// A measured power.
71    #[serde(rename = "PowerMeasurement")]
72    PowerMeasurement(PowerMeasurement),
73    /// An expected power.
74    #[serde(rename = "PowerForecast")]
75    PowerForecast(Box<PowerForecast>),
76    /// Withdrawing an object published earlier.
77    #[serde(rename = "RevokeObject")]
78    RevokeObject(RevokeObject),
79
80    // --- PEBC -------------------------------------------------------------
81    /// The bounds within which the CEM may set an envelope.
82    #[serde(rename = "PEBC.PowerConstraints")]
83    PebcPowerConstraints(Box<pebc::PowerConstraints>),
84    /// How much energy must still flow over a period.
85    #[serde(rename = "PEBC.EnergyConstraint")]
86    PebcEnergyConstraint(Box<pebc::EnergyConstraint>),
87    /// The envelope the CEM wants followed.
88    #[serde(rename = "PEBC.Instruction")]
89    PebcInstruction(Box<pebc::Instruction>),
90
91    // --- PPBC -------------------------------------------------------------
92    /// The task, its window, and every way of performing it.
93    #[serde(rename = "PPBC.PowerProfileDefinition")]
94    PpbcPowerProfileDefinition(Box<ppbc::PowerProfileDefinition>),
95    /// How every container of a profile is getting on.
96    #[serde(rename = "PPBC.PowerProfileStatus")]
97    PpbcPowerProfileStatus(Box<ppbc::PowerProfileStatus>),
98    /// The CEM choosing a sequence and a start time.
99    #[serde(rename = "PPBC.ScheduleInstruction")]
100    PpbcScheduleInstruction(Box<ppbc::ScheduleInstruction>),
101    /// The CEM pausing a running sequence.
102    #[serde(rename = "PPBC.StartInterruptionInstruction")]
103    PpbcStartInterruptionInstruction(Box<ppbc::StartInterruptionInstruction>),
104    /// The CEM resuming an interrupted sequence.
105    #[serde(rename = "PPBC.EndInterruptionInstruction")]
106    PpbcEndInterruptionInstruction(Box<ppbc::EndInterruptionInstruction>),
107
108    // --- OMBC -------------------------------------------------------------
109    /// The state machine.
110    #[serde(rename = "OMBC.SystemDescription")]
111    OmbcSystemDescription(Box<ombc::SystemDescription>),
112    /// Which mode the device is in.
113    #[serde(rename = "OMBC.Status")]
114    OmbcStatus(Box<ombc::Status>),
115    /// When one of its timers finishes.
116    #[serde(rename = "OMBC.TimerStatus")]
117    OmbcTimerStatus(ombc::TimerStatus),
118    /// The CEM asking for a mode change.
119    #[serde(rename = "OMBC.Instruction")]
120    OmbcInstruction(Box<ombc::Instruction>),
121
122    // --- FRBC -------------------------------------------------------------
123    /// The storage and every actuator that can move it.
124    #[serde(rename = "FRBC.SystemDescription")]
125    FrbcSystemDescription(Box<frbc::SystemDescription>),
126    /// How full the store is.
127    #[serde(rename = "FRBC.StorageStatus")]
128    FrbcStorageStatus(frbc::StorageStatus),
129    /// Which mode an actuator is in.
130    #[serde(rename = "FRBC.ActuatorStatus")]
131    FrbcActuatorStatus(Box<frbc::ActuatorStatus>),
132    /// When one of an actuator's timers finishes.
133    #[serde(rename = "FRBC.TimerStatus")]
134    FrbcTimerStatus(Box<frbc::TimerStatus>),
135    /// The store's standing losses.
136    #[serde(rename = "FRBC.LeakageBehaviour")]
137    FrbcLeakageBehaviour(Box<frbc::LeakageBehaviour>),
138    /// What the user is expected to take out of the store.
139    #[serde(rename = "FRBC.UsageForecast")]
140    FrbcUsageForecast(Box<frbc::UsageForecast>),
141    /// Fill levels the CEM should aim for.
142    #[serde(rename = "FRBC.FillLevelTargetProfile")]
143    FrbcFillLevelTargetProfile(Box<frbc::FillLevelTargetProfile>),
144    /// The CEM asking an actuator to change mode.
145    #[serde(rename = "FRBC.Instruction")]
146    FrbcInstruction(Box<frbc::Instruction>),
147
148    // --- DDBC -------------------------------------------------------------
149    /// Every actuator that can meet the demand.
150    #[serde(rename = "DDBC.SystemDescription")]
151    DdbcSystemDescription(Box<ddbc::SystemDescription>),
152    /// Which mode an actuator is in.
153    #[serde(rename = "DDBC.ActuatorStatus")]
154    DdbcActuatorStatus(Box<ddbc::ActuatorStatus>),
155    /// When one of an actuator's timers finishes.
156    #[serde(rename = "DDBC.TimerStatus")]
157    DdbcTimerStatus(Box<ddbc::TimerStatus>),
158    /// What the system expects to be asked for.
159    #[serde(rename = "DDBC.AverageDemandRateForecast")]
160    DdbcAverageDemandRateForecast(Box<ddbc::AverageDemandRateForecast>),
161    /// The demand that must be satisfied right now. New in S2 JSON v1.0.0.
162    #[serde(rename = "DDBC.PresentDemandStatus")]
163    DdbcPresentDemandStatus(ddbc::PresentDemandStatus),
164    /// The CEM asking an actuator to change mode.
165    #[serde(rename = "DDBC.Instruction")]
166    DdbcInstruction(Box<ddbc::Instruction>),
167}
168
169/// Every S2 message type, without the payload.
170///
171/// `MessageKind` is `Copy` and fieldless, which is what makes the session's
172/// allowed-message table a lookup rather than a match over 36 arms.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
174#[non_exhaustive]
175#[allow(missing_docs)] // one variant per Message variant; see there
176pub enum MessageKind {
177    Handshake,
178    HandshakeResponse,
179    ResourceManagerDetails,
180    SelectControlType,
181    SessionRequest,
182    ReceptionStatus,
183    InstructionStatusUpdate,
184    PowerMeasurement,
185    PowerForecast,
186    RevokeObject,
187    PebcPowerConstraints,
188    PebcEnergyConstraint,
189    PebcInstruction,
190    PpbcPowerProfileDefinition,
191    PpbcPowerProfileStatus,
192    PpbcScheduleInstruction,
193    PpbcStartInterruptionInstruction,
194    PpbcEndInterruptionInstruction,
195    OmbcSystemDescription,
196    OmbcStatus,
197    OmbcTimerStatus,
198    OmbcInstruction,
199    FrbcSystemDescription,
200    FrbcStorageStatus,
201    FrbcActuatorStatus,
202    FrbcTimerStatus,
203    FrbcLeakageBehaviour,
204    FrbcUsageForecast,
205    FrbcFillLevelTargetProfile,
206    FrbcInstruction,
207    DdbcSystemDescription,
208    DdbcActuatorStatus,
209    DdbcTimerStatus,
210    DdbcAverageDemandRateForecast,
211    DdbcPresentDemandStatus,
212    DdbcInstruction,
213}
214
215/// Builds the `MessageKind` tables once, so the wire names, the parser and the
216/// `Message`-to-kind mapping cannot drift apart: each is generated from the same list.
217macro_rules! message_kinds {
218    ($(($kind:ident, $wire:literal, $variant:ident)),* $(,)?) => {
219        impl MessageKind {
220            /// Every message type this crate knows, in declaration order.
221            pub const ALL: &'static [MessageKind] = &[$(MessageKind::$kind),*];
222
223            /// The `message_type` string this kind has on the wire.
224            #[must_use]
225            pub const fn as_str(self) -> &'static str {
226                match self { $(MessageKind::$kind => $wire),* }
227            }
228
229            /// The kind a `message_type` string names, if this crate knows it.
230            #[must_use]
231            pub fn from_wire(s: &str) -> Option<Self> {
232                match s { $($wire => Some(MessageKind::$kind),)* _ => None }
233            }
234        }
235
236        impl Message {
237            /// Which message this is.
238            #[must_use]
239            pub const fn kind(&self) -> MessageKind {
240                match self { $(Message::$variant(..) => MessageKind::$kind),* }
241            }
242        }
243    };
244}
245
246message_kinds![
247    (Handshake, "Handshake", Handshake),
248    (HandshakeResponse, "HandshakeResponse", HandshakeResponse),
249    (
250        ResourceManagerDetails,
251        "ResourceManagerDetails",
252        ResourceManagerDetails
253    ),
254    (SelectControlType, "SelectControlType", SelectControlType),
255    (SessionRequest, "SessionRequest", SessionRequest),
256    (ReceptionStatus, "ReceptionStatus", ReceptionStatus),
257    (
258        InstructionStatusUpdate,
259        "InstructionStatusUpdate",
260        InstructionStatusUpdate
261    ),
262    (PowerMeasurement, "PowerMeasurement", PowerMeasurement),
263    (PowerForecast, "PowerForecast", PowerForecast),
264    (RevokeObject, "RevokeObject", RevokeObject),
265    (
266        PebcPowerConstraints,
267        "PEBC.PowerConstraints",
268        PebcPowerConstraints
269    ),
270    (
271        PebcEnergyConstraint,
272        "PEBC.EnergyConstraint",
273        PebcEnergyConstraint
274    ),
275    (PebcInstruction, "PEBC.Instruction", PebcInstruction),
276    (
277        PpbcPowerProfileDefinition,
278        "PPBC.PowerProfileDefinition",
279        PpbcPowerProfileDefinition
280    ),
281    (
282        PpbcPowerProfileStatus,
283        "PPBC.PowerProfileStatus",
284        PpbcPowerProfileStatus
285    ),
286    (
287        PpbcScheduleInstruction,
288        "PPBC.ScheduleInstruction",
289        PpbcScheduleInstruction
290    ),
291    (
292        PpbcStartInterruptionInstruction,
293        "PPBC.StartInterruptionInstruction",
294        PpbcStartInterruptionInstruction
295    ),
296    (
297        PpbcEndInterruptionInstruction,
298        "PPBC.EndInterruptionInstruction",
299        PpbcEndInterruptionInstruction
300    ),
301    (
302        OmbcSystemDescription,
303        "OMBC.SystemDescription",
304        OmbcSystemDescription
305    ),
306    (OmbcStatus, "OMBC.Status", OmbcStatus),
307    (OmbcTimerStatus, "OMBC.TimerStatus", OmbcTimerStatus),
308    (OmbcInstruction, "OMBC.Instruction", OmbcInstruction),
309    (
310        FrbcSystemDescription,
311        "FRBC.SystemDescription",
312        FrbcSystemDescription
313    ),
314    (FrbcStorageStatus, "FRBC.StorageStatus", FrbcStorageStatus),
315    (
316        FrbcActuatorStatus,
317        "FRBC.ActuatorStatus",
318        FrbcActuatorStatus
319    ),
320    (FrbcTimerStatus, "FRBC.TimerStatus", FrbcTimerStatus),
321    (
322        FrbcLeakageBehaviour,
323        "FRBC.LeakageBehaviour",
324        FrbcLeakageBehaviour
325    ),
326    (FrbcUsageForecast, "FRBC.UsageForecast", FrbcUsageForecast),
327    (
328        FrbcFillLevelTargetProfile,
329        "FRBC.FillLevelTargetProfile",
330        FrbcFillLevelTargetProfile
331    ),
332    (FrbcInstruction, "FRBC.Instruction", FrbcInstruction),
333    (
334        DdbcSystemDescription,
335        "DDBC.SystemDescription",
336        DdbcSystemDescription
337    ),
338    (
339        DdbcActuatorStatus,
340        "DDBC.ActuatorStatus",
341        DdbcActuatorStatus
342    ),
343    (DdbcTimerStatus, "DDBC.TimerStatus", DdbcTimerStatus),
344    (
345        DdbcAverageDemandRateForecast,
346        "DDBC.AverageDemandRateForecast",
347        DdbcAverageDemandRateForecast
348    ),
349    (
350        DdbcPresentDemandStatus,
351        "DDBC.PresentDemandStatus",
352        DdbcPresentDemandStatus
353    ),
354    (DdbcInstruction, "DDBC.Instruction", DdbcInstruction),
355];
356
357impl core::fmt::Display for MessageKind {
358    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
359        f.write_str(self.as_str())
360    }
361}
362
363impl MessageKind {
364    /// The control type this message belongs to, if any.
365    #[must_use]
366    pub const fn control_type(self) -> Option<ControlType> {
367        use MessageKind as K;
368        match self {
369            K::PebcPowerConstraints | K::PebcEnergyConstraint | K::PebcInstruction => {
370                Some(ControlType::PowerEnvelopeBasedControl)
371            }
372            K::PpbcPowerProfileDefinition
373            | K::PpbcPowerProfileStatus
374            | K::PpbcScheduleInstruction
375            | K::PpbcStartInterruptionInstruction
376            | K::PpbcEndInterruptionInstruction => Some(ControlType::PowerProfileBasedControl),
377            K::OmbcSystemDescription | K::OmbcStatus | K::OmbcTimerStatus | K::OmbcInstruction => {
378                Some(ControlType::OperationModeBasedControl)
379            }
380            K::FrbcSystemDescription
381            | K::FrbcStorageStatus
382            | K::FrbcActuatorStatus
383            | K::FrbcTimerStatus
384            | K::FrbcLeakageBehaviour
385            | K::FrbcUsageForecast
386            | K::FrbcFillLevelTargetProfile
387            | K::FrbcInstruction => Some(ControlType::FillRateBasedControl),
388            K::DdbcSystemDescription
389            | K::DdbcActuatorStatus
390            | K::DdbcTimerStatus
391            | K::DdbcAverageDemandRateForecast
392            | K::DdbcPresentDemandStatus
393            | K::DdbcInstruction => Some(ControlType::DemandDrivenBasedControl),
394            _ => None,
395        }
396    }
397
398    /// Whether this message asks a Resource Manager to do something, and therefore earns
399    /// an `InstructionStatusUpdate` as well as a `ReceptionStatus`.
400    #[must_use]
401    pub const fn is_instruction(self) -> bool {
402        use MessageKind as K;
403        matches!(
404            self,
405            K::PebcInstruction
406                | K::PpbcScheduleInstruction
407                | K::PpbcStartInterruptionInstruction
408                | K::PpbcEndInterruptionInstruction
409                | K::OmbcInstruction
410                | K::FrbcInstruction
411                | K::DdbcInstruction
412        )
413    }
414
415    /// Which role sends this message.
416    ///
417    /// `SessionRequest` and `ReceptionStatus` are sent by both, and so answer `None`.
418    #[must_use]
419    pub const fn sender(self) -> Option<EnergyManagementRole> {
420        use EnergyManagementRole as Role;
421        use MessageKind as K;
422        match self {
423            K::SelectControlType | K::HandshakeResponse => Some(Role::Cem),
424            _ if self.is_instruction() => Some(Role::Cem),
425            // RevokeObject is listed only in the RM column of the state table, but
426            // `RevokableObjects` contains every instruction type, which only a CEM
427            // sends (erratum E6). Both roles may send it; the
428            // object-type mismatch is a warning rule instead.
429            K::SessionRequest | K::ReceptionStatus | K::Handshake | K::RevokeObject => None,
430            _ => Some(Role::Rm),
431        }
432    }
433
434    /// Whether the message exists in a given wire profile.
435    ///
436    /// Only `DDBC.PresentDemandStatus` answers `false` for anything: it is new in
437    /// v1.0.0.
438    #[must_use]
439    pub const fn exists_in(self, profile: crate::types::WireProfile) -> bool {
440        !(matches!(self, MessageKind::DdbcPresentDemandStatus)
441            && matches!(profile, crate::types::WireProfile::V0_0_2Beta))
442    }
443}
444
445impl Message {
446    /// This message's own identifier.
447    ///
448    /// `None` for `ReceptionStatus`, which has none — it names the message it is about
449    /// instead, via [`subject_message_id`](Self::subject_message_id).
450    #[must_use]
451    pub fn id(&self) -> Option<Id> {
452        use Message as M;
453        Some(match self {
454            M::Handshake(m) => m.message_id,
455            M::HandshakeResponse(m) => m.message_id,
456            M::ResourceManagerDetails(m) => m.message_id,
457            M::SelectControlType(m) => m.message_id,
458            M::SessionRequest(m) => m.message_id,
459            M::ReceptionStatus(_) => return None,
460            M::InstructionStatusUpdate(m) => m.message_id,
461            M::PowerMeasurement(m) => m.message_id,
462            M::PowerForecast(m) => m.message_id,
463            M::RevokeObject(m) => m.message_id,
464            M::PebcPowerConstraints(m) => m.message_id,
465            M::PebcEnergyConstraint(m) => m.message_id,
466            M::PebcInstruction(m) => m.message_id,
467            M::PpbcPowerProfileDefinition(m) => m.message_id,
468            M::PpbcPowerProfileStatus(m) => m.message_id,
469            M::PpbcScheduleInstruction(m) => m.message_id,
470            M::PpbcStartInterruptionInstruction(m) => m.message_id,
471            M::PpbcEndInterruptionInstruction(m) => m.message_id,
472            M::OmbcSystemDescription(m) => m.message_id,
473            M::OmbcStatus(m) => m.message_id,
474            M::OmbcTimerStatus(m) => m.message_id,
475            M::OmbcInstruction(m) => m.message_id,
476            M::FrbcSystemDescription(m) => m.message_id,
477            M::FrbcStorageStatus(m) => m.message_id,
478            M::FrbcActuatorStatus(m) => m.message_id,
479            M::FrbcTimerStatus(m) => m.message_id,
480            M::FrbcLeakageBehaviour(m) => m.message_id,
481            M::FrbcUsageForecast(m) => m.message_id,
482            M::FrbcFillLevelTargetProfile(m) => m.message_id,
483            M::FrbcInstruction(m) => m.message_id,
484            M::DdbcSystemDescription(m) => m.message_id,
485            M::DdbcActuatorStatus(m) => m.message_id,
486            M::DdbcTimerStatus(m) => m.message_id,
487            M::DdbcAverageDemandRateForecast(m) => m.message_id,
488            M::DdbcPresentDemandStatus(m) => m.message_id,
489            M::DdbcInstruction(m) => m.message_id,
490        })
491    }
492
493    /// The message a `ReceptionStatus` is about, if this is one.
494    #[must_use]
495    pub fn subject_message_id(&self) -> Option<Id> {
496        match self {
497            Message::ReceptionStatus(s) => Some(s.subject_message_id),
498            _ => None,
499        }
500    }
501
502    /// The instruction's own identifier, if this message is an instruction.
503    ///
504    /// This is **not** the `message_id`: an `InstructionStatusUpdate` names this one.
505    #[must_use]
506    pub fn instruction_id(&self) -> Option<Id> {
507        use Message as M;
508        Some(match self {
509            M::PebcInstruction(m) => m.id,
510            M::PpbcScheduleInstruction(m) => m.id,
511            M::PpbcStartInterruptionInstruction(m) => m.id,
512            M::PpbcEndInterruptionInstruction(m) => m.id,
513            M::OmbcInstruction(m) => m.id,
514            M::FrbcInstruction(m) => m.id,
515            M::DdbcInstruction(m) => m.id,
516            _ => return None,
517        })
518    }
519
520    /// The identifier of the object this message publishes, if it is one a
521    /// [`RevokeObject`] could later withdraw.
522    #[must_use]
523    pub fn revokable_id(&self) -> Option<(crate::types::common::RevokableObjects, Id)> {
524        use crate::types::common::RevokableObjects as R;
525        use Message as M;
526        Some(match self {
527            M::PebcPowerConstraints(m) => (R::PebcPowerConstraints, m.id),
528            M::PebcEnergyConstraint(m) => (R::PebcEnergyConstraint, m.id),
529            M::PebcInstruction(m) => (R::PebcInstruction, m.id),
530            M::PpbcPowerProfileDefinition(m) => (R::PpbcPowerProfileDefinition, m.id),
531            M::PpbcScheduleInstruction(m) => (R::PpbcScheduleInstruction, m.id),
532            M::PpbcStartInterruptionInstruction(m) => (R::PpbcStartInterruptionInstruction, m.id),
533            M::PpbcEndInterruptionInstruction(m) => (R::PpbcEndInterruptionInstruction, m.id),
534            M::OmbcInstruction(m) => (R::OmbcInstruction, m.id),
535            M::FrbcInstruction(m) => (R::FrbcInstruction, m.id),
536            M::DdbcInstruction(m) => (R::DdbcInstruction, m.id),
537            // A system description is revokable but has no `id` of its own; the standard
538            // has the `message_id` stand in, since that is the only handle a CEM has.
539            M::OmbcSystemDescription(m) => (R::OmbcSystemDescription, m.message_id),
540            M::FrbcSystemDescription(m) => (R::FrbcSystemDescription, m.message_id),
541            M::DdbcSystemDescription(m) => (R::DdbcSystemDescription, m.message_id),
542            _ => return None,
543        })
544    }
545
546    /// The control type this message belongs to, if any.
547    #[must_use]
548    pub const fn control_type(&self) -> Option<ControlType> {
549        self.kind().control_type()
550    }
551
552    /// Whether this message is an instruction.
553    #[must_use]
554    pub const fn is_instruction(&self) -> bool {
555        self.kind().is_instruction()
556    }
557}
558
559/// Generates the `From<Payload> for Message` conversions, boxing where the variant does.
560macro_rules! from_payload {
561    ($($ty:ty => $variant:ident $(, $boxed:tt)?);* $(;)?) => {
562        $(impl From<$ty> for Message {
563            fn from(value: $ty) -> Self {
564                Message::$variant(from_payload!(@wrap value $(, $boxed)?))
565            }
566        })*
567    };
568    (@wrap $v:ident) => { $v };
569    (@wrap $v:ident, box) => { Box::new($v) };
570}
571
572from_payload![
573    Handshake => Handshake;
574    HandshakeResponse => HandshakeResponse;
575    ResourceManagerDetails => ResourceManagerDetails, box;
576    SelectControlType => SelectControlType;
577    SessionRequest => SessionRequest;
578    ReceptionStatus => ReceptionStatus;
579    InstructionStatusUpdate => InstructionStatusUpdate;
580    PowerMeasurement => PowerMeasurement;
581    PowerForecast => PowerForecast, box;
582    RevokeObject => RevokeObject;
583    pebc::PowerConstraints => PebcPowerConstraints, box;
584    pebc::EnergyConstraint => PebcEnergyConstraint, box;
585    pebc::Instruction => PebcInstruction, box;
586    ppbc::PowerProfileDefinition => PpbcPowerProfileDefinition, box;
587    ppbc::PowerProfileStatus => PpbcPowerProfileStatus, box;
588    ppbc::ScheduleInstruction => PpbcScheduleInstruction, box;
589    ppbc::StartInterruptionInstruction => PpbcStartInterruptionInstruction, box;
590    ppbc::EndInterruptionInstruction => PpbcEndInterruptionInstruction, box;
591    ombc::SystemDescription => OmbcSystemDescription, box;
592    ombc::Status => OmbcStatus, box;
593    ombc::TimerStatus => OmbcTimerStatus;
594    ombc::Instruction => OmbcInstruction, box;
595    frbc::SystemDescription => FrbcSystemDescription, box;
596    frbc::StorageStatus => FrbcStorageStatus;
597    frbc::ActuatorStatus => FrbcActuatorStatus, box;
598    frbc::TimerStatus => FrbcTimerStatus, box;
599    frbc::LeakageBehaviour => FrbcLeakageBehaviour, box;
600    frbc::UsageForecast => FrbcUsageForecast, box;
601    frbc::FillLevelTargetProfile => FrbcFillLevelTargetProfile, box;
602    frbc::Instruction => FrbcInstruction, box;
603    ddbc::SystemDescription => DdbcSystemDescription, box;
604    ddbc::ActuatorStatus => DdbcActuatorStatus, box;
605    ddbc::TimerStatus => DdbcTimerStatus, box;
606    ddbc::AverageDemandRateForecast => DdbcAverageDemandRateForecast, box;
607    ddbc::PresentDemandStatus => DdbcPresentDemandStatus;
608    ddbc::Instruction => DdbcInstruction, box;
609];
610
611#[cfg(test)]
612mod tests {
613    use super::*;
614    use crate::types::Timestamp;
615    use crate::types::common::{ReceptionStatusValues, SessionRequestType};
616
617    #[test]
618    fn every_message_type_in_s2_json_v1_is_present() {
619        assert_eq!(MessageKind::ALL.len(), 36, "S2 JSON v1.0.0 has 36 messages");
620        // And no two share a wire name.
621        let mut names: alloc::vec::Vec<_> = MessageKind::ALL.iter().map(|k| k.as_str()).collect();
622        names.sort_unstable();
623        let before = names.len();
624        names.dedup();
625        assert_eq!(names.len(), before, "duplicate message_type");
626    }
627
628    #[test]
629    fn wire_names_round_trip_through_the_parser() {
630        for kind in MessageKind::ALL {
631            assert_eq!(MessageKind::from_wire(kind.as_str()), Some(*kind));
632        }
633        assert_eq!(MessageKind::from_wire("Nope"), None);
634        // Case matters: the wire names are exact.
635        assert_eq!(MessageKind::from_wire("frbc.instruction"), None);
636    }
637
638    #[test]
639    fn control_types_are_read_off_the_message_type_prefix() {
640        for kind in MessageKind::ALL {
641            let expected = kind
642                .as_str()
643                .split_once('.')
644                .and_then(|(prefix, _)| match prefix {
645                    "PEBC" => Some(ControlType::PowerEnvelopeBasedControl),
646                    "PPBC" => Some(ControlType::PowerProfileBasedControl),
647                    "OMBC" => Some(ControlType::OperationModeBasedControl),
648                    "FRBC" => Some(ControlType::FillRateBasedControl),
649                    "DDBC" => Some(ControlType::DemandDrivenBasedControl),
650                    _ => None,
651                });
652            assert_eq!(kind.control_type(), expected, "{kind}");
653        }
654    }
655
656    #[test]
657    fn instructions_are_exactly_the_seven() {
658        let instructions: alloc::vec::Vec<_> = MessageKind::ALL
659            .iter()
660            .filter(|k| k.is_instruction())
661            .map(|k| k.as_str())
662            .collect();
663        assert_eq!(
664            instructions,
665            alloc::vec![
666                "PEBC.Instruction",
667                "PPBC.ScheduleInstruction",
668                "PPBC.StartInterruptionInstruction",
669                "PPBC.EndInterruptionInstruction",
670                "OMBC.Instruction",
671                "FRBC.Instruction",
672                "DDBC.Instruction",
673            ]
674        );
675    }
676
677    #[test]
678    fn reception_status_is_the_one_message_with_no_id_of_its_own() {
679        let rs = Message::from(ReceptionStatus::ok(Id::new_const("m1")));
680        assert_eq!(rs.id(), None);
681        assert_eq!(rs.subject_message_id(), Some(Id::new_const("m1")));
682
683        for kind in MessageKind::ALL {
684            if *kind != MessageKind::ReceptionStatus {
685                // Every other message carries a message_id; the property is asserted by
686                // the round-trip tests, this documents the exception.
687                assert!(kind.as_str() != "ReceptionStatus");
688            }
689        }
690    }
691
692    #[test]
693    fn the_tag_is_first_on_the_wire_and_matches_the_kind() {
694        let m = Message::from(SessionRequest {
695            message_id: Id::new_const("m1"),
696            request: SessionRequestType::Terminate,
697            diagnostic_label: None,
698        });
699        let json = serde_json::to_string(&m).unwrap();
700        assert!(
701            json.starts_with(r#"{"message_type":"SessionRequest","message_id":"m1""#),
702            "{json}"
703        );
704        let back: Message = serde_json::from_str(&json).unwrap();
705        assert_eq!(back, m);
706        assert_eq!(back.kind(), MessageKind::SessionRequest);
707    }
708
709    #[test]
710    fn unknown_fields_are_refused_through_the_enum_too() {
711        // The tag itself must not count as an unknown field, and anything else must.
712        let ok =
713            r#"{"message_type":"FRBC.StorageStatus","message_id":"m1","present_fill_level":1.0}"#;
714        assert!(serde_json::from_str::<Message>(ok).is_ok());
715        let bad = r#"{"message_type":"FRBC.StorageStatus","message_id":"m1","present_fill_level":1.0,"extra":1}"#;
716        assert!(serde_json::from_str::<Message>(bad).is_err());
717    }
718
719    #[test]
720    fn an_unknown_message_type_is_an_error_not_a_silent_variant() {
721        let json = r#"{"message_type":"FRBC.SomethingNew","message_id":"m1"}"#;
722        assert!(serde_json::from_str::<Message>(json).is_err());
723    }
724
725    #[test]
726    fn revokable_objects_line_up_with_the_messages_that_publish_them() {
727        let instruction = frbc::Instruction {
728            message_id: Id::new_const("m1"),
729            id: Id::new_const("instr0"),
730            actuator_id: Id::new_const("a1"),
731            operation_mode: Id::new_const("om1"),
732            operation_mode_factor: 1.0,
733            execution_time: Timestamp::UNIX_EPOCH,
734            abnormal_condition: false,
735        };
736        let m = Message::from(instruction);
737        assert_eq!(m.instruction_id(), Some(Id::new_const("instr0")));
738        let (object_type, id) = m.revokable_id().unwrap();
739        assert_eq!(
740            object_type,
741            crate::types::common::RevokableObjects::FrbcInstruction
742        );
743        assert_eq!(id, Id::new_const("instr0"));
744        assert_eq!(
745            object_type.control_type(),
746            ControlType::FillRateBasedControl
747        );
748    }
749
750    #[test]
751    fn the_new_message_exists_only_in_the_newer_profile() {
752        use crate::types::WireProfile;
753        assert!(MessageKind::DdbcPresentDemandStatus.exists_in(WireProfile::V1_0_0));
754        assert!(!MessageKind::DdbcPresentDemandStatus.exists_in(WireProfile::V0_0_2Beta));
755        // Everything else exists in both.
756        for kind in MessageKind::ALL {
757            if *kind != MessageKind::DdbcPresentDemandStatus {
758                assert!(kind.exists_in(WireProfile::V0_0_2Beta), "{kind}");
759                assert!(kind.exists_in(WireProfile::V1_0_0), "{kind}");
760            }
761        }
762    }
763
764    #[test]
765    fn the_enum_stays_small_enough_to_move_cheaply() {
766        // Where the number comes from: an `Id` is 65 bytes inline, because it is `Copy`
767        // and allocation-free (D11), and the widest *unboxed* variant is
768        // `OMBC.TimerStatus` — two identifiers and a timestamp, 146 bytes, padded to
769        // 152. Payloads that own heap data, and the instruction and actuator-status
770        // messages that carry three or four identifiers, are boxed; without that the
771        // enum would be 288 bytes, the size of `FRBC.Instruction`.
772        let size = core::mem::size_of::<Message>();
773        assert!(size <= 160, "Message grew to {size} bytes");
774        // Boxing keeps the spread well inside clippy's large-enum-variant threshold.
775        assert_eq!(core::mem::size_of::<Box<frbc::Instruction>>(), 8);
776    }
777
778    #[test]
779    fn reception_status_values_are_not_confused_with_statuses() {
780        let s = ReceptionStatus::error(
781            Id::new_const("m1"),
782            ReceptionStatusValues::InvalidContent,
783            "S2-STATE-001: nope",
784        );
785        let json = serde_json::to_string(&Message::from(s)).unwrap();
786        assert!(json.contains(r#""status":"INVALID_CONTENT""#));
787        assert!(json.contains("S2-STATE-001"));
788    }
789}