Skip to main content

ocpp_kit/engine/
mod.rs

1//! Layer 2 — the sans-I/O protocol engine.
2//!
3//! [`Engine`] is a pure state machine. It owns no socket, reads no clock and spawns no task:
4//! the driver feeds it [`Input`]s and drains [`Output`]s. That is what makes every timing
5//! rule in OCPP — message timeouts, the linear transaction-retry schedule, boot back-off —
6//! testable in microseconds, and what lets the same code run on Tokio, inside an `embassy`
7//! firmware loop, or in a browser.
8//!
9//! Every entry point takes the driver's current [`Instant`]: the engine has no clock of its
10//! own, and a deadline armed against a stale one fires the moment it is armed.
11//!
12//! ```
13//! use ocpp_kit::Version;
14//! use ocpp_kit::engine::{Engine, EngineConfig, Input, Instant, Output, Role};
15//! use serde_json::value::RawValue;
16//!
17//! let now = Instant::ZERO;
18//! let mut engine = Engine::new(EngineConfig::new(Role::ChargingStation, Version::V2_1));
19//! engine.handle(now, Input::Connected { version: Version::V2_1 });
20//!
21//! let payload = RawValue::from_string(
22//!     r#"{"reason":"PowerUp","chargingStation":{"model":"M1","vendorName":"ACME"}}"#.into(),
23//! )
24//! .unwrap();
25//! engine.call(now, "BootNotification", payload).unwrap();
26//!
27//! let frame = engine
28//!     .drain()
29//!     .into_iter()
30//!     .find_map(|output| match output {
31//!         Output::Transmit(text) => Some(text),
32//!         _ => None,
33//!     })
34//!     .unwrap();
35//! assert!(frame.starts_with(r#"[2,"#));
36//! ```
37//!
38//! In a test, [`Sim`](crate::testkit::Sim) owns the clock for you and the same session reads
39//! as a transcript.
40//!
41//! # Rules this layer enforces
42//!
43//! * **One outstanding `CALL` per direction** (2.x Part 4 §4.1.1 `SHALL NOT`; 1.6J §4.1.1
44//!   `SHOULD NOT` — hence [`InboundConcurrency`]). Our own extra calls are queued, never
45//!   rejected.
46//! * **`SEND` is exempt** and is never answered (Part 4 §4.2.4, FR.07).
47//! * **Unknown message type numbers** are ignored on every version (1.6J §4.1.3, 2.x
48//!   Part 4 §4.1).
49//! * **Message timeout**, freeing the slot and starting the next queued call.
50//! * **Transaction-message retries only**, on the linear schedule of 1.6 §3.7.1 and the 2.x
51//!   `MessageAttempts[TransactionEvent]` variables, in chronological order, skipping a
52//!   message once its attempts are exhausted.
53//! * **Durable offline queueing** of transaction messages (E04/E08/E12) via
54//!   [`MessageStore`] — [`MemStore`] in memory, [`FileStore`] on disk, or your own.
55//! * **The boot state machine** (B01–B04) on *both* sides, including the CSMS's
56//!   `SecurityError` answer to an unsolicited call from a `Pending` station (B02.FR.09).
57//! * **Graceful drain**: finish the in-flight call, flush the queue, then close.
58
59mod backoff;
60mod queue;
61mod rate;
62#[cfg(feature = "std")]
63mod store_file;
64mod time;
65
66use alloc::boxed::Box;
67use alloc::collections::{BTreeSet, VecDeque};
68use alloc::format;
69use alloc::string::{String, ToString};
70use alloc::vec::Vec;
71use core::fmt;
72use core::time::Duration;
73
74use serde::Deserialize;
75use serde_json::value::RawValue;
76
77use crate::actions;
78use crate::message::{MessageKind, Origin};
79use crate::rpc::{CallError, CallErrorRef, ErrorCode, Frame, FrameError, FrameReply};
80use crate::types::{DateTime, IdGenerator, MessageId};
81use crate::version::Version;
82
83pub use backoff::{Backoff, Jitter};
84pub use queue::{MemStore, MessageStore, QueuedCall, RetryPolicy, Seq, StoreError};
85pub use rate::{InvalidRateLimit, RateLimit};
86#[cfg(feature = "std")]
87pub use store_file::FileStore;
88pub use time::{Instant, Timer};
89
90/// Which side of the connection this engine is.
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub enum Role {
93    /// A Charging Station: it dials out, and it boots.
94    ChargingStation,
95    /// A CSMS: it accepts connections and decides whether a station may proceed.
96    Csms,
97}
98
99impl Role {
100    /// The origin this engine is allowed to send.
101    const fn sends(self) -> Origin {
102        match self {
103            Role::ChargingStation => Origin::ChargingStation,
104            Role::Csms => Origin::Csms,
105        }
106    }
107
108    /// The origin this engine expects to receive.
109    const fn receives(self) -> Origin {
110        match self {
111            Role::ChargingStation => Origin::Csms,
112            Role::Csms => Origin::ChargingStation,
113        }
114    }
115}
116
117/// What to do when the peer breaks the one-outstanding-`CALL` rule.
118///
119/// 1.6J §4.1.1 words it as `SHOULD NOT`, 2.x Part 4 §4.1.1 as `SHALL NOT`. Field stations
120/// break it either way, and dropping their calls is usually worse than serving them.
121#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
122pub enum InboundConcurrency {
123    /// Answer the extra call normally. The default, and the only workable choice on 1.6.
124    #[default]
125    Serve,
126    /// Answer the extra call with `CALLERROR: ProtocolError`.
127    Reject,
128}
129
130/// Whether the engine sends `Heartbeat` on its own.
131#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
132pub enum HeartbeatPolicy {
133    /// The engine schedules and sends `Heartbeat` itself.
134    ///
135    /// `OCPPCommCtrlr.HeartbeatInterval` is defined as the *interval of inactivity* — "no
136    /// OCPP exchanges" — after which a station sends `Heartbeat`, so the timer is an idle
137    /// timer that every frame in either direction resets, not a fixed period. The payload is
138    /// an empty object in every version, so no application code is needed.
139    #[default]
140    Automatic,
141    /// The application sends `Heartbeat` itself; the engine only reports the interval.
142    Manual,
143}
144
145/// What happens to outgoing calls while the connection is down.
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147pub struct OfflinePolicy {
148    /// Queue every message, not just transaction-related ones — the 1.6
149    /// `QueueAllMessages` behaviour.
150    pub queue_all_messages: bool,
151    /// Upper bound on the in-memory queue. Reached, further calls fail with
152    /// [`CallFailure::QueueFull`] instead of growing without limit.
153    pub max_queued: usize,
154}
155
156impl Default for OfflinePolicy {
157    fn default() -> Self {
158        Self {
159            queue_all_messages: false,
160            max_queued: 1024,
161        }
162    }
163}
164
165/// Engine configuration.
166#[derive(Clone, Debug)]
167#[non_exhaustive]
168pub struct EngineConfig {
169    /// Which side this is.
170    pub role: Role,
171    /// The negotiated protocol version.
172    pub version: Version,
173    /// How long to wait for a `CALLRESULT` / `CALLERROR`.
174    ///
175    /// The specification deliberately leaves this implementation-defined (Part 4 §4.1.1);
176    /// 2.x sources it from `NetworkConnectionProfile.messageTimeout`, falling back to
177    /// `OCPPCommCtrlr.MessageTimeout[Default]`. 30 s is the widely used default.
178    pub call_timeout: Duration,
179    /// What to do about a peer that keeps two calls in flight.
180    pub inbound_concurrency: InboundConcurrency,
181    /// Whether the engine sends `Heartbeat` itself.
182    pub heartbeat: HeartbeatPolicy,
183    /// Retry schedule for transaction-related messages.
184    pub retry: RetryPolicy,
185    /// Offline queueing behaviour.
186    pub offline: OfflinePolicy,
187    /// Reconnect back-off parameters, for the driver to use (Part 4 §5.4).
188    pub backoff: Backoff,
189    /// Whether the boot state machine gates outgoing calls (B02.FR.02).
190    ///
191    /// Always on for a Charging Station; a CSMS uses it to enforce B02.FR.09.
192    pub enforce_boot_gate: bool,
193    /// How long to wait before re-sending `BootNotification` when the CSMS answered
194    /// `Pending` or `Rejected` with `interval = 0` (B02.FR.07).
195    pub boot_retry_fallback: Duration,
196    /// Upper bound on the peer's simultaneously unanswered `CALL`s.
197    ///
198    /// The specification allows exactly one (Part 4 §4.1.1), and
199    /// [`InboundConcurrency::Serve`] deliberately tolerates more — but "more" must still be
200    /// finite, or a peer that never stops asking can make the receiver hold requests, and
201    /// handler tasks, without limit. Beyond this many the extra call is answered
202    /// `ProtocolError` regardless of [`InboundConcurrency`].
203    pub max_peer_requests: usize,
204    /// How often the peer may send unprompted messages; `None` (the default) for no limit.
205    ///
206    /// Counted: every `CALL`, `SEND`, malformed frame and answer to a call that is not
207    /// outstanding. Never counted: answers to our own outstanding call, whose rate is ours.
208    /// Over the rate, a `CALL` is answered `SecurityError` before any other check — it never
209    /// becomes an [`Output::Request`] or an in-flight call — and everything else is dropped
210    /// without an answer or a violation, because answering a flood is what it is for.
211    /// [`Output::RateLimited`] reports the first refusal of each run.
212    pub inbound_rate: Option<RateLimit>,
213}
214
215impl EngineConfig {
216    /// A configuration with the specification's defaults.
217    #[must_use]
218    pub fn new(role: Role, version: Version) -> Self {
219        Self {
220            role,
221            version,
222            call_timeout: Duration::from_secs(30),
223            inbound_concurrency: InboundConcurrency::Serve,
224            heartbeat: HeartbeatPolicy::Automatic,
225            retry: RetryPolicy::default(),
226            offline: OfflinePolicy::default(),
227            backoff: Backoff::default(),
228            enforce_boot_gate: true,
229            boot_retry_fallback: Duration::from_secs(30),
230            max_peer_requests: 64,
231            inbound_rate: None,
232        }
233    }
234
235    /// Sets the message timeout.
236    #[must_use]
237    pub const fn with_call_timeout(mut self, timeout: Duration) -> Self {
238        self.call_timeout = timeout;
239        self
240    }
241
242    /// Sets the transaction retry schedule.
243    #[must_use]
244    pub const fn with_retry(mut self, retry: RetryPolicy) -> Self {
245        self.retry = retry;
246        self
247    }
248
249    /// Sets the offline queueing policy.
250    #[must_use]
251    pub const fn with_offline(mut self, offline: OfflinePolicy) -> Self {
252        self.offline = offline;
253        self
254    }
255
256    /// Sets the heartbeat policy.
257    #[must_use]
258    pub const fn with_heartbeat(mut self, heartbeat: HeartbeatPolicy) -> Self {
259        self.heartbeat = heartbeat;
260        self
261    }
262
263    /// Limits how often the peer may send unprompted messages. See
264    /// [`inbound_rate`](Self::inbound_rate).
265    #[must_use]
266    pub const fn with_inbound_rate(mut self, rate: RateLimit) -> Self {
267        self.inbound_rate = Some(rate);
268        self
269    }
270
271    /// Sets what happens when the peer keeps two calls in flight.
272    #[must_use]
273    pub const fn with_inbound_concurrency(mut self, mode: InboundConcurrency) -> Self {
274        self.inbound_concurrency = mode;
275        self
276    }
277}
278
279/// The boot state machine (OCPP 2.x block B; 1.6 §4.2).
280#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
281pub enum BootState {
282    /// No `BootNotification` has been answered yet. Only `BootNotification` and messages the
283    /// CSMS explicitly asked for may be sent (B02.FR.02).
284    #[default]
285    Idle,
286    /// The CSMS answered `Pending`: it is still configuring the station. The connection
287    /// stays open (B02.FR.06) and the station may only answer what it is asked.
288    Pending,
289    /// The CSMS answered `Accepted`. Normal operation.
290    Accepted,
291    /// The CSMS answered `Rejected`. The station must wait for the interval before trying
292    /// again (B02.FR.08).
293    Rejected,
294}
295
296impl BootState {
297    /// Whether ordinary, unsolicited calls may be sent.
298    ///
299    /// Only `Accepted` does: B01.FR.08 keeps a freshly powered station quiet until the CSMS
300    /// answers, and B02.FR.02 keeps it quiet while the answer is `Pending`.
301    #[must_use]
302    pub const fn allows_traffic(self) -> bool {
303        matches!(self, BootState::Accepted)
304    }
305
306    /// Whether a *CSMS* must answer an unsolicited call with `SecurityError`.
307    ///
308    /// B01.FR.10 and B02.FR.09 both have the same precondition: *the Charging Station has
309    /// received a `BootNotificationResponse` whose status is not `Accepted`*. A station that
310    /// has not been answered at all — the normal state of a reconnected station, which
311    /// Part 4 §5.4 tells not to repeat its `BootNotification` — is therefore not covered,
312    /// and blocking it would break every reconnect.
313    #[must_use]
314    pub const fn blocks_unsolicited_traffic(self) -> bool {
315        matches!(self, BootState::Pending | BootState::Rejected)
316    }
317}
318
319/// A handle to a call the application asked for.
320///
321/// Issued when the call is accepted — which may be long before it reaches the wire, since it
322/// can sit in the offline queue — and reported back in [`CallOutcome`].
323#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
324pub struct CallToken(u64);
325
326impl fmt::Display for CallToken {
327    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328        write!(f, "call#{}", self.0)
329    }
330}
331
332/// Per-call overrides.
333#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
334#[non_exhaustive]
335pub struct CallOptions {
336    /// The CSMS asked for this message (`TriggerMessage`, `GetBaseReport`, …), so the boot
337    /// gate does not apply to it (B02.FR.02).
338    pub triggered: bool,
339    /// Override whether the message is queued durably. Defaults to "yes for
340    /// transaction-related messages".
341    pub persist: Option<bool>,
342    /// Override whether the message survives a disconnection. Defaults to the
343    /// [`OfflinePolicy`].
344    pub queue_when_offline: Option<bool>,
345}
346
347impl CallOptions {
348    /// Marks the call as one the peer explicitly requested.
349    #[must_use]
350    pub const fn triggered() -> Self {
351        Self {
352            triggered: true,
353            persist: None,
354            queue_when_offline: None,
355        }
356    }
357
358    /// Overrides whether the call is written to the durable [`MessageStore`].
359    #[must_use]
360    pub const fn persist(mut self, persist: bool) -> Self {
361        self.persist = Some(persist);
362        self
363    }
364
365    /// Overrides whether the call waits out a disconnection instead of failing.
366    #[must_use]
367    pub const fn queue_when_offline(mut self, queue: bool) -> Self {
368        self.queue_when_offline = Some(queue);
369        self
370    }
371}
372
373/// Something the peer did that the specification forbids, but which is not fatal.
374#[derive(Clone, Debug, PartialEq, Eq)]
375#[non_exhaustive]
376pub enum ProtocolViolation {
377    /// A `CALLRESULT` / `CALLERROR` arrived for an id that is not outstanding.
378    UnexpectedResponse {
379        /// The id that was answered.
380        id: MessageId,
381    },
382    /// A message type number outside 2–6 (Part 4 §4.4).
383    UnknownMessageType {
384        /// The raw JSON of the type element.
385        number: String,
386    },
387    /// The peer started a second `CALL` while one was still outstanding.
388    ConcurrentCall {
389        /// The id of the extra call.
390        id: MessageId,
391    },
392    /// The peer sent an action defined as a `SEND` as a `CALL`, or the other way round
393    /// (N15.FR.01).
394    WrongMessageKind {
395        /// The action name.
396        action: String,
397        /// The kind it arrived as.
398        received: MessageKind,
399    },
400    /// The peer sent an action it is not allowed to originate.
401    WrongDirection {
402        /// The action name.
403        action: String,
404    },
405    /// The peer used a `MessageId` longer than 36 characters.
406    NonConformingMessageId {
407        /// The id, kept verbatim so responses still correlate.
408        id: MessageId,
409    },
410    /// The peer reused a `MessageId` that is still unanswered (Part 4 §4.1.4, §4.2.3).
411    DuplicateMessageId {
412        /// The id that was reused.
413        id: MessageId,
414    },
415    /// The peer has more unanswered `CALL`s than
416    /// [`EngineConfig::max_peer_requests`] allows.
417    TooManyPeerRequests {
418        /// The id of the call that went over the limit.
419        id: MessageId,
420    },
421    /// The frame could not be parsed at all.
422    MalformedFrame {
423        /// The parse failure.
424        error: FrameError,
425    },
426    /// The durable store failed.
427    StoreFailure {
428        /// The store's complaint.
429        error: StoreError,
430    },
431    /// A frame this peer wanted to send could not be serialized.
432    ///
433    /// Only reachable from a payload the application supplied, since everything else the
434    /// engine builds is known-good JSON.
435    UnserializableFrame {
436        /// What `serde_json` said.
437        reason: String,
438    },
439}
440
441/// Why the engine wants the connection closed.
442#[derive(Clone, Debug, PartialEq, Eq)]
443#[non_exhaustive]
444pub enum CloseReason {
445    /// A graceful drain finished.
446    Drained,
447    /// The drain deadline passed with work still queued.
448    DrainTimedOut,
449    /// The application asked for it.
450    Requested,
451}
452
453/// A request the peer sent that the application must handle.
454#[derive(Clone, Debug)]
455pub struct IncomingRequest {
456    /// Correlation id. Pass it back to [`Engine::respond`].
457    pub id: MessageId,
458    /// The action name, already checked against the version and the direction.
459    pub action: String,
460    /// The still-unparsed payload.
461    pub payload: Box<RawValue>,
462    /// `Call` (answer it) or `Send` (do not).
463    pub kind: MessageKind,
464}
465
466/// Why a call did not succeed.
467#[derive(Clone, Debug, PartialEq)]
468#[non_exhaustive]
469pub enum CallFailure {
470    /// The peer answered `CALLERROR`.
471    Rejected(CallError),
472    /// No answer arrived before [`EngineConfig::call_timeout`].
473    Timeout,
474    /// The connection went away and the message was not queued.
475    Disconnected,
476    /// A transaction message used up its attempts and was skipped (1.6 §3.7.1).
477    RetriesExhausted,
478    /// The offline queue is full.
479    QueueFull,
480    /// The application withdrew the call before it was transmitted.
481    Cancelled,
482    /// The engine is draining and refused a new call.
483    ShuttingDown,
484}
485
486impl fmt::Display for CallFailure {
487    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
488        match self {
489            CallFailure::Rejected(error) => write!(f, "peer answered {error}"),
490            CallFailure::Timeout => f.write_str("no answer before the message timeout"),
491            CallFailure::Disconnected => f.write_str("connection lost"),
492            CallFailure::RetriesExhausted => f.write_str("transaction message attempts exhausted"),
493            CallFailure::QueueFull => f.write_str("offline queue is full"),
494            CallFailure::Cancelled => f.write_str("cancelled before transmission"),
495            CallFailure::ShuttingDown => f.write_str("engine is draining"),
496        }
497    }
498}
499
500#[cfg(feature = "std")]
501impl std::error::Error for CallFailure {}
502
503/// How a message the application started ended, when it ended well.
504///
505/// A `CALL` succeeds when the peer answers; a `SEND` when it is written, because Part 4
506/// §4.2.4 forbids the peer from ever answering one.
507#[derive(Clone, Debug)]
508#[non_exhaustive]
509pub enum Answer {
510    /// The peer's `CALLRESULT` payload.
511    Result(Box<RawValue>),
512    /// A `SEND` reached the wire. There is nothing further to wait for.
513    Sent,
514}
515
516impl Answer {
517    /// The peer's payload, or `None` for a `SEND`.
518    #[must_use]
519    pub fn payload(&self) -> Option<&RawValue> {
520        match self {
521            Answer::Result(payload) => Some(payload),
522            Answer::Sent => None,
523        }
524    }
525
526    /// Unwraps the peer's payload, or `None` for a `SEND`.
527    #[must_use]
528    pub fn into_payload(self) -> Option<Box<RawValue>> {
529        match self {
530            Answer::Result(payload) => Some(payload),
531            Answer::Sent => None,
532        }
533    }
534}
535
536/// The final result of a call the application started.
537#[derive(Clone, Debug)]
538pub struct CallOutcome {
539    /// The handle returned by [`Engine::call`].
540    pub token: CallToken,
541    /// The `MessageId` it was sent with, if it ever reached the wire.
542    pub id: Option<MessageId>,
543    /// The action.
544    pub action: String,
545    /// How it ended.
546    pub result: Result<Answer, CallFailure>,
547}
548
549/// An authoritative timestamp observed in a `BootNotificationResponse` or
550/// `HeartbeatResponse`.
551///
552/// A station whose `ClockCtrlr.TimeSource` is `Heartbeat` uses this to discipline its clock;
553/// `at` is the monotonic instant the answer arrived, so the application can subtract the
554/// round-trip.
555#[derive(Clone, Copy, Debug, PartialEq, Eq)]
556pub struct ClockSample {
557    /// The CSMS's `currentTime`.
558    pub csms_time: DateTime,
559    /// When the answer was processed, on the driver's monotonic clock.
560    pub at: Instant,
561}
562
563/// What the driver must do next.
564#[derive(Clone, Debug)]
565#[non_exhaustive]
566pub enum Output {
567    /// Write this UTF-8 text frame to the WebSocket.
568    Transmit(String),
569    /// The peer sent a request. Answer a `Call` with [`Engine::respond`]; a `Send` needs no
570    /// answer and must not get one.
571    Request(IncomingRequest),
572    /// One of our calls finished.
573    Outcome(CallOutcome),
574    /// The peer rejected a `CALLRESULT` we sent, with `CALLRESULTERROR` (OCPP 2.1).
575    ResultRejected {
576        /// The id of the result the peer could not use.
577        id: MessageId,
578        /// Why.
579        error: CallError,
580    },
581    /// Arm a timer. Re-arming an already-armed timer replaces it.
582    SetTimer {
583        /// Which timer.
584        timer: Timer,
585        /// When it should fire, on the driver's monotonic clock.
586        at: Instant,
587    },
588    /// Disarm a timer.
589    ClearTimer(Timer),
590    /// The boot state changed (Charging Station side), or was decided (CSMS side).
591    BootState(BootState),
592    /// A `currentTime` was observed.
593    ClockSample(ClockSample),
594    /// The peer misbehaved. Never fatal by itself; log it and carry on.
595    Violation(ProtocolViolation),
596    /// The peer went over [`EngineConfig::inbound_rate`] and is being refused.
597    ///
598    /// Once per run of refusals: the next one comes only after a message was admitted again.
599    RateLimited,
600    /// Close the connection.
601    Close(CloseReason),
602}
603
604/// Events the driver feeds into the engine, via [`Engine::handle`].
605#[derive(Clone, Copy, Debug)]
606#[non_exhaustive]
607pub enum Input<'a> {
608    /// The WebSocket handshake completed with this negotiated version.
609    Connected {
610        /// The subprotocol the peer selected.
611        version: Version,
612    },
613    /// One complete text frame arrived.
614    Received(&'a str),
615    /// The connection went away.
616    Disconnected,
617    /// Nothing happened but time. Every timer whose deadline has passed fires.
618    Timeout,
619}
620
621/// Why a command was refused.
622#[derive(Clone, Debug, PartialEq, Eq)]
623#[non_exhaustive]
624pub enum EngineError {
625    /// This version does not define the action.
626    UnknownAction(String),
627    /// This peer is not allowed to originate the action.
628    WrongDirection(String),
629    /// A `SEND` was requested on a version that has no `SEND` (before 2.1).
630    SendNotSupported(String),
631    /// The action is a `SEND` but was submitted as a call, or the other way round.
632    WrongMessageKind(String),
633    /// No outstanding request has that id.
634    NoSuchRequest(MessageId),
635    /// `CALLRESULTERROR` needs OCPP 2.1.
636    CallResultErrorNotSupported,
637    /// The engine is draining.
638    ShuttingDown,
639}
640
641impl fmt::Display for EngineError {
642    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643        match self {
644            EngineError::UnknownAction(action) => write!(f, "unknown action {action:?}"),
645            EngineError::WrongDirection(action) => {
646                write!(f, "this peer may not originate {action:?}")
647            }
648            EngineError::SendNotSupported(action) => {
649                write!(f, "{action:?} is a SEND, which needs OCPP 2.1")
650            }
651            EngineError::WrongMessageKind(action) => {
652                write!(f, "{action:?} was submitted with the wrong message kind")
653            }
654            EngineError::NoSuchRequest(id) => write!(f, "no outstanding request with id {id}"),
655            EngineError::CallResultErrorNotSupported => {
656                f.write_str("CALLRESULTERROR needs OCPP 2.1")
657            }
658            EngineError::ShuttingDown => f.write_str("engine is draining"),
659        }
660    }
661}
662
663#[cfg(feature = "std")]
664impl std::error::Error for EngineError {}
665
666// ---------------------------------------------------------------------------
667// Internal state
668// ---------------------------------------------------------------------------
669
670#[derive(Debug)]
671struct Pending {
672    token: CallToken,
673    action: String,
674    payload: Box<RawValue>,
675    kind: MessageKind,
676    transactional: bool,
677    attempts: u32,
678    /// Sequence number in the durable store, when persisted.
679    seq: Option<Seq>,
680    /// Not eligible for transmission before this instant (retry back-off).
681    not_before: Option<Instant>,
682    triggered: bool,
683    queue_when_offline: bool,
684}
685
686#[derive(Debug)]
687struct InFlight {
688    id: MessageId,
689    token: CallToken,
690    action: String,
691    transactional: bool,
692    attempts: u32,
693    seq: Option<Seq>,
694    payload: Box<RawValue>,
695    triggered: bool,
696    queue_when_offline: bool,
697    deadline: Instant,
698}
699
700/// Minimal view of a `BootNotificationResponse`, the one payload the engine looks inside.
701///
702/// The three members it needs have the same names and meanings in 1.6 and 2.x, so one shape
703/// covers every version. Nothing else is parsed, and a payload that does not match is
704/// ignored rather than treated as an error — the application still sees it in full.
705#[derive(Deserialize)]
706struct BootAnswer<'a> {
707    status: &'a str,
708    #[serde(default)]
709    interval: Option<u64>,
710    #[serde(default)]
711    #[serde(rename = "currentTime")]
712    current_time: Option<DateTime>,
713}
714
715#[derive(Deserialize)]
716struct HeartbeatAnswer {
717    #[serde(rename = "currentTime")]
718    current_time: DateTime,
719}
720
721#[derive(Deserialize)]
722struct TriggerRequest<'a> {
723    #[serde(default)]
724    #[serde(rename = "requestedMessage")]
725    requested_message: Option<&'a str>,
726}
727
728/// The sans-I/O OCPP protocol engine.
729///
730/// See the [module documentation](self) for the rules it enforces.
731pub struct Engine<S: MessageStore = MemStore> {
732    config: EngineConfig,
733    store: S,
734    ids: Box<dyn IdGenerator + Send>,
735    outputs: VecDeque<Output>,
736    queue: VecDeque<Pending>,
737    inflight: Option<InFlight>,
738    /// The ids of the `CALL`s the peer is waiting on.
739    ///
740    /// Normally at most one — that is the rule — but [`InboundConcurrency::Serve`] means a
741    /// peer that breaks it is answered anyway, and every one of its calls still has to be
742    /// matched to its answer.
743    peer_inflight: BTreeSet<MessageId>,
744    connected: bool,
745    version: Version,
746    now: Instant,
747    next_token: u64,
748    boot: BootState,
749    heartbeat_interval: Option<Duration>,
750    /// Actions the CSMS asked this station for, which therefore survive the boot gate
751    /// (B02.FR.09).
752    solicited: BTreeSet<String>,
753    draining: Option<Instant>,
754    boot_retry_at: Option<Instant>,
755    heartbeat_at: Option<Instant>,
756    /// The inbound rate limiter, when one is configured. Its state lives as long as the
757    /// engine — one connection on a CSMS, which builds an engine per session.
758    rate: Option<rate::Gcra>,
759}
760
761impl Engine<MemStore> {
762    /// An engine with an in-memory queue.
763    #[must_use]
764    pub fn new(config: EngineConfig) -> Self {
765        Self::with_store(config, MemStore::new()).expect("MemStore never fails")
766    }
767}
768
769impl<S: MessageStore> Engine<S> {
770    /// An engine backed by a durable [`MessageStore`].
771    ///
772    /// Anything the store still holds is loaded into the queue, so a Charging Station
773    /// replays the transaction messages a power cut interrupted.
774    pub fn with_store(config: EngineConfig, store: S) -> Result<Self, StoreError> {
775        let version = config.version;
776        let rate = config.inbound_rate.map(rate::Gcra::new);
777        let mut engine = Self {
778            config,
779            store,
780            ids: default_ids(),
781            outputs: VecDeque::new(),
782            queue: VecDeque::new(),
783            inflight: None,
784            peer_inflight: BTreeSet::new(),
785            connected: false,
786            version,
787            now: Instant::ZERO,
788            next_token: 0,
789            boot: BootState::Idle,
790            heartbeat_interval: None,
791            solicited: BTreeSet::new(),
792            draining: None,
793            boot_retry_at: None,
794            heartbeat_at: None,
795            rate,
796        };
797        for (seq, entry) in engine.store.pending()? {
798            let pending = engine.stored(seq, entry);
799            engine.queue.push_back(pending);
800        }
801        Ok(engine)
802    }
803
804    /// Re-opens the boot gate, so the station registers again before ordinary traffic.
805    ///
806    /// The engine keeps its boot state across reconnects (Part 4 §5.4). The exception is
807    /// B10.FR.10 (2.0.1 edition 4, 2.1 edition 2): a station that "successfully connected after
808    /// having switched to a different `NetworkConnectionProfile`" SHALL send a
809    /// `BootNotificationRequest` "even if it has not rebooted". This returns the engine to
810    /// [`BootState::Idle`] and reports it as [`Output::BootState`], the same signal a
811    /// `Pending`/`Rejected` retry gives; the application then sends the `BootNotification`.
812    /// The Tokio station calls it when it connects on a different configuration slot.
813    pub fn require_boot(&mut self, now: Instant) {
814        self.advance(now);
815        if self.config.role != Role::ChargingStation || self.boot == BootState::Idle {
816            return;
817        }
818        self.boot = BootState::Idle;
819        self.boot_retry_at = None;
820        self.outputs.push_back(Output::BootState(BootState::Idle));
821    }
822
823    /// Queues what another process added to the store since this engine was built.
824    ///
825    /// The engine reads its store when it is built ([`with_store`](Self::with_store)) and
826    /// otherwise only writes it. With a store shared between processes — a station and a
827    /// metering daemon on one SQLite file — a message the other process pushes is durable at
828    /// once but would leave only on the next start. This reads [`MessageStore::pending`] again
829    /// and queues every entry whose [`Seq`] the engine does not already hold, queued or in
830    /// flight, so calling it twice queues nothing twice.
831    ///
832    /// Among messages not yet sent, stored ones are ordered by `Seq`, so each producer's
833    /// messages leave in the order it pushed them — what per-transaction ordering requires
834    /// (1.6 §3.7, E04.FR.01–03), since one transaction's messages come from one producer. A
835    /// message already sent is never reordered. Adoption obeys
836    /// [`OfflinePolicy::max_queued`]: what does not fit stays in the store, still counted by
837    /// [`MessageStore::len`], and is adopted by a later call. During a
838    /// [`shutdown`](Self::shutdown) drain nothing is adopted.
839    ///
840    /// Only one engine may drain a store. A second one would adopt — and send — every entry
841    /// the first holds; other processes push and never drain.
842    ///
843    /// Returns how many entries were queued. The Tokio station calls this on connect and
844    /// periodically when built with `store_poll`.
845    ///
846    /// # Errors
847    ///
848    /// The store's error from `pending()`. The queue is unchanged.
849    pub fn adopt_pending(&mut self, now: Instant) -> Result<usize, StoreError> {
850        self.advance(now);
851        if self.draining.is_some() {
852            return Ok(0);
853        }
854        let held: BTreeSet<Seq> = self
855            .queue
856            .iter()
857            .filter_map(|entry| entry.seq)
858            .chain(self.inflight.as_ref().and_then(|inflight| inflight.seq))
859            .collect();
860        let mut room = self
861            .config
862            .offline
863            .max_queued
864            .saturating_sub(self.queue.len());
865        let mut adopted = 0;
866        for (seq, entry) in self.store.pending()? {
867            if held.contains(&seq) {
868                continue;
869            }
870            if room == 0 {
871                break;
872            }
873            let pending = self.stored(seq, entry);
874            let at = self
875                .queue
876                .iter()
877                .position(|queued| queued.seq.is_some_and(|queued| queued > seq))
878                .unwrap_or(self.queue.len());
879            self.queue.insert(at, pending);
880            room -= 1;
881            adopted += 1;
882        }
883        if adopted > 0 {
884            self.pump();
885        }
886        Ok(adopted)
887    }
888
889    /// The queue entry for a message read back from the store.
890    fn stored(&mut self, seq: Seq, entry: QueuedCall) -> Pending {
891        Pending {
892            token: self.mint_token(),
893            action: entry.action,
894            payload: entry.payload,
895            kind: entry.kind,
896            transactional: entry.transactional,
897            attempts: entry.attempts,
898            seq: Some(seq),
899            not_before: None,
900            triggered: false,
901            queue_when_offline: true,
902        }
903    }
904
905    /// Changes the message timeout.
906    ///
907    /// 2.x sources it from the active `NetworkConnectionProfile.messageTimeout`, falling back
908    /// to `OCPPCommCtrlr.MessageTimeout[Default]` — so it changes when the station fails over
909    /// to a different network configuration slot, and it must be changeable at run time.
910    /// A call that is already outstanding keeps the deadline it was given.
911    pub fn set_call_timeout(&mut self, timeout: Duration) {
912        self.config.call_timeout = timeout;
913    }
914
915    /// Replaces the [`IdGenerator`].
916    ///
917    /// A Local Controller uses this to guarantee that the ids it invents cannot collide with
918    /// the CSMS's (Part 4 §6.4).
919    pub fn set_id_generator(&mut self, ids: Box<dyn IdGenerator + Send>) {
920        self.ids = ids;
921    }
922
923    /// The configuration this engine was built with.
924    #[must_use]
925    pub fn config(&self) -> &EngineConfig {
926        &self.config
927    }
928
929    /// The negotiated version.
930    #[must_use]
931    pub fn version(&self) -> Version {
932        self.version
933    }
934
935    /// Whether the transport is currently up.
936    #[must_use]
937    pub fn is_connected(&self) -> bool {
938        self.connected
939    }
940
941    /// The boot state machine's current state.
942    #[must_use]
943    pub fn boot_state(&self) -> BootState {
944        self.boot
945    }
946
947    /// The heartbeat interval the CSMS asked for, once boot succeeded.
948    #[must_use]
949    pub fn heartbeat_interval(&self) -> Option<Duration> {
950        self.heartbeat_interval
951    }
952
953    /// How many messages are waiting to be sent.
954    ///
955    /// This is what `GetTransactionStatus.messagesInQueue` reports.
956    #[must_use]
957    pub fn queued(&self) -> usize {
958        self.queue.len()
959    }
960
961    /// The durable store.
962    pub fn store(&self) -> &S {
963        &self.store
964    }
965
966    /// Whether one of *our* calls is currently outstanding.
967    #[must_use]
968    pub fn has_outstanding_call(&self) -> bool {
969        self.inflight.is_some()
970    }
971
972    /// How many of the *peer's* calls are waiting for an answer.
973    ///
974    /// More than one means the peer broke the one-outstanding-`CALL` rule and
975    /// [`InboundConcurrency::Serve`] let it.
976    #[must_use]
977    pub fn awaiting_response(&self) -> usize {
978        self.peer_inflight.len()
979    }
980
981    // -- driver interface ---------------------------------------------------
982
983    /// Feeds one event into the state machine at time `now`.
984    ///
985    /// `now` is the driver's monotonic clock, taken on every input rather than only on
986    /// [`Input::Timeout`]: every input can arm a deadline, and one computed from a stale
987    /// clock fires the moment it is armed.
988    pub fn handle(&mut self, now: Instant, input: Input<'_>) {
989        self.advance(now);
990        match input {
991            Input::Connected { version } => self.on_connected(version),
992            Input::Received(text) => self.on_received(text),
993            Input::Disconnected => self.on_disconnected(),
994            Input::Timeout => self.on_timeout(),
995        }
996    }
997
998    /// Moves the clock forward, never backwards: an older instant must not resurrect a
999    /// deadline that has already passed.
1000    fn advance(&mut self, now: Instant) {
1001        if now > self.now {
1002            self.now = now;
1003        }
1004    }
1005
1006    /// The engine's view of the driver's clock.
1007    #[must_use]
1008    pub fn now(&self) -> Instant {
1009        self.now
1010    }
1011
1012    /// Takes the next thing the driver must do.
1013    pub fn poll_output(&mut self) -> Option<Output> {
1014        self.outputs.pop_front()
1015    }
1016
1017    /// Takes everything the driver must do, in order.
1018    pub fn drain(&mut self) -> Vec<Output> {
1019        self.outputs.drain(..).collect()
1020    }
1021
1022    // -- application interface ----------------------------------------------
1023
1024    /// Starts a `CALL` (or a `SEND`, if that is what the action is).
1025    ///
1026    /// The call is accepted immediately and reaches the wire when the one-outstanding rule,
1027    /// the boot gate and the connection allow it. The returned [`CallToken`] appears again
1028    /// in the matching [`CallOutcome`].
1029    pub fn call(
1030        &mut self,
1031        now: Instant,
1032        action: &str,
1033        payload: Box<RawValue>,
1034    ) -> Result<CallToken, EngineError> {
1035        self.call_with(now, action, payload, CallOptions::default())
1036    }
1037
1038    /// Starts a call with per-call overrides.
1039    pub fn call_with(
1040        &mut self,
1041        now: Instant,
1042        action: &str,
1043        payload: Box<RawValue>,
1044        options: CallOptions,
1045    ) -> Result<CallToken, EngineError> {
1046        self.advance(now);
1047        if self.draining.is_some() {
1048            return Err(EngineError::ShuttingDown);
1049        }
1050        let Some(kind) = actions::kind(self.version, action) else {
1051            return Err(EngineError::UnknownAction(action.to_string()));
1052        };
1053        let origin = actions::origin(self.version, action).unwrap_or(Origin::Both);
1054        if !allows(origin, self.config.role.sends()) {
1055            return Err(EngineError::WrongDirection(action.to_string()));
1056        }
1057        if kind == MessageKind::Send && !self.version.has_extended_message_types() {
1058            return Err(EngineError::SendNotSupported(action.to_string()));
1059        }
1060
1061        let transactional = actions::is_transaction_related(self.version, action);
1062        let persist = options.persist.unwrap_or(transactional);
1063        let queue_when_offline = options
1064            .queue_when_offline
1065            .unwrap_or(transactional || self.config.offline.queue_all_messages);
1066
1067        let token = self.mint_token();
1068        if !self.connected && !queue_when_offline {
1069            // Nothing about this message survives an outage, and there is no outage to wait
1070            // out — reporting that now beats letting it sit in a queue it was never meant to
1071            // enter until the *next* disconnection notices it.
1072            self.fail(token, None, action, CallFailure::Disconnected);
1073            return Ok(token);
1074        }
1075        if self.queue.len() >= self.config.offline.max_queued {
1076            self.fail(token, None, action, CallFailure::QueueFull);
1077            return Ok(token);
1078        }
1079
1080        let mut seq = None;
1081        if persist {
1082            let entry = QueuedCall {
1083                action: action.to_string(),
1084                payload: payload.clone(),
1085                kind,
1086                attempts: 0,
1087                transactional,
1088            };
1089            match self.store.push(&entry) {
1090                Ok(value) => seq = Some(value),
1091                Err(error) => {
1092                    self.outputs
1093                        .push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
1094                    self.fail(token, None, action, CallFailure::QueueFull);
1095                    return Ok(token);
1096                }
1097            }
1098        }
1099
1100        // The CSMS records what it asked the station for, so the boot gate can tell a
1101        // solicited follow-up call from an unsolicited one (B02.FR.09).
1102        if self.config.role == Role::Csms {
1103            self.remember_solicited(action, &payload);
1104        }
1105
1106        self.queue.push_back(Pending {
1107            token,
1108            action: action.to_string(),
1109            payload,
1110            kind,
1111            transactional,
1112            attempts: 0,
1113            seq,
1114            not_before: None,
1115            triggered: options.triggered,
1116            queue_when_offline,
1117        });
1118        self.pump();
1119        Ok(token)
1120    }
1121
1122    /// Answers an outstanding request with a `CALLRESULT`.
1123    pub fn respond(
1124        &mut self,
1125        now: Instant,
1126        id: &MessageId,
1127        payload: &RawValue,
1128    ) -> Result<(), EngineError> {
1129        self.advance(now);
1130        self.take_peer_request(id)?;
1131        // The CSMS side learns the boot verdict from the answer it is sending.
1132        if self.config.role == Role::Csms {
1133            self.observe_boot_answer(payload, /* outgoing */ true);
1134        }
1135        let frame = Frame::CallResult {
1136            id: id.clone(),
1137            payload: alloc::borrow::Cow::Borrowed(payload),
1138        };
1139        self.transmit(&frame);
1140        Ok(())
1141    }
1142
1143    /// Answers an outstanding request with a `CALLERROR`.
1144    pub fn respond_error(
1145        &mut self,
1146        now: Instant,
1147        id: &MessageId,
1148        error: CallError,
1149    ) -> Result<(), EngineError> {
1150        self.advance(now);
1151        self.take_peer_request(id)?;
1152        let frame = Frame::CallError {
1153            id: id.clone(),
1154            error: error.into(),
1155        };
1156        self.transmit(&frame);
1157        Ok(())
1158    }
1159
1160    /// Tells the peer that the `CALLRESULT` it sent could not be used (OCPP 2.1
1161    /// `CALLRESULTERROR`).
1162    ///
1163    /// Before 2.1 no such message exists, and the failure can only be logged locally.
1164    pub fn reject_result(
1165        &mut self,
1166        now: Instant,
1167        id: &MessageId,
1168        error: CallError,
1169    ) -> Result<(), EngineError> {
1170        self.advance(now);
1171        if !self.version.has_extended_message_types() {
1172            return Err(EngineError::CallResultErrorNotSupported);
1173        }
1174        let frame = Frame::CallResultError {
1175            id: id.clone(),
1176            error: error.into(),
1177        };
1178        self.transmit(&frame);
1179        Ok(())
1180    }
1181
1182    /// Abandons a call that has not been transmitted yet.
1183    ///
1184    /// Returns `true` if it was still in the queue. A call that is already outstanding
1185    /// cannot be withdrawn — the peer will answer it.
1186    pub fn cancel(&mut self, token: CallToken) -> bool {
1187        let Some(index) = self.queue.iter().position(|entry| entry.token == token) else {
1188            return false;
1189        };
1190        let entry = self.queue.remove(index).expect("index from position");
1191        self.ack_store(entry.seq);
1192        self.outputs.push_back(Output::Outcome(CallOutcome {
1193            token,
1194            id: None,
1195            action: entry.action,
1196            result: Err(CallFailure::Cancelled),
1197        }));
1198        true
1199    }
1200
1201    /// Starts a graceful drain: no new calls are accepted, the outstanding call is allowed
1202    /// to finish and the queue is flushed, then [`Output::Close`] is emitted.
1203    ///
1204    /// If `deadline` passes first, the connection is closed with
1205    /// [`CloseReason::DrainTimedOut`] and the queue is left in the durable store.
1206    pub fn shutdown(&mut self, now: Instant, deadline: Instant) {
1207        self.advance(now);
1208        if self.draining.is_some() {
1209            return;
1210        }
1211        self.draining = Some(deadline);
1212        self.outputs.push_back(Output::SetTimer {
1213            timer: Timer::DrainDeadline,
1214            at: deadline,
1215        });
1216        self.check_drain();
1217    }
1218
1219    // -- inbound -------------------------------------------------------------
1220
1221    fn on_connected(&mut self, version: Version) {
1222        self.version = version;
1223        self.connected = true;
1224        self.peer_inflight.clear();
1225        // The engine survives reconnects (Part 4 §5.4: no repeat `BootNotification`), so an
1226        // already-accepted station has to pick its heartbeat back up here — nothing else
1227        // will re-arm it.
1228        self.arm_heartbeat();
1229        self.pump();
1230    }
1231
1232    fn on_disconnected(&mut self) {
1233        self.connected = false;
1234        self.peer_inflight.clear();
1235        self.outputs
1236            .push_back(Output::ClearTimer(Timer::CallTimeout));
1237        self.outputs.push_back(Output::ClearTimer(Timer::Heartbeat));
1238        self.heartbeat_at = None;
1239
1240        if let Some(inflight) = self.inflight.take() {
1241            self.requeue_or_fail(inflight, CallFailure::Disconnected);
1242        }
1243        // Messages that must not survive the outage are failed now, in order.
1244        let mut kept = VecDeque::with_capacity(self.queue.len());
1245        while let Some(entry) = self.queue.pop_front() {
1246            if entry.queue_when_offline {
1247                kept.push_back(entry);
1248            } else {
1249                self.ack_store(entry.seq);
1250                self.outputs.push_back(Output::Outcome(CallOutcome {
1251                    token: entry.token,
1252                    id: None,
1253                    action: entry.action,
1254                    result: Err(CallFailure::Disconnected),
1255                }));
1256            }
1257        }
1258        self.queue = kept;
1259        self.check_drain();
1260    }
1261
1262    fn on_timeout(&mut self) {
1263        let now = self.now;
1264
1265        if let Some(deadline) = self.inflight.as_ref().map(|f| f.deadline) {
1266            if now >= deadline {
1267                let inflight = self.inflight.take().expect("checked");
1268                self.outputs
1269                    .push_back(Output::ClearTimer(Timer::CallTimeout));
1270                self.requeue_or_fail(inflight, CallFailure::Timeout);
1271            }
1272        }
1273
1274        if let Some(at) = self.heartbeat_at {
1275            if now >= at {
1276                self.heartbeat_at = None;
1277                if self.connected && self.boot.allows_traffic() {
1278                    self.send_heartbeat();
1279                }
1280                // Sending re-arms the idle timer by way of `transmit`; this covers the cases
1281                // where nothing was sent, or the `Heartbeat` had to queue behind a call.
1282                self.arm_heartbeat();
1283            }
1284        }
1285
1286        if let Some(at) = self.boot_retry_at {
1287            if now >= at {
1288                self.boot_retry_at = None;
1289                // B02.FR.04 / FR.08: the station re-sends BootNotification once the interval
1290                // has passed. Only the application can build the payload, so the engine
1291                // reports the transition and re-opens the gate.
1292                self.boot = BootState::Idle;
1293                self.outputs.push_back(Output::BootState(BootState::Idle));
1294            }
1295        }
1296
1297        if let Some(deadline) = self.draining {
1298            if now >= deadline && !self.drain_complete() {
1299                self.outputs
1300                    .push_back(Output::Close(CloseReason::DrainTimedOut));
1301                self.draining = None;
1302                return;
1303            }
1304        }
1305
1306        self.pump();
1307        self.check_drain();
1308    }
1309
1310    fn on_received(&mut self, text: &str) {
1311        // `HeartbeatInterval` is defined as an interval of *inactivity*, so traffic in either
1312        // direction postpones the next `Heartbeat`.
1313        self.arm_heartbeat();
1314        let frame = match Frame::parse(text, self.version) {
1315            Ok(frame) => frame,
1316            Err(error) => {
1317                if self.over_rate() {
1318                    return;
1319                }
1320                let reply = error.reply(self.version);
1321                let reply_id = error.reply_id();
1322                let code = error.error_code();
1323                // One violation per frame: the specific one when the frame got far enough to
1324                // name what was wrong with it, the general one otherwise.
1325                self.outputs.push_back(Output::Violation(match &error {
1326                    FrameError::UnknownMessageType { number } => {
1327                        ProtocolViolation::UnknownMessageType {
1328                            number: number.clone(),
1329                        }
1330                    }
1331                    _ => ProtocolViolation::MalformedFrame { error },
1332                }));
1333                // §4.2.3 — a CALL gets a CALLERROR, a CALLRESULT gets a CALLRESULTERROR, and
1334                // a SEND or a broken error frame gets nothing at all.
1335                let answer = match reply {
1336                    FrameReply::Ignore => return,
1337                    FrameReply::CallError => Frame::CallError {
1338                        id: reply_id,
1339                        error: CallError::new(code, "frame could not be processed").into(),
1340                    },
1341                    FrameReply::CallResultError => Frame::CallResultError {
1342                        id: reply_id,
1343                        error: CallError::new(code, "result could not be processed").into(),
1344                    },
1345                };
1346                self.transmit(&answer);
1347                return;
1348            }
1349        };
1350
1351        // The answer to our own outstanding call is paced by us, so it is never counted.
1352        // Everything else the peer sends is.
1353        let expected = matches!(frame, Frame::CallResult { .. } | Frame::CallError { .. })
1354            && self
1355                .inflight
1356                .as_ref()
1357                .is_some_and(|inflight| &inflight.id == frame.id());
1358        if !expected && self.over_rate() {
1359            // Before every other inbound check: a refused call must cost nothing but this
1360            // answer, and must not occupy an in-flight slot. A SEND is never answered (FR.07);
1361            // anything else is dropped without an answer or a violation.
1362            if let Frame::Call { id, .. } = &frame {
1363                let refusal = Frame::CallError {
1364                    id: id.clone(),
1365                    error: CallError::security(format!(
1366                        "message rate exceeded ({})",
1367                        self.config
1368                            .inbound_rate
1369                            .map_or_else(String::new, |rate| rate.to_string())
1370                    ))
1371                    .into(),
1372                };
1373                self.transmit(&refusal);
1374            }
1375            return;
1376        }
1377
1378        if !frame.id().is_conforming() {
1379            self.outputs.push_back(Output::Violation(
1380                ProtocolViolation::NonConformingMessageId {
1381                    id: frame.id().clone(),
1382                },
1383            ));
1384        }
1385
1386        match frame {
1387            Frame::Call {
1388                id,
1389                action,
1390                payload,
1391            } => {
1392                self.on_call(id, &action, payload.into_owned(), MessageKind::Call);
1393            }
1394            Frame::Send {
1395                id,
1396                action,
1397                payload,
1398            } => {
1399                self.on_call(id, &action, payload.into_owned(), MessageKind::Send);
1400            }
1401            Frame::CallResult { id, payload } => self.on_call_result(&id, payload.into_owned()),
1402            Frame::CallError { id, error } => self.on_call_error(&id, &error),
1403            Frame::CallResultError { id, error } => {
1404                self.outputs.push_back(Output::ResultRejected {
1405                    id,
1406                    error: error.to_call_error(),
1407                });
1408            }
1409        }
1410    }
1411
1412    fn on_call(
1413        &mut self,
1414        id: MessageId,
1415        action: &str,
1416        payload: Box<RawValue>,
1417        received: MessageKind,
1418    ) {
1419        let Some(expected) = actions::kind(self.version, action) else {
1420            self.reject(&id, received, CallError::not_implemented(action));
1421            return;
1422        };
1423        if expected != received {
1424            // N15.FR.01: a SEND-only action must not arrive as a CALL, and a CALL must not
1425            // arrive as a SEND.
1426            self.outputs
1427                .push_back(Output::Violation(ProtocolViolation::WrongMessageKind {
1428                    action: action.to_string(),
1429                    received,
1430                }));
1431            self.reject(
1432                &id,
1433                received,
1434                CallError::new(
1435                    ErrorCode::ProtocolError,
1436                    format!("{action} is a {expected:?} message, not a {received:?} message"),
1437                ),
1438            );
1439            return;
1440        }
1441
1442        let origin = actions::origin(self.version, action).unwrap_or(Origin::Both);
1443        if !allows(origin, self.config.role.receives()) {
1444            self.outputs
1445                .push_back(Output::Violation(ProtocolViolation::WrongDirection {
1446                    action: action.to_string(),
1447                }));
1448            self.reject(&id, received, CallError::not_supported(action));
1449            return;
1450        }
1451
1452        if received == MessageKind::Call {
1453            // §4.2.3 lists "an existing message with the same unique identifier is being
1454            // handled already" as a CALLERROR condition — and answering it as an ordinary
1455            // request would make the two answers indistinguishable to the peer.
1456            if self.peer_inflight.contains(&id) {
1457                self.outputs
1458                    .push_back(Output::Violation(ProtocolViolation::DuplicateMessageId {
1459                        id: id.clone(),
1460                    }));
1461                self.reject(
1462                    &id,
1463                    received,
1464                    CallError::new(
1465                        ErrorCode::RpcFrameworkError,
1466                        "a CALL with this MessageId is already being handled (Part 4 §4.2.3)",
1467                    ),
1468                );
1469                return;
1470            }
1471            if !self.peer_inflight.is_empty() {
1472                self.outputs
1473                    .push_back(Output::Violation(ProtocolViolation::ConcurrentCall {
1474                        id: id.clone(),
1475                    }));
1476                // Serving extra calls is a kindness to non-conforming peers, not an
1477                // invitation to hold unbounded state on their behalf.
1478                let over_limit = self.peer_inflight.len() >= self.config.max_peer_requests;
1479                if over_limit {
1480                    self.outputs.push_back(Output::Violation(
1481                        ProtocolViolation::TooManyPeerRequests { id: id.clone() },
1482                    ));
1483                }
1484                if over_limit || self.config.inbound_concurrency == InboundConcurrency::Reject {
1485                    self.reject(
1486                        &id,
1487                        received,
1488                        CallError::new(
1489                            ErrorCode::ProtocolError,
1490                            "a CALL is already outstanding in this direction (Part 4 §4.1.1)",
1491                        ),
1492                    );
1493                    return;
1494                }
1495            }
1496        }
1497
1498        // B01.FR.10 / B02.FR.09 — a CSMS answers an unsolicited call with SecurityError once
1499        // it has told the station it is *not* accepted. The precondition is "the Charging
1500        // Station has received a BootNotificationResponse with a status other than
1501        // Accepted", so it does **not** apply before any BootNotification has been answered:
1502        // Part 4 §5.4 explicitly lets a station reconnect without repeating one.
1503        // BootNotification itself is always allowed, and so is anything the CSMS asked for.
1504        if self.config.role == Role::Csms
1505            && self.config.enforce_boot_gate
1506            && self.boot.blocks_unsolicited_traffic()
1507            && action != "BootNotification"
1508            && !self.solicited.contains(action)
1509        {
1510            self.reject(
1511                &id,
1512                received,
1513                CallError::security(format!(
1514                    "{action} is not allowed while the charging station is {:?} (B02.FR.09)",
1515                    self.boot
1516                )),
1517            );
1518            return;
1519        }
1520
1521        if self.config.role == Role::Csms && action == "BootNotification" {
1522            self.boot = BootState::Idle;
1523        }
1524
1525        if received == MessageKind::Call {
1526            self.peer_inflight.insert(id.clone());
1527        }
1528        self.outputs.push_back(Output::Request(IncomingRequest {
1529            id,
1530            action: action.to_string(),
1531            payload,
1532            kind: received,
1533        }));
1534    }
1535
1536    fn on_call_result(&mut self, id: &MessageId, payload: Box<RawValue>) {
1537        let Some(inflight) = self.take_inflight(id) else {
1538            self.outputs
1539                .push_back(Output::Violation(ProtocolViolation::UnexpectedResponse {
1540                    id: id.clone(),
1541                }));
1542            return;
1543        };
1544        self.ack_store(inflight.seq);
1545        self.outputs
1546            .push_back(Output::ClearTimer(Timer::CallTimeout));
1547
1548        match inflight.action.as_str() {
1549            "BootNotification" if self.config.role == Role::ChargingStation => {
1550                self.observe_boot_answer(&payload, false);
1551            }
1552            "Heartbeat" => {
1553                if let Ok(answer) = serde_json::from_str::<HeartbeatAnswer>(payload.get()) {
1554                    self.outputs.push_back(Output::ClockSample(ClockSample {
1555                        csms_time: answer.current_time,
1556                        at: self.now,
1557                    }));
1558                }
1559            }
1560            _ => {}
1561        }
1562
1563        self.outputs.push_back(Output::Outcome(CallOutcome {
1564            token: inflight.token,
1565            id: Some(inflight.id),
1566            action: inflight.action,
1567            result: Ok(Answer::Result(payload)),
1568        }));
1569        self.pump();
1570        self.check_drain();
1571    }
1572
1573    fn on_call_error(&mut self, id: &MessageId, error: &CallErrorRef<'_>) {
1574        let Some(inflight) = self.take_inflight(id) else {
1575            self.outputs
1576                .push_back(Output::Violation(ProtocolViolation::UnexpectedResponse {
1577                    id: id.clone(),
1578                }));
1579            return;
1580        };
1581        // A CALLERROR is a definitive answer, so it is not retried — unlike a timeout or a
1582        // dropped connection, retrying it would just produce the same error.
1583        self.ack_store(inflight.seq);
1584        self.outputs
1585            .push_back(Output::ClearTimer(Timer::CallTimeout));
1586        self.outputs.push_back(Output::Outcome(CallOutcome {
1587            token: inflight.token,
1588            id: Some(inflight.id),
1589            action: inflight.action,
1590            result: Err(CallFailure::Rejected(error.to_call_error())),
1591        }));
1592        self.pump();
1593        self.check_drain();
1594    }
1595
1596    // -- helpers -------------------------------------------------------------
1597
1598    fn mint_token(&mut self) -> CallToken {
1599        let token = CallToken(self.next_token);
1600        self.next_token += 1;
1601        token
1602    }
1603
1604    fn take_inflight(&mut self, id: &MessageId) -> Option<InFlight> {
1605        match self.inflight.as_ref() {
1606            Some(inflight) if &inflight.id == id => self.inflight.take(),
1607            _ => None,
1608        }
1609    }
1610
1611    fn take_peer_request(&mut self, id: &MessageId) -> Result<(), EngineError> {
1612        if self.peer_inflight.remove(id) {
1613            return Ok(());
1614        }
1615        Err(EngineError::NoSuchRequest(id.clone()))
1616    }
1617
1618    /// Counts one unprompted message against the inbound rate. `true` when it is refused.
1619    fn over_rate(&mut self) -> bool {
1620        let now = self.now;
1621        match self.rate.as_mut().map(|rate| rate.admit(now)) {
1622            Some(rate::Admission::Refused { new_episode }) => {
1623                if new_episode {
1624                    self.outputs.push_back(Output::RateLimited);
1625                }
1626                true
1627            }
1628            Some(rate::Admission::Admitted) | None => false,
1629        }
1630    }
1631
1632    fn reject(&mut self, id: &MessageId, kind: MessageKind, error: CallError) {
1633        // FR.07 — a SEND is never answered, not even to report that it was unusable.
1634        if kind == MessageKind::Send {
1635            return;
1636        }
1637        let frame = Frame::CallError {
1638            id: id.clone(),
1639            error: error.into(),
1640        };
1641        self.transmit(&frame);
1642    }
1643
1644    fn transmit(&mut self, frame: &Frame<'_>) {
1645        match frame.to_json(self.version) {
1646            Ok(text) => {
1647                self.outputs.push_back(Output::Transmit(text));
1648                self.arm_heartbeat();
1649            }
1650            Err(error) => {
1651                self.outputs
1652                    .push_back(Output::Violation(ProtocolViolation::StoreFailure {
1653                        error: StoreError::new(format!("frame could not be serialized: {error}")),
1654                    }));
1655            }
1656        }
1657    }
1658
1659    fn ack_store(&mut self, seq: Option<Seq>) {
1660        if let Some(seq) = seq {
1661            if let Err(error) = self.store.ack(seq) {
1662                self.outputs
1663                    .push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
1664            }
1665        }
1666    }
1667
1668    fn fail(&mut self, token: CallToken, id: Option<MessageId>, action: &str, why: CallFailure) {
1669        self.outputs.push_back(Output::Outcome(CallOutcome {
1670            token,
1671            id,
1672            action: action.to_string(),
1673            result: Err(why),
1674        }));
1675    }
1676
1677    /// Decides what happens to a call that lost its answer: a transaction message goes back
1678    /// on the queue for its next scheduled attempt; anything else fails now.
1679    ///
1680    /// Only transaction messages are replayed, and deliberately so. They are the ones the
1681    /// specification makes idempotent — a CSMS deduplicates `TransactionEvent` by
1682    /// `transactionId` and `seqNo` — so a second copy is harmless. Re-sending an
1683    /// `Authorize` or a `SetVariables` whose answer merely went missing is not obviously
1684    /// safe, and the caller, which knows what the message meant, gets to decide.
1685    fn requeue_or_fail(&mut self, inflight: InFlight, why: CallFailure) {
1686        let attempts = inflight.attempts;
1687        if inflight.transactional && self.config.retry.may_retry(attempts) {
1688            let delay = self.config.retry.delay_after(attempts);
1689            let not_before = self.now.saturating_add(delay);
1690            if let Some(seq) = inflight.seq {
1691                if let Err(error) = self.store.set_attempts(seq, attempts) {
1692                    self.outputs
1693                        .push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
1694                }
1695            }
1696            self.queue.push_front(Pending {
1697                token: inflight.token,
1698                action: inflight.action,
1699                payload: inflight.payload,
1700                kind: MessageKind::Call,
1701                transactional: true,
1702                attempts,
1703                seq: inflight.seq,
1704                not_before: Some(not_before),
1705                triggered: inflight.triggered,
1706                queue_when_offline: inflight.queue_when_offline,
1707            });
1708            self.outputs.push_back(Output::SetTimer {
1709                timer: Timer::TransactionRetry,
1710                at: not_before,
1711            });
1712            return;
1713        }
1714        let why = if inflight.transactional {
1715            CallFailure::RetriesExhausted
1716        } else {
1717            why
1718        };
1719        self.ack_store(inflight.seq);
1720        self.outputs.push_back(Output::Outcome(CallOutcome {
1721            token: inflight.token,
1722            id: Some(inflight.id),
1723            action: inflight.action,
1724            result: Err(why),
1725        }));
1726    }
1727
1728    /// Whether the entry at `index` may go out right now.
1729    ///
1730    /// Two rules decide it. B02.FR.02 gates everything before the CSMS accepts the station.
1731    /// And 1.6 §3.7 — carried into 2.x — says transaction-related messages are delivered *in
1732    /// chronological order*: "the delivery of new transaction-related messages SHALL wait
1733    /// until the queue has been emptied". So a transaction message may only go out if it is
1734    /// the oldest one queued, even when a later one is due and it is still waiting out its
1735    /// retry interval. Messages that are *not* transaction-related are explicitly allowed to
1736    /// overtake the queue, so that an `Authorize` is not held up behind a stuck meter value.
1737    fn eligible(&self, index: usize) -> bool {
1738        let entry = &self.queue[index];
1739        if entry.not_before.is_some_and(|at| self.now < at) {
1740            return false;
1741        }
1742        if entry.transactional {
1743            let oldest = self
1744                .queue
1745                .iter()
1746                .position(|other| other.transactional)
1747                .expect("this entry is transactional");
1748            if oldest != index {
1749                return false;
1750            }
1751        }
1752        if !self.config.enforce_boot_gate || self.config.role != Role::ChargingStation {
1753            return true;
1754        }
1755        // B02.FR.02 — before the CSMS accepts the station, only BootNotification and
1756        // messages the CSMS explicitly asked for may be sent.
1757        self.boot.allows_traffic() || entry.action == "BootNotification" || entry.triggered
1758    }
1759
1760    fn pump(&mut self) {
1761        if !self.connected {
1762            return;
1763        }
1764
1765        // Part 4 §4.2.4 — a SEND is exempt from the one-outstanding-CALL rule, so it goes
1766        // out whether or not a CALL is in flight, and completes as soon as it is written.
1767        while let Some(index) = (0..self.queue.len())
1768            .find(|index| self.queue[*index].kind == MessageKind::Send && self.eligible(*index))
1769        {
1770            let entry = self.queue.remove(index).expect("index from position");
1771            let id = self.ids.next_id();
1772            let frame = Frame::Send {
1773                id: id.clone(),
1774                action: (&entry.action).into(),
1775                payload: alloc::borrow::Cow::Borrowed(entry.payload.as_ref()),
1776            };
1777            self.transmit(&frame);
1778            self.ack_store(entry.seq);
1779            self.outputs.push_back(Output::Outcome(CallOutcome {
1780                token: entry.token,
1781                id: Some(id),
1782                action: entry.action,
1783                result: Ok(Answer::Sent),
1784            }));
1785        }
1786
1787        while self.inflight.is_none() {
1788            let Some(index) = (0..self.queue.len()).find(|index| {
1789                self.queue[*index].kind == MessageKind::Call && self.eligible(*index)
1790            }) else {
1791                break;
1792            };
1793            let entry = self.queue.remove(index).expect("index from position");
1794            let id = self.ids.next_id();
1795            let frame = Frame::Call {
1796                id: id.clone(),
1797                action: (&entry.action).into(),
1798                payload: alloc::borrow::Cow::Borrowed(entry.payload.as_ref()),
1799            };
1800            self.transmit(&frame);
1801            let deadline = self.now.saturating_add(self.config.call_timeout);
1802            self.outputs.push_back(Output::SetTimer {
1803                timer: Timer::CallTimeout,
1804                at: deadline,
1805            });
1806            self.inflight = Some(InFlight {
1807                id,
1808                token: entry.token,
1809                action: entry.action,
1810                transactional: entry.transactional,
1811                attempts: entry.attempts + 1,
1812                seq: entry.seq,
1813                payload: entry.payload,
1814                triggered: entry.triggered,
1815                queue_when_offline: entry.queue_when_offline,
1816                deadline,
1817            });
1818        }
1819    }
1820
1821    fn send_heartbeat(&mut self) {
1822        // `HeartbeatRequest` is an empty object in 1.6 and 2.x alike.
1823        let now = self.now;
1824        let _ = self.call_with(
1825            now,
1826            "Heartbeat",
1827            empty_payload(),
1828            CallOptions::default().queue_when_offline(false),
1829        );
1830    }
1831
1832    /// (Re-)arms the inactivity timer that triggers the next `Heartbeat`.
1833    ///
1834    /// `OCPPCommCtrlr.HeartbeatInterval` is the interval of inactivity after which a station
1835    /// sends `Heartbeat`, so this is called for every frame in either direction — not once
1836    /// per period. A `Heartbeat` that times out or is answered with a `CALLERROR` therefore
1837    /// cannot stop the sequence, which is what a fixed schedule anchored on the response
1838    /// would do.
1839    fn arm_heartbeat(&mut self) {
1840        if self.config.heartbeat != HeartbeatPolicy::Automatic
1841            || self.config.role != Role::ChargingStation
1842        {
1843            return;
1844        }
1845        let Some(interval) = self.heartbeat_interval.filter(|d| !d.is_zero()) else {
1846            return;
1847        };
1848        let at = self.now.saturating_add(interval);
1849        if self.heartbeat_at == Some(at) {
1850            return;
1851        }
1852        self.heartbeat_at = Some(at);
1853        self.outputs.push_back(Output::SetTimer {
1854            timer: Timer::Heartbeat,
1855            at,
1856        });
1857    }
1858
1859    /// Reads `status`, `interval` and `currentTime` out of a `BootNotificationResponse`.
1860    fn observe_boot_answer(&mut self, payload: &RawValue, outgoing: bool) {
1861        let Ok(answer) = serde_json::from_str::<BootAnswer<'_>>(payload.get()) else {
1862            return;
1863        };
1864        let state = match answer.status {
1865            "Accepted" => BootState::Accepted,
1866            "Pending" => BootState::Pending,
1867            "Rejected" => BootState::Rejected,
1868            _ => return,
1869        };
1870        self.boot = state;
1871        self.outputs.push_back(Output::BootState(state));
1872
1873        if let Some(time) = answer.current_time {
1874            if !outgoing {
1875                self.outputs.push_back(Output::ClockSample(ClockSample {
1876                    csms_time: time,
1877                    at: self.now,
1878                }));
1879            }
1880        }
1881
1882        let interval = answer.interval.map(Duration::from_secs);
1883        match state {
1884            BootState::Accepted => {
1885                self.heartbeat_interval = interval.filter(|d| !d.is_zero());
1886                if !outgoing {
1887                    self.arm_heartbeat();
1888                    self.pump();
1889                }
1890            }
1891            BootState::Pending | BootState::Rejected if !outgoing => {
1892                // B02.FR.04 / FR.07 / FR.08: wait `interval` before retrying, or a
1893                // locally chosen back-off when the CSMS said 0.
1894                let wait = interval
1895                    .filter(|d| !d.is_zero())
1896                    .unwrap_or(self.config.boot_retry_fallback);
1897                let at = self.now.saturating_add(wait);
1898                self.boot_retry_at = Some(at);
1899                self.outputs.push_back(Output::SetTimer {
1900                    timer: Timer::BootRetry,
1901                    at,
1902                });
1903            }
1904            _ => {}
1905        }
1906    }
1907
1908    /// Remembers the follow-up calls a CSMS request licenses the station to make.
1909    fn remember_solicited(&mut self, action: &str, payload: &RawValue) {
1910        if action == "TriggerMessage" || action == "ExtendedTriggerMessage" {
1911            if let Ok(trigger) = serde_json::from_str::<TriggerRequest<'_>>(payload.get()) {
1912                if let Some(requested) = trigger.requested_message {
1913                    self.solicited.insert(requested.to_string());
1914                    // 1.6 and 2.x both name the message, not the action, so a couple of
1915                    // aliases are needed.
1916                    if requested == "SignChargePointCertificate" {
1917                        self.solicited.insert("SignCertificate".to_string());
1918                    }
1919                }
1920            }
1921        }
1922        for follow_up in actions::solicited_by(self.version, action) {
1923            self.solicited.insert((*follow_up).to_string());
1924        }
1925    }
1926
1927    fn drain_complete(&self) -> bool {
1928        self.inflight.is_none() && self.queue.is_empty()
1929    }
1930
1931    fn check_drain(&mut self) {
1932        if self.draining.is_some() && self.drain_complete() {
1933            self.draining = None;
1934            self.outputs
1935                .push_back(Output::ClearTimer(Timer::DrainDeadline));
1936            self.outputs.push_back(Output::Close(CloseReason::Drained));
1937        }
1938    }
1939}
1940
1941/// The best [`IdGenerator`] the build offers.
1942///
1943/// Random ids when an entropy source is available, because Part 4 §4.1.4 requires ids to be
1944/// unique across *every* connection under one identity, not just within one. Without one,
1945/// a counter — which the caller must then prefix per boot; see
1946/// [`CounterIds`](crate::types::CounterIds).
1947fn default_ids() -> Box<dyn IdGenerator + Send> {
1948    #[cfg(feature = "getrandom")]
1949    {
1950        Box::new(crate::types::RandomIds::new())
1951    }
1952    #[cfg(not(feature = "getrandom"))]
1953    {
1954        Box::new(crate::types::CounterIds::default())
1955    }
1956}
1957
1958fn allows(origin: Origin, side: Origin) -> bool {
1959    match side {
1960        Origin::ChargingStation => origin.from_charging_station(),
1961        Origin::Csms => origin.from_csms(),
1962        Origin::Both => true,
1963    }
1964}
1965
1966fn empty_payload() -> Box<RawValue> {
1967    RawValue::from_string("{}".to_string()).expect("`{}` is valid JSON")
1968}