Skip to main content

ocpp_kit/
message.rs

1//! The traits that tie a payload type to its action, direction and message kind.
2
3use core::fmt;
4
5use serde::Serialize;
6use serde::de::DeserializeOwned;
7
8use crate::validate::{Validate, ValidationPath, Violations};
9
10/// Prevents downstream crates from implementing the payload traits, so new actions and new
11/// versions are not breaking changes for them.
12pub trait Sealed {}
13
14/// Whether a message is a confirmed `CALL` or an unconfirmed `SEND`.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16pub enum MessageKind {
17    /// A `CALL` (message type 2), answered with `CALLRESULT`, `CALLERROR` or —
18    /// in 2.1 — `CALLRESULTERROR`.
19    Call,
20    /// A `SEND` (message type 6, OCPP 2.1 only): never answered, and exempt from the
21    /// one-outstanding-`CALL` rule (Part 4 §4.2.4, FR.07).
22    Send,
23}
24
25/// Which peer originates an action.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27pub enum Origin {
28    /// Charging Station → CSMS.
29    ChargingStation,
30    /// CSMS → Charging Station.
31    Csms,
32    /// Either peer may originate it. Only `DataTransfer`.
33    Both,
34}
35
36impl Origin {
37    /// Whether a Charging Station may send this action.
38    #[must_use]
39    pub const fn from_charging_station(self) -> bool {
40        matches!(self, Origin::ChargingStation | Origin::Both)
41    }
42
43    /// Whether a CSMS may send this action.
44    #[must_use]
45    pub const fn from_csms(self) -> bool {
46        matches!(self, Origin::Csms | Origin::Both)
47    }
48}
49
50/// The behaviour every generated per-version `Action` enum provides.
51pub trait ActionName:
52    Copy + Eq + Ord + core::hash::Hash + fmt::Debug + fmt::Display + Sized + 'static
53{
54    /// Every action this version defines, in specification order.
55    fn all() -> &'static [Self];
56
57    /// The action name as it appears on the wire.
58    fn as_str(&self) -> &'static str;
59
60    /// Parses a wire action name; `None` if this version does not define it.
61    fn from_wire(name: &str) -> Option<Self>;
62
63    /// Whether the action is a `CALL` or a `SEND`.
64    fn kind(&self) -> MessageKind;
65
66    /// Which peer originates the action.
67    fn origin(&self) -> Origin;
68
69    /// The functional block (2.x) or feature profile (1.6) the action belongs to.
70    fn block(&self) -> &'static str;
71}
72
73/// A request payload.
74pub trait Request: Serialize + DeserializeOwned + Validate + Sealed {
75    /// This version's action enum.
76    type Action: ActionName;
77    /// The action this payload belongs to.
78    const ACTION: Self::Action;
79    /// `CALL` or `SEND`.
80    const KIND: MessageKind;
81    /// Which peer originates this request.
82    const ORIGIN: Origin;
83    /// The matching response payload, or [`NoResponse`] for a `SEND`.
84    type Response: Response;
85}
86
87/// A request that is answered — everything except an OCPP 2.1 `SEND`.
88///
89/// The bound exists so that awaiting a response the specification forbids the peer from ever
90/// sending is a *compile* error rather than a message timeout. It is implemented by the code
91/// generator for exactly those actions whose schema directory contains a `…Response.json`.
92pub trait Confirmed: Request {}
93
94/// An unconfirmed request — an OCPP 2.1 `SEND` (Part 4 §4.2.4).
95///
96/// Disjoint from [`Confirmed`]: an action is one or the other, never both.
97pub trait Unconfirmed: Request<Response = NoResponse> {}
98
99/// A response payload.
100pub trait Response: Serialize + DeserializeOwned + Validate + Sealed {}
101
102/// The response type of a `SEND`, which by definition never has one (Part 4 §4.2.4).
103///
104/// It is uninhabited, so a `SEND` cannot be awaited by construction.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub enum NoResponse {}
107
108impl Sealed for NoResponse {}
109impl Response for NoResponse {}
110
111impl Validate for NoResponse {
112    fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
113}
114
115impl Serialize for NoResponse {
116    fn serialize<S: serde::Serializer>(&self, _ser: S) -> Result<S::Ok, S::Error> {
117        match *self {}
118    }
119}
120
121impl<'de> serde::Deserialize<'de> for NoResponse {
122    fn deserialize<D: serde::Deserializer<'de>>(_de: D) -> Result<Self, D::Error> {
123        Err(serde::de::Error::custom("a SEND message has no response"))
124    }
125}
126
127/// An action name this version does not define.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub struct UnknownAction;
130
131impl fmt::Display for UnknownAction {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        f.write_str("unknown OCPP action for this version")
134    }
135}
136
137#[cfg(feature = "std")]
138impl std::error::Error for UnknownAction {}
139
140/// An enumeration value this version does not define.
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub struct UnknownVariant {
143    /// The enumeration that rejected the value.
144    pub type_name: &'static str,
145}
146
147impl fmt::Display for UnknownVariant {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        write!(f, "not a defined value of {}", self.type_name)
150    }
151}
152
153#[cfg(feature = "std")]
154impl std::error::Error for UnknownVariant {}