# ocpp-kit
[](https://crates.io/crates/ocpp-kit)
[](https://docs.rs/ocpp-kit)
[](https://github.com/hupe1980/ocpp-kit/actions/workflows/ci.yml)
[](#license)
An [Open Charge Point Protocol](https://openchargealliance.org/) toolkit for Rust β
**OCPP 1.6J, 2.0.1 and 2.1** over JSON/WebSocket, for charging stations, CSMS backends and
local controllers.
π **[Documentation](https://hupe1980.github.io/ocpp-kit/docs/)** Β·
[API reference](https://docs.rs/ocpp-kit)
```console
$ cargo add ocpp-kit --features tokio,rustls
```
## Five layers
| **L0** | `v1_6` Β· `v2_0_1` Β· `v2_1` | Typed, validated payloads for all **39 / 64 / 91** actions, generated from the official OCA JSON schemas | β
`alloc` |
| **L1** | `rpc` | OCPP-J framing: `CALL`, `CALLRESULT`, `CALLERROR`, `CALLRESULTERROR`, `SEND`, with version-exact error codes, plus JWS signed messages | β
`alloc` |
| **L2** | `engine` | A **sans-I/O** protocol engine: correlation, the one-outstanding-`CALL` rule, timeouts, transaction retries, the offline queue, the boot state machine | β
`alloc` |
| **L3** | `transport` | Tokio + `rustls`, with its own RFC 6455 WebSocket and RFC 7692 compression: charging station, CSMS and local controller; security profiles 0 (1.6 only) to 3, profile 2 and 3 on one listener; per-station message rate and idle timeout; network failover | β |
| **L4** | `station` Β· `csms` | Opt-in blocks: device model, 1.6 configuration keys, transaction rules, local authorization, an idempotent CSMS ledger, version-agnostic events with phase-aware telemetry | partial |
| β | `smart_charging` | Block K for both sides: the composite schedule, a quarter-hour plan into a valid `TxProfile` within the station's limits, `ChargingProfile` across the wire for every version, 2.1 bidirectional charging (V2X operation modes, dynamic setpoints), what the EV needs on 2.0.1 and 2.1, and the 2.1 DER controls a station reports | β
`alloc` |
| β | `standard` | The catalogues that live outside the schemas: security events with their criticality, 74 standardized components, 458 variables, reason codes | β
`alloc` |
| β | `metering` | Signed meter values: where each version hides the record a customer may be billed for, and how to read its public-key envelope | β
`alloc` |
With default features there is no async runtime, no TLS and no domain logic in your binary β
just the types, the framing and the engine.
## A charging station
```rust
use ocpp_kit::transport::{BasicAuthPassword, ClientTls, Handler, SecurityProfile, Station};
use ocpp_kit::{Version, v2_1};
async fn boot(handler: impl Handler) -> Result<(), Box<dyn std::error::Error>> {
let handle = Station::builder()
.identity("CS-0001")?
.url("wss://csms.example.com/ocpp")
// Part 4 Β§3.2 recommends that a 2.1 station also offer 2.0.1.
.versions([Version::V2_1, Version::V2_0_1])
.security_profile(SecurityProfile::TlsBasicAuth)
.password(BasicAuthPassword::utf8("a-sixteen-plus-character-secret")?)
.tls(ClientTls::with_webpki_roots()?)
.handler(handler)
.build()?
.spawn()?;
let boot = handle
.call(v2_1::BootNotificationRequest::new(
v2_1::ChargingStation::new("Model-1", "ACME"),
v2_1::BootReason::PowerUp,
))
.await?;
println!("{:?}, heartbeat every {}s", boot.status, boot.interval);
Ok(())
}
```
The offline queue, the reconnect back-off, the heartbeat and the boot gate are all handled
underneath: anything you send before the CSMS accepts the station is queued and released the
moment it does, and a connection the network has silently dropped is detected by an unanswered
WebSocket ping instead of waiting out the operating system's TCP timeout.
Add `.store(FileStore::open("/var/lib/ocpp/queue.jsonl")?)` and the queue survives a power cut,
which E04/E08/E12 require of a station.
Run the pair for yourself:
```console
$ cargo run --features full --example minimal_csms
$ cargo run --features full --example minimal_station
```
## Why another OCPP crate
**Error codes are exact.** OCPP does not have one "bad payload" error; it has five, and
answering with the wrong one is a conformance failure that most implementations make. A
missing member is an `OccurrenceConstraintViolation`, a string where an integer belongs is a
`TypeConstraintViolation`, an over-long string is a `PropertyConstraintViolation`, a
non-object payload is a `FormatViolation` β spelled `FormationViolation` when you are talking
1.6 β and a frame that is not a valid RPC request at all is an `RpcFrameworkError`, which
1.6 does not have and therefore degrades to `GenericError`.
```console
$ echo '{"reason":"PowerUp","chargingStation":{"model":"a-model-name-that-is-far-too-long","vendorName":"ACME"}}' \
| ocpp-cli validate --action BootNotification
error: /chargingStation/model: maxLength 20 exceeded (got 32 characters)
OCPP error code: PropertyConstraintViolation
path: /chargingStation/model
```
**The protocol logic has no I/O.** The engine is a pure state machine β feed it events with the
current instant, drain effects. Every timing rule in OCPP is therefore testable in microseconds
rather than minutes, and the same code runs on Tokio, in an `embassy` firmware loop and in
WebAssembly. The `thumbv7em-none-eabihf` build of L0βL4 is checked in CI.
```rust
# use std::time::Duration;
# use ocpp_kit::Version;
# use ocpp_kit::engine::{EngineConfig, Role};
# use ocpp_kit::testkit::Sim;
# fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut sim = Sim::new(EngineConfig::new(Role::ChargingStation, Version::V2_1));
sim.connect(Version::V2_1);
sim.call("BootNotification", r#"{"reason":"PowerUp"}"#)?;
sim.advance(Duration::from_secs(31)); // the message timeout, instantly
assert_eq!(sim.failures().len(), 1);
# Ok(()) }
```
Time is a parameter of *every* entry point, not just the timer one β a deadline armed against
a clock that has not moved since the last timer fired expires the moment it is armed.
**Both sides, and the middle.** Charging Station, CSMS and the Part 4 chapter 6 Local
Controller are built from the same engine. The local controller opens one upstream connection
per attached station under the station's own identity, propagates closes in both directions,
and relays the OCPP-J text unchanged so signed messages survive.
**The edge a CSMS shows the internet.** Authentication is `async` and answers 401 or 404; the
Basic user must *be* the URL identity (A00.FR.204/207). `message_rate` refuses a flooding station
before your handler, `idle_timeout` frees a peer that answers pings but never speaks OCPP, and one
listener can serve profiles 2 and 3. Every session ends with a `DisconnectReason` you can match on.
**Controlling a wallbox, not just talking to it.** `per_phase(CURRENT_IMPORT)` reads a 1.6 and a
2.1 station the same way. `ChargingPlan::to_profile` turns quarter-hour ceilings into one
`TxProfile` within the station's limits that never exceeds the plan, and `smart_charging::v2x` does
the same for 2.1 setpoints β discharge is a magnitude, so there is no sign to get wrong.
`EvNeeds` reads what the vehicle asks for from 2.0.1 and 2.1 alike, and `smart_charging::der`
answers the question a V2H planner has about a station's grid-code controls: which of the ones in
effect can lower or stop the discharge it is counting on.
**The value that pays for the electricity.** Under German calibration law a customer may only
be billed for a value they can check, which is the record the *meter* signed β not the
protocol's own number, and often not even the same quantity: in the OCA's own example message
a 1.6 `meterStop` is the meter's **lifetime** register while the signed record beside it
reports the session. `ocpp_kit::metering` carries that record verbatim in both directions, and
knows both of its hiding places: 1.6, which has no `signedMeterValue` field, puts the whole
2.x object inside the `value` **string** of a `SignedData` sample, and `publicKey` is an
`oca:` envelope in the specification but plain Base64-over-hex in the same document's own
example. Both shapes are in the field; both are read, and the result says which arrived. See
[signed meter values](https://hupe1980.github.io/ocpp-kit/docs/metering/).
**Nothing that decides money fails silently.** A station that *claims* to send signed meter
data and sends something unparseable looks, through a version-neutral view, exactly like one
sending none β until a month of sessions turns out to be unbillable. Every such drop raises an
`Observed::warnings` entry naming what arrived. The funnel also carries what a CDR needs and a
meter reading cannot supply: the `charging_state` β a register at zero is a taper if the
station says `Charging` and an occupancy fee if it says `SuspendedEV` β and the EVSE or
connector the session is at.
**Numbers are exact, not `f64`.** Every OCPP `number` β a meter register, a charging limit, a
2.1 tariff price β is a `types::Decimal`: a mantissa and a decimal scale. A meter reporting
`2935.600` kWh is claiming three decimals of resolution, and it goes back out as `2935.600`;
a session's energy, which OCPP *defines* as a difference of two registers, is that difference
exactly rather than `10.000000000000002`; and unit conversion moves the decimal point instead
of multiplying by `1000.0`. `cargo xtask no-floats` fails the build if an `f32` or `f64`
reaches any public signature, and CI runs it. Exact is still not billable: `Record::energy()`
returns a `RegisterDelta` whose number is spelled `unverified_wh()` and which carries the
signed meter records a calibration-law billing chain settles on.
**The types are checked against the schemas.** Every action's request and response is
round-tripped through pseudo-random schema-valid payloads in CI, and the result is validated
back against the official schema β 9 000+ round trips per run. The types cannot quietly drop
a member, widen a constraint, or miss an enumeration value.
**Every certification-profile action is driven, not just typed.** Schema round trips prove the
types match the schemas; they say nothing about whether an action dispatches. So every action
OCPP 2.0.1 Part 5 names β all 76, across all eight profiles β is exercised as a real exchange
over a socket, asserting the typed response on both sides. `cargo xtask coverage --profile all`
reports it, and counts an action only when a test names its typed payload or puts it on the
wire.
**Compression, because 2.1 requires it.** Part 4 Β§3.4 Table 2 makes RFC 7692
`permessage-deflate` **required** for a CSMS and a Local Controller. No general-purpose Rust
WebSocket crate implements it β and RFC 6455 obliges a crate that does not to *reject* the
`RSV1` bit a compressed message sets. So the frame layer is in this crate: a focused RFC 6455
implementation with compression, checked against `tokio-tungstenite` in both directions,
fuzzed, and verified compressed on the wire. Framing costs ~110 ns per message, and a repeated
`TransactionEvent` frame goes out at **5 % of its size** once the DEFLATE window has warmed up.
See [the WebSocket layer](https://hupe1980.github.io/ocpp-kit/docs/websocket/).
**Message-level signatures, and a policy you cannot forget.** With a Local Controller in the
path, TLS proves you are talking to the *controller*, not the CSMS. Part 4 chapter 7's JWS
signed messages β `<Action>-Signed`, the flattened JWS serialization, the `OCPPAction` /
`OCPPMessageTypedId` / `x5t#S256` headers β are implemented, with `Signer` and `Verifier` as
traits so a key in a secure element never has to reach RAM.
`verify_frame` takes a `SignaturePolicy` and has no default: "verify it if it is signed" is not
a check, because an intermediary can delete three JSON members and a name suffix and the
receiver cannot tell.
**Unsafe options are never the default.** A00.FR.207 requires the CSMS to validate that the
Basic username is the identity from the URL, so `Csms` answers 401 on a mismatch before your
`Authenticator` sees it β left to the application it is a trap, since HTTP Basic hands you a
username while the session is filed under the identity from the path. And a CSMS with no
authenticator does not build: accepting everyone is spelled `authenticate(AcceptEveryStation)`,
because a server that authenticates nobody looks exactly like one that authenticates everybody
successfully.
**The vocabulary, not just the messages.** The schemas define the messages; the appendix
defines what they talk about. `ocpp_kit::standard` carries the 21 security events *with their
criticality* (and 1.6's own 21, from the Security Whitepaper), the 74 standardized components and their 458 variables *with their data types
and units*, and the standardized reason codes β extracted from the specification, asserted by
tests, and wired into the device model so a station gets them right without transcribing a PDF.
**Version differences are modelled, not averaged.** They are real, and they are in the code
with the citation next to them:
| Message types | 2, 3, 4 | 2, 3, 4 | + 5 `CALLRESULTERROR`, 6 `SEND` |
| Unreadable `MessageId` | no rule | answer with id `"-1"` | answer with id `"-1"` |
| "Syntactically incorrect" | `FormationViolation` | `FormatViolation` | `FormatViolation` |
| Occurrence violation | `OccurenceConstraintViolation` | `OccurrenceConstraintViolation` | `OccurrenceConstraintViolation` |
| One outstanding `CALL` | `SHOULD NOT` | `SHALL NOT` | `SHALL NOT` |
| Basic-auth password | `AuthorizationKey`, hexadecimal, 16β20 bytes | `BasicAuthPassword`, UTF-8, β₯ 16 chars, ceiling 40β64 | same |
| `permessage-deflate` | discouraged | β | CSMS and LC **shall** support β [implemented](https://hupe1980.github.io/ocpp-kit/docs/websocket/) |
| Transaction ordering | strictly chronological (Β§3.7) | same | same |
| Charging point | `connectorId`, no EVSEs | `evseId` | same |
| Signed meter values | serialized into a `SignedData` sample's `value` **string** | `SampledValue.signedMeterValue` | same, with fewer required members |
**You can test your own code with the tools this crate tests itself with.** `testkit` ships
`Sim` and `Recorder` β what the protocol-rule tests here are written against β and mock
peers that give you a working CSMS or Charging Station on a loopback port in one line:
```rust,no_run
# use std::time::Duration;
# use ocpp_kit::Version;
# use ocpp_kit::testkit::{MockCsms, MockStation};
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
let csms = MockCsms::start().await?;
let station = MockStation::connect(csms.url(), "CS-0001")?;
station.boot(Version::V2_1).await?;
assert!(csms.wait_for("BootNotification", Duration::from_secs(5)).await);
# Ok(()) }
```
**And a vehicle to test a controller against.** `testkit::Ev` reacts the way a car does β late,
not at all below 6 A, with a pause or a fault when the phases switch, stopping at its target β and
`testkit::Wallbox` plugs it into a simulated EVSE that answers your CSMS's charging profiles and
reports back, in 1.6, 2.0.1 or 2.1, on virtual time:
```rust
# use std::time::Duration;
# use ocpp_kit::Version;
# use ocpp_kit::testkit::{Ev, Wallbox};
# fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut wallbox = Wallbox::new(Version::V2_0_1, "2026-11-20T18:00:00Z".parse()?);
let sent = wallbox.plug_in(Ev::builder().soc(30).build())?; // what your CSMS receives
let reports = wallbox.advance(Duration::from_secs(8 * 3600)); // a night, in milliseconds
# let _ = (sent, reports);
# Ok(()) }
```
**A `SEND` cannot be awaited.** OCPP 2.1's `SEND` is never answered (Part 4 Β§4.2.4), so
`Handle::call` does not accept one β the bound is `Confirmed`, which the code generator
implements for exactly the actions whose schemas define a response. Unconfirmed messages go
through `Handle::send`, which returns when the frame is written. What would otherwise be a
message timeout in production is a compile error.
**Real-world tolerance is a policy, not a guess.** The strict default is exactly what the
specification requires. `DecodeOptions::lenient()` additionally accepts the things field
devices actually send β timestamps without an offset, `"42"` where a number belongs, enum
values that are not in the schema β and it does so with a bounded *repair loop* that runs
only after the strict parse has already failed, so conforming traffic costs nothing. Every
repair is **reported**, by JSON pointer and kind, and a CSMS sees them for its whole fleet as
`SessionEvent::Repaired` β so tolerance is something an operator can count and take back to a
vendor, not something that silently happens.
**The schemas are the OCA's, checked.** `schemas/` holds the OCA packages byte for byte β
`cargo xtask schemas-check` fails CI on any difference β and where the specification text is
stricter than a schema the generator applies a cited patch that fails once the schema is
fixed. Each file's JSON Schema draft decides what `integer` means, so `20000.0` is accepted
where draft-06 says it is an integer (2.x) and not where draft-04 says it is not (1.6 core).
## `ocpp-cli`
```console
$ cargo install ocpp-kit --features cli
$ ocpp-cli actions --version 2.1 --block R
ACTION BLOCK KIND DIRECTION
ClearDERControl R CALL CSMS -> CS
GetDERControl R CALL CSMS -> CS
NotifyDERAlarm R CALL CS -> CSMS
β¦
$ ocpp-cli replay capture.ocppcap --version 2.1 # validate a whole capture
$ ocpp-cli signed --key MzA1OTMwMTMw⦠# read a signed meter value as a CSMS must
$ ocpp-cli csms --bind 127.0.0.1:9000 # a mock CSMS
$ ocpp-cli station --url ws://β¦ --identity CS-0001 # a mock charging station
```
## Feature flags
| `std` | β
| `std` types and `std::error::Error`; off gives `alloc`-only L0βL2 |
| `v1_6`, `v2_0_1`, `v2_1` | β
| The per-version types and dispatch tables |
| `tokio` | β | L3: the Tokio + WebSocket transport |
| `rustls` | β | TLS for security profiles 2 and 3 |
| `compression` | β | RFC 7692 `permessage-deflate`, which 2.1 requires of a CSMS |
| `signed-messages` | β | JWS signed messages (Part 4 ch. 7) |
| `getrandom` | β | Random `MessageId`s and `transactionId`s, which is what Part 4 Β§4.1.4 and E01.FR.08 need; implied by `tokio` |
| `testkit` | β | A recorder for the sans-I/O engine, mock peers, and a simulated vehicle and wallbox, for your `[dev-dependencies]` |
| `jws-es256` | β | A ready-made software ES256 signer and verifier |
| `station`, `csms` | β | The L4 building blocks |
| `tracing` | β | `tracing` spans and events in the transport |
| `cli` | β | The `ocpp-cli` binary |
| `full` | β | Everything above |
`ocpp_kit::standard` β the security events, standardized components and reason codes β and
`ocpp_kit::metering` are always available: protocol knowledge, not machinery.
## Documentation
* [The guide](https://hupe1980.github.io/ocpp-kit/docs/) β layer by layer, with the
specification citations
* [API reference](https://docs.rs/ocpp-kit)
* [`SPEC_EDITIONS.md`](SPEC_EDITIONS.md) β exactly which editions and errata the generated
code targets
* [`CHANGELOG.md`](CHANGELOG.md)
## Development
```console
$ cargo xtask codegen # regenerate src/v1_6, src/v2_0_1, src/v2_1 from schemas/
$ cargo xtask codegen --check # what CI runs; fails if the committed code is stale
$ cargo xtask schema-report # action, enum and type counts per version
$ cargo xtask schema-diff # what actually differs between 2.0.1 and 2.1 (--check in CI)
$ cargo xtask coverage # requirement IDs cited; fails on one Part 2 does not define
$ cargo xtask coverage --profile all # how much of each certification profile the tests drive
$ cargo xtask appendix # regenerate src/standard from Part 2 β Appendices
$ cargo xtask no-floats # fail if an f32/f64 reaches a public signature
$ cargo xtask schemas-check # fail if a vendored schema is not the OCA file SHA256SUMS records
$ cargo xtask ci # run what CI runs β commands *and* env β from the workflow
$ cargo xtask ci --all # β¦even the ones whose tooling looks to be missing
$ cargo test --features full
```
Generated code is committed, so building the crate needs neither the schemas nor a network
connection, and a schema change shows up as a readable diff.
## JSON schemas
The OCPP JSON schemas in [`schemas/`](schemas/) are published by the Open Charge Alliance and
are redistributed unmodified β OCPP 1.6 (all files & errata) with the Security Whitepaper
edition 4, 2.0.1 edition 4, 2.1 edition 2 β and `schemas/SHA256SUMS` lists every file; see
[`schemas/NOTICE`](schemas/NOTICE). They are **not** covered
by this crate's license. The specification PDFs are not redistributed.
## License
Licensed under either of
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE))
- MIT license ([LICENSE-MIT](LICENSE-MIT))
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion
in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above,
without any additional terms or conditions.