OCPP, the Open Charge Point Protocol, is how an EV charger talks to the system that runs it. If you build a Flutter EV charging app, a charger simulator, or a gateway that sits next to real hardware, you will end up reading OCPP frames sooner or later. Most of the existing tooling is written for Java, Node or Python. For Dart there was little, so I wrote dart_ocpp after working on an EV charging app where we needed exactly this.
This post covers how OCPP works, then shows an OCPP 1.6 WebSocket client in Dart, the 2.0.1 equivalent, and what the migration helpers do. Every code sample uses the package's real API.
What OCPP 1.6-J and 2.0.1 are
OCPP has two sides:
- The charge point (also called the charging station): the physical charger.
- The Central System (1.6) or CSMS (2.0.1): the backend that authorizes drivers, records sessions and sends commands.
The charge point opens a WebSocket connection to the backend and they exchange JSON messages. A few facts matter in practice:
- OCPP 1.6-J is the JSON-over-WebSocket flavour of 1.6 (the
Jstands for JSON, as opposed to the older SOAP version). It is the most widely deployed version. - OCPP 2.0.1 is a redesign, not a patch. It adds EVSEs on top of connectors, replaces
StartTransaction,StopTransactionandMeterValueswith a singleTransactionEvent, and adds a device model and security profiles. - The framing is identical in both. Only the message payloads and the WebSocket subprotocol (
ocpp1.6orocpp2.0.1) differ.
The charge point connects to wss://<backend>/<path>/<chargePointId>. The identity is the last path segment, which is how the backend knows which charger it is talking to.
Do you need an OCPP client or a server?
The side you implement depends on what you are building:
- A charger, a charger simulator, or a gateway in front of a charger is the charge point. That is a client: it dials the backend.
- A backend that manages many chargers is the Central System or CSMS. That is a server: it accepts connections.
A Flutter app for drivers usually implements neither. It talks to your own backend API, and the backend speaks OCPP to the chargers. A Flutter client makes sense when the app is the charge-point side: a commissioning tool for installers, a simulator for testing a backend, or an app on an embedded display.
dart_ocpp is the charge point client side today. A Central System server API is on the roadmap but is not in 0.2.0, so I won't pretend otherwise. If you are building the backend, you can still use its message models and codec to parse frames.
CALL, CALLRESULT and CALLERROR
Every OCPP-J message is a JSON array in one of three shapes:
[2, "<uniqueId>", "<Action>", { ...payload }] CALL
[3, "<uniqueId>", { ...payload }] CALLRESULT
[4, "<uniqueId>", "<errorCode>", "<description>", {}] CALLERROR
A CALL is a request. The receiver answers with a CALLRESULT or a CALLERROR that carries the same uniqueId. That ID is the only thing that links a response to its request, and either side can send CALLs, so a client has to keep a table of pending requests and still be ready to receive requests from the backend.
dart_ocpp models these as OcppCall, OcppCallResult and OcppCallError, and JsonOcppCodec encodes and decodes them. A malformed frame throws an OcppFormatException from decode.
Connecting a charge point over WebSocket
import 'package:dart_ocpp/dart_ocpp.dart';
final client = OcppClient(
url: 'wss://cs.example.com/ocpp',
version: OcppVersion.v16,
chargePointId: 'CP01',
reconnect: ReconnectPolicy(),
);
await client.connect();
What OcppClient does with those arguments:
- Negotiates the
ocpp1.6orocpp2.0.1subprotocol fromversion. - Appends the charge point ID to the URL path if it is not already the last segment, so
wss://cs.example.com/ocppbecomes.../ocpp/CP01. - Sends WebSocket pings every 30 seconds by default (
pingInterval), to keep NAT and load balancer timeouts from dropping an idle connection. - Reconnects with exponential backoff when you pass a
ReconnectPolicy. It starts at 1 second and doubles up to a 60 second cap, andmaxAttemptslets it give up. - Fails a request with a
TimeoutExceptionif no answer arrives withincallTimeout, 30 seconds by default.
The built-in transport uses dart:io, so it targets Android, iOS, desktop and the Dart VM. You can pass your own OcppTransport instead, which is also how you test without a network.
The boot, heartbeat and status flow
A charge point does not just start sending data. The order is fixed:
- BootNotification. The charger introduces itself. The backend answers
Accepted,PendingorRejected, plus the heartbeat interval to use. - StatusNotification for each connector, so the backend knows what is available.
- Heartbeat at the agreed interval, so the backend knows the charger is alive. The response carries the backend's clock, which is how chargers correct their own time.
- Authorize when a driver presents an RFID card or token.
The client has one method for each of these, and the same method names work on both protocol versions:
final boot = await client.sendBootNotification(vendor: 'Acme', model: 'X1');
if (boot.accepted) {
await client.sendStatusNotification(
connectorId: 1,
status: ConnectorStatusEnumType.available,
);
final serverTime = await client.sendHeartbeat();
print('Backend clock: $serverTime, heartbeat every ${boot.interval}s');
}
sendBootNotification returns a version-neutral BootNotificationResult with accepted, status, currentTime and interval. If accepted is false, interval is the retry delay and you must not send other messages yet.
sendStatusNotification takes the 2.0.1 ConnectorStatusEnumType on both versions. On a 1.6 client the package maps it to the 1.6 status through its translator. 2.0.1 only distinguishes Available, Occupied, Reserved, Unavailable and Faulted, so a connector reported as occupied becomes 1.6 Preparing by default.
final auth = await client.sendAuthorize('04A1B2C3D4');
if (auth.accepted) {
// Start charging.
}
AuthorizeResult has accepted and the raw status string, for cases such as Blocked or Expired.
An OCPP 1.6 transaction: StartTransaction and StopTransaction
In 1.6, a charging session is two messages. The charge point sends StartTransaction, and the backend assigns the transaction ID in the response:
final started = await client.sendStartTransaction(
StartTransactionReq(
connectorId: 1,
idTag: '04A1B2C3D4',
meterStart: 0,
timestamp: DateTime.now().toUtc(),
),
);
final txId = started.transactionId;
When the session ends, you send StopTransaction with that ID and the final meter reading:
await client.sendStopTransaction(
StopTransactionReq(
meterStop: 12400,
timestamp: DateTime.now().toUtc(),
transactionId: txId,
reason: Reason.local,
),
);
Meter values are in Wh by default. In between, sendMeterValues carries readings for the backend to bill from.
An OCPP 2.0.1 transaction: TransactionEvent
2.0.1 replaces those three messages with TransactionEvent, with an eventType of Started, Updated or Ended. Two things change:
- The charge point generates the transaction ID, as a string.
- Each event carries a
seqNothat you increase within the transaction, so the backend can detect gaps and order events.
await client.sendTransactionEvent(
TransactionEventRequest(
eventType: TransactionEventEnumType.started,
timestamp: DateTime.now().toUtc(),
triggerReason: TriggerReasonEnumType.authorized,
seqNo: 0,
transactionInfo: TransactionType(transactionId: 'tx-0001'),
evse: EVSEType(id: 1, connectorId: 1),
idToken: IdTokenType(
idToken: '04A1B2C3D4',
type: IdTokenEnumType.iso14443,
),
),
);
The client guards against mixing versions. Calling sendTransactionEvent on a 1.6 client, or sendStartTransaction on a 2.0.1 client, throws UnsupportedError instead of sending a message the backend would reject.
Handling commands from the backend
The backend sends CALLs too: it can reserve a connector, push a charging profile or send a local authorization list. There are two ways to receive them.
For the seven supported command types (ReserveNow, CancelReservation, SetChargingProfile, ClearChargingProfile, GetCompositeSchedule, SendLocalList and GetLocalListVersion) register a typed handler that returns the matching response:
final client = OcppClient(
url: 'wss://cs.example.com/ocpp/CP01',
version: OcppVersion.v201,
chargePointId: 'CP01',
);
client.on<ReserveNowRequest>((req) async {
return ReserveNowResponse(status: ReserveNowStatusEnumType.accepted);
});
On a 1.6 client the same call uses the 1.6 types: client.on<ReserveNowReq>((req) => ReserveNowConf(status: ReservationStatus.accepted)). Registering a type from the wrong protocol version throws an ArgumentError.
If a handler throws an OcppCallException, the package sends a CALLERROR with that code. Any other exception becomes an InternalError, and a payload that fails to decode is answered with the format-violation error for that version.
Everything without a handler arrives on client.incoming as a raw OcppCall, and you answer it yourself:
client.incoming.listen((msg) {
if (msg is OcppCall && msg.action == 'Reset') {
client.respond(msg.uniqueId, {'status': 'Accepted'});
} else if (msg is OcppCall) {
client.respondError(msg.uniqueId, 'NotImplemented', 'Not supported');
}
});
Commands such as Reset and RemoteStartTransaction have no typed model in 0.2.0, so this raw path is how you handle them today. For any message the client has no helper for, client.call(action, payload) sends a raw CALL and returns the OcppCallResult.
Errors from the other side are exceptions. When the backend answers one of your requests with a CALLERROR, the future throws OcppCallException, which carries the error code and description.
What the 1.x to 2.x migration helpers do
Many fleets run 1.6 chargers today and are moving to 2.0.1, and a gateway often needs to speak both. V16ToV201Translator and V201ToV16Translator convert message objects between the two versions:
final event = V16ToV201Translator.fromStartTransaction(
startReq,
transactionId: 'tx-0001',
);
The transactionId is a parameter because a 1.6 charge point only learns its ID from the backend's response, while 2.0.1 needs one up front.
The package's MIGRATION.md documents every mapping. The important point is that the conversion is best effort and lossy, because 2.0.1 restructured the protocol. A few examples from that document:
- Connectors become EVSEs, and the translator assumes
evseId == connectorIdunless you override it. - A 1.6
idTaghas no type, so it is mapped to the ISO 14443 token type. - 1.6
StatusNotificationerror details have no destination in 2.0.1, because 2.0.1 reports faults through a different message. The fine-grained occupied states (Preparing,Charging,SuspendedEVand so on) collapse intoOccupied. - Going back from 2.0.1 to 1.6 loses fields such as
triggerReasonandseqNo.
Read that file before relying on a conversion in production. It lists what is lost and what is defaulted for each message.
Limits of version 0.2.0
The package does not validate payloads against the OCPP JSON schemas, and it does not store or enforce reservations, charging profiles or local lists; it only models and routes them. Not yet covered: ISO 15118 Plug and Charge, a Central System server API, security profile helpers, and the 2.0.1 device model. The README keeps an up-to-date list.
Where this fits in a real EV app
OCPP is one layer of an EV charging stack. The EV charging app case study shows the app side of a real project. If your stack also uses AWS IoT, my post on Flutter and AWS IoT Core with Cognito covers connecting devices and apps to the cloud over MQTT. For the wider picture of MQTT, BLE and cloud work in mobile apps, see the IoT app developer page.
Try it
dart pub add dart_ocpp
The code is on GitHub, the package is on pub.dev, and the repository has an example charge point. Issues and pull requests are welcome, particularly for the remaining backend-initiated commands, which are the most useful next step.