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