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/// A union of the requests one side receives — `v2_1::CsRequest` on a CSMS,
103/// `v2_1::CsmsRequest` on a station — decodable from an action and a raw payload.
104///
105/// Implemented by the code generator. A handler normally uses it through
106/// [`Ctx::decode`](crate::transport::Ctx::decode), which also reports what leniency forgave.
107pub trait DecodeRequest: Sized + Sealed {
108 /// This version's action enum.
109 type Action: ActionName;
110
111 /// Decodes `payload` for `action`, returning the value and every
112 /// [`Repair`](crate::decode::Repair) the options applied.
113 ///
114 /// # Errors
115 ///
116 /// The classified [`DecodeError`](crate::decode::DecodeError) — including
117 /// `UnsupportedAction` when `action` is not one this side receives.
118 fn decode_reporting(
119 action: Self::Action,
120 payload: &serde_json::value::RawValue,
121 options: &crate::decode::DecodeOptions,
122 ) -> Result<crate::decode::Decoded<Self>, crate::decode::DecodeError>;
123}
124
125/// The response type of a `SEND`, which by definition never has one (Part 4 §4.2.4).
126///
127/// It is uninhabited, so a `SEND` cannot be awaited by construction.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum NoResponse {}
130
131impl Sealed for NoResponse {}
132impl Response for NoResponse {}
133
134impl Validate for NoResponse {
135 fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
136}
137
138impl Serialize for NoResponse {
139 fn serialize<S: serde::Serializer>(&self, _ser: S) -> Result<S::Ok, S::Error> {
140 match *self {}
141 }
142}
143
144impl<'de> serde::Deserialize<'de> for NoResponse {
145 fn deserialize<D: serde::Deserializer<'de>>(_de: D) -> Result<Self, D::Error> {
146 Err(serde::de::Error::custom("a SEND message has no response"))
147 }
148}
149
150/// An action name this version does not define.
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152pub struct UnknownAction;
153
154impl fmt::Display for UnknownAction {
155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156 f.write_str("unknown OCPP action for this version")
157 }
158}
159
160#[cfg(feature = "std")]
161impl std::error::Error for UnknownAction {}
162
163/// An enumeration value this version does not define.
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub struct UnknownVariant {
166 /// The enumeration that rejected the value.
167 pub type_name: &'static str,
168}
169
170impl fmt::Display for UnknownVariant {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 write!(f, "not a defined value of {}", self.type_name)
173 }
174}
175
176#[cfg(feature = "std")]
177impl std::error::Error for UnknownVariant {}