ocpp-kit
An Open Charge Point Protocol toolkit for Rust β OCPP 1.6J, 2.0.1 and 2.1 over JSON/WebSocket, for charging stations, CSMS backends and local controllers.
π Documentation Β· API reference
$ cargo add ocpp-kit --features tokio,rustls
Five layers
| Layer | Module | What it gives you | no_std |
|---|---|---|---|
| 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; network failover |
β |
| L4 | station Β· csms |
Opt-in blocks: device model, 1.6 configuration keys, transaction rules, local authorization, composite schedules, an idempotent CSMS ledger, version-agnostic events | partial |
| β | 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
use ;
use ;
async
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:
$ 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.
$ 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.
# use Duration;
# use Version;
# use ;
# use Sim;
#
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 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.
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.
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:
| 1.6J | 2.0.1 | 2.1 | |
|---|---|---|---|
| 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 |
| 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:
# use Duration;
# use Version;
# use ;
# async
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
$ 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
| Feature | Default | What it turns on |
|---|---|---|
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 MessageIds and transactionIds, 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 and mock peers, 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 β layer by layer, with the specification citations
- API reference
SPEC_EDITIONS.mdβ exactly which editions and errata the generated code targetsCHANGELOG.md
Development
$ 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/ 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. 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)
- MIT license (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.