Rust
Making invalid OCPP messages unrepresentable in Rust
Lessons from implementing OCPP 1.6, 2.0.1 and 2.1 in Rust: parsing frames with slice patterns, validating constrained strings with Serde, and handling version-specific error codes.
By Kevin Vavelin, Founder, CodeticsPublished 9 min read
- Rust
- OCPP
- Serde
- Protocols
- Electric mobility
The Open Charge Point Protocol (OCPP) is how charging stations talk to the systems that supervise them. A station opens a WebSocket connection to its Charging Station Management System (CSMS), and both sides exchange JSON messages: boot notifications, status changes, meter values, remote start and stop commands, firmware updates.
We implemented OCPP-J 1.6, 2.0.1 and 2.1 in Rust, without an OCPP library or code generation, as part of our Codetics OCPP project. This article shares three techniques that made the implementation easier to trust.
Parse the frame before the payload
An OCPP-J message is a JSON array. The first element is the message type: 2 for a CALL, 3 for a CALLRESULT, 4 for a CALLERROR (OCPP 2.1 also adds CALLRESULTERROR and SEND). The other elements depend on that type.
- [2, "19223201", "BootNotification", {…}]
- CALL · id · action · payload
Rust's slice patterns let us express each shape directly. The compiler checks that every case is handled, and a frame that does not match any shape becomes an explicit error instead of a crash further down.
use serde_json::Value;
/// An OCPP-J frame is a JSON array whose first element is the message type.
#[derive(Debug)]
pub enum Frame {
Call { id: String, action: String, payload: Value },
CallResult { id: String, payload: Value },
CallError { id: String, code: String, description: String, details: Value },
}
#[derive(Debug)]
pub enum FrameError {
NotJson,
Malformed,
}
impl Frame {
pub fn parse(text: &str) -> Result<Frame, FrameError> {
let items: Vec<Value> = serde_json::from_str(text).map_err(|_| FrameError::NotJson)?;
let kind = items.first().and_then(Value::as_u64);
match (kind, items.as_slice()) {
(Some(2), [_, Value::String(id), Value::String(action), payload]) => Ok(Frame::Call {
id: id.clone(),
action: action.clone(),
payload: payload.clone(),
}),
(Some(3), [_, Value::String(id), payload]) => Ok(Frame::CallResult {
id: id.clone(),
payload: payload.clone(),
}),
(Some(4), [_, Value::String(id), Value::String(code), Value::String(description), details]) => {
Ok(Frame::CallError {
id: id.clone(),
code: code.clone(),
description: description.clone(),
details: details.clone(),
})
}
_ => Err(FrameError::Malformed),
}
}
}Keeping the payload as a raw JSON value at this stage matters: the message id is needed to answer with a CALLERROR even when the payload turns out to be invalid.
Encode the specification's constraints in types
The OCPP specifications constrain many fields. In OCPP 1.6, chargePointVendor is a CiString20Type: a case-insensitive string of at most 20 printable ASCII characters. A plain String would accept anything, and every handler would have to remember to check.
Instead, we validate once, while deserializing. With Serde's try_from attribute, a value that breaks the constraint never becomes a Rust value at all.
use serde::Deserialize;
/// OCPP "CiString": printable ASCII, bounded length, compared case-insensitively.
#[derive(Debug, Clone, Deserialize)]
#[serde(try_from = "String")]
pub struct CiString<const N: usize>(String);
impl<const N: usize> TryFrom<String> for CiString<N> {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
if !value.chars().all(|c| c.is_ascii() && !c.is_ascii_control()) {
return Err("must be printable ASCII".into());
}
if value.len() > N {
return Err(format!("must be at most {N} characters"));
}
Ok(Self(value))
}
}
/// OCPP 1.6 BootNotification.req
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BootNotificationRequest {
pub charge_point_vendor: CiString<20>,
pub charge_point_model: CiString<20>,
pub charge_point_serial_number: Option<CiString<25>>,
pub firmware_version: Option<CiString<50>>,
}Handlers then receive a BootNotificationRequest that is valid by construction. Optional fields are Option, so the compiler forces every handler to consider their absence. This is what "making invalid states unrepresentable" means in practice: the checks still exist, but they live in one place, and the type system carries the proof everywhere else.
Treat versions as separate languages
It is tempting to share message types across OCPP versions, since many actions have the same name. In practice the payloads differ, and so do the details. One well-known example is the CALLERROR code for a malformed payload:
/// The same failure is spelled differently depending on the protocol version.
pub enum Version { V16, V201, V21 }
pub fn format_violation(version: Version) -> &'static str {
match version {
Version::V16 => "FormationViolation",
Version::V201 | Version::V21 => "FormatViolation",
}
}OCPP 1.6 spells it FormationViolation; later versions use FormatViolation. Similar differences exist for other codes. We give each version its own crate and its own handler module, and share only what is truly version-neutral: frame parsing, timestamps, identifiers and validation helpers.
| Component | Shared across versions? |
|---|---|
| Frame parsing, message ids, RFC 3339 timestamps | Yes |
| WebSocket transport and compression | Yes |
| Message payload types | No, one crate per version |
| Error code spellings | No, resolved per version |
| Business handlers | No, one module per version |
Concurrency follows the protocol
The OCPP-J specification states that a party should not send a new CALL until the previous one has been answered or has timed out. That rule maps naturally to Rust's async model: each connection runs as its own Tokio task, holds at most one outstanding outgoing call, and waits for the matching response through a one-shot channel. Thousands of stations become thousands of lightweight tasks, and ownership rules prevent two tasks from writing to the same socket by accident.
What this buys you
- Fewer runtime surprises. Invalid input is rejected at the boundary with a precise, protocol-compliant error.
- Safer changes. Adding a field or a message variant makes the compiler point to every place that must handle it.
- Clear version boundaries. A fix for OCPP 2.0.1 cannot accidentally change 1.6 behaviour.
None of this is specific to charging stations. Any service that implements a protocol (payment messages, industrial telemetry, device commands) benefits from validating at the edge and carrying guarantees in types. If you are building such a system, our Rust backend and connected mobility pages describe how we can help.