dart_ocpp

A production-ready Open Charge Point Protocol (OCPP) 1.6-J and 2.0.1 Central System (server) and Charge Point (client) implementation for Dart and Flutter. It connects electric vehicle (EV) charging stations and Central Systems / Charging Station Management Systems (CSMS) over WebSocket JSON connections, providing strongly-typed message models, automated subprotocol negotiation, automatic reconnects, queueing for strict OCPP synchronicity, and bidirectional message translation helpers for migrating between OCPP 1.6 and 2.0.1.

Features

  • Central System (server) and Charge Point (client) roles for both OCPP 1.6-J (ocpp1.6) and OCPP 2.0.1 (ocpp2.0.1) JSON subprotocols.
  • OcppServer & OcppSession: Bind an HTTP server, accept WebSocket upgrades with path prefix routing, negotiate subprotocols, enforce pre-upgrade authorization hooks, track session lifecycle events, and handle reconnection of stale sockets.
  • Strict OCPP synchronicity: Outbound call messages on OcppSession respect the OCPP requirement of at most one outstanding request per connection direction via internal FIFO queueing.
  • Typed message models with json_serializable support covering core operations: BootNotification, Authorize, StatusNotification, Heartbeat, MeterValues, TransactionEvent, Reservation, Smart Charging, and Local Auth List.
  • Automatic reconnect and keep-alive: Configurable exponential-backoff reconnect policy for clients and WebSocket ping/pong heartbeat handling.
  • Typed handlers on both ends: Register strongly-typed incoming call listeners with session.on<T>() / client.on<T>() with automated CALLRESULT and CALLERROR dispatching.
  • Bidirectional 1.6 <-> 2.0.1 migration: V16ToV201Translator and V201ToV16Translator simplify transitioning existing charging station infrastructure between protocol versions.
  • Pluggable transport layer: Easy testing and custom network environments via the OcppTransport interface.

Install

Add dart_ocpp to your pubspec.yaml:

dart pub add dart_ocpp

Or manually:

dependencies:
  dart_ocpp: ^0.3.0

Quickstart: Central System (Server)

import 'dart:io';
import 'package:dart_ocpp/dart_ocpp.dart';

final server = await OcppServer.bind(
  host: InternetAddress.anyIPv4,
  port: 9000,
  pathPrefix: '/ocpp', // e.g. ws://host:9000/ocpp/CP001 -> id CP001
  onAuthorize: (chargePointId, subprotocols, headers) async {
    // Optional async authorization hook (e.g. check Basic auth or bearer token)
    return const OcppAuthResult.accept();
  },
);

// Register typed server-side handlers for Charge Point requests
server.on<BootNotificationReq>((req) async {
  print('Boot request from vendor: ${req.chargePointVendor}');
  return BootNotificationConf(
    status: RegistrationStatus.accepted,
    currentTime: DateTime.now().toUtc(),
    interval: 300,
  );
});

// Monitor session lifecycle
server.events.listen((event) async {
  switch (event) {
    case OcppSessionConnected(:final session):
      print('Charge point connected: ${session.chargePointId} (${session.version.subprotocol})');
      // Send a Central-System-initiated request to the charger:
      final res = await session.reset(type: ResetType.soft);
      print('Reset response: ${res.status}');
    case OcppSessionDisconnected(:final session):
      print('Charge point disconnected: ${session.chargePointId}');
  }
});

Quickstart: OCPP 2.0.1

import 'package:dart_ocpp/dart_ocpp.dart';

final client = OcppClient(
  url: 'wss://cs.example.com/ocpp/CP01',
  version: OcppVersion.v201,
  chargePointId: 'CP01',
);
await client.connect();
final boot = await client.sendBootNotification(vendor: 'Acme', model: 'X1');
if (boot.accepted) {
  await client.sendStatusNotification(
      connectorId: 1, status: ConnectorStatusEnumType.available);
}
client.incoming.listen((msg) {
  if (msg is OcppCall && msg.action == 'Reset') {
    client.respond(msg.uniqueId, {'status': 'Accepted'});
  }
});

Quickstart: OCPP 1.6-J

final client = OcppClient(
  url: 'wss://cs.example.com/ocpp',   // "/CP01" is appended automatically
  version: OcppVersion.v16,
  chargePointId: 'CP01',
);
await client.connect();
await client.sendBootNotification(vendor: 'Acme', model: 'X1');
final tx = await client.sendStartTransaction(StartTransactionReq(
    connectorId: 1,
    idTag: 'TAG',
    meterStart: 0,
    timestamp: DateTime.now().toUtc()));
print(tx.transactionId);

The same convenience methods (sendBootNotification, sendHeartbeat, sendAuthorize, sendStatusNotification, sendDataTransfer) work on both versions and return version-neutral results. Version-specific messages (sendStartTransaction/sendStopTransaction/sendMeterValues for 1.6, sendTransactionEvent for 2.0.1) throw UnsupportedError on the wrong version. client.call(action, payload) sends any other message.

Connection features: subprotocol negotiation (ocpp1.6 / ocpp2.0.1), WebSocket ping heartbeat (pingInterval, default 30 s), optional exponential-backoff reconnect (reconnect: ReconnectPolicy()), request timeout (callTimeout, default 30 s). Provide your own OcppTransport for testing.

Migration note

V16ToV201Translator and V201ToV16Translator convert messages between versions. Conversions are lossy; see MIGRATION.md.

final event = V16ToV201Translator.fromStartTransaction(req, transactionId: 'tx-1');

Supported messages (Charge Point -> Central System)

Message OCPP 1.6 OCPP 2.0.1
BootNotification BootNotificationReq/Conf BootNotificationRequest/Response
Authorize AuthorizeReq/Conf AuthorizeRequest/Response
Heartbeat HeartbeatReq/Conf HeartbeatRequest/Response
StartTransaction StartTransactionReq/Conf (TransactionEvent)
StopTransaction StopTransactionReq/Conf (TransactionEvent)
MeterValues MeterValuesReq/Conf (TransactionEvent)
TransactionEvent - TransactionEventRequest/Response
StatusNotification StatusNotificationReq/Conf StatusNotificationRequest/Response
DataTransfer DataTransferReq/Conf DataTransferRequest/Response
FirmwareStatusNotification FirmwareStatusNotificationReq/Conf FirmwareStatusNotificationRequest/Response
DiagnosticsStatusNotification DiagnosticsStatusNotificationReq/Conf -
LogStatusNotification - LogStatusNotificationRequest/Response

Supported messages (Central System -> Charge Point)

Register a typed handler with client.on<T>(...); the handler returns the matching response object. Calls without a handler still arrive on client.incoming as raw OcppCalls.

Message OCPP 1.6 OCPP 2.0.1
ReserveNow ReserveNowReq/Conf ReserveNowRequest/Response
CancelReservation CancelReservationReq/Conf CancelReservationRequest/Response
SetChargingProfile SetChargingProfileReq/Conf SetChargingProfileRequest/Response
ClearChargingProfile ClearChargingProfileReq/Conf ClearChargingProfileRequest/Response
GetCompositeSchedule GetCompositeScheduleReq/Conf GetCompositeScheduleRequest/Response
SendLocalList SendLocalListReq/Conf SendLocalListRequest/Response
GetLocalListVersion GetLocalListVersionReq/Conf GetLocalListVersionRequest/Response
Reset ResetReq/Conf ResetRequest/Response
RemoteStartTransaction RemoteStartTransactionReq/Conf RequestStartTransactionRequest/Response
RemoteStopTransaction RemoteStopTransactionReq/Conf RequestStopTransactionRequest/Response
ChangeConfiguration ChangeConfigurationReq/Conf (SetVariables)
GetConfiguration GetConfigurationReq/Conf (GetVariables)
SetVariables - SetVariablesRequest/Response
GetVariables - GetVariablesRequest/Response
TriggerMessage TriggerMessageReq/Conf TriggerMessageRequest/Response
UnlockConnector UnlockConnectorReq/Conf UnlockConnectorRequest/Response
ChangeAvailability ChangeAvailabilityReq/Conf ChangeAvailabilityRequest/Response
ClearCache ClearCacheReq/Conf ClearCacheRequest/Response
GetDiagnostics GetDiagnosticsReq/Conf -
UpdateFirmware UpdateFirmwareReq/Conf -
final client = OcppClient(
    url: url, version: OcppVersion.v201, chargePointId: 'CP01');
client.on<ReserveNowRequest>((req) async =>
    ReserveNowResponse(status: ReserveNowStatusEnumType.accepted));
// v1.6: client.on<ResetReq>((req) async =>
//     ResetConf(status: ResetStatus.accepted));

Throw an OcppCallException from a handler to send a specific CALLERROR; any other exception is answered with InternalError.

Design notes and assumptions

  • Messages are json_serializable classes; null optional fields are omitted from JSON. Regenerate with dart run build_runner build --delete-conflicting-outputs.
  • v1.6 types use Req/Conf suffixes, v2.0.1 types Request/Response; v2.0.1 enums end in EnumType. TransactionEventReq is an alias.
  • SampledValue.measurand/phase/unit are plain strings (large, vendor-extensible enumerations).
  • Inbound calls without a registered typed handler arrive as raw OcppCall on incoming (and automatically respond with NotImplemented per the OCPP spec).
  • Where v1.6 and v2.0.1 spec names collide, the 2.0.1 class gets a Type suffix (AuthorizationDataType).
  • No JSON-schema validation of payloads is performed.
  • json_serializable is capped below 6.10 in dev_dependencies because newer releases did not compile against the analyzer pub resolved on Dart 3.10.

Not yet covered (Phase 2 and later)

  • State handling and persistence: the library routes messages and enforces framing/synchronicity rules, but does not store or enforce reservations, transaction state, auth lists, or smart charging schedules in a persistence store.
  • OCPP 2.0.1 Firmware Management & Diagnostics CS-initiated commands: UpdateFirmware, PublishFirmware, GetLog, CustomerInformation, and monitoring commands remain outstanding for Phase 2. (All 9 Core profile CS-initiated commands—Reset, RequestStartTransaction, RequestStopTransaction, SetVariables, GetVariables, TriggerMessage, UnlockConnector, ChangeAvailability, ClearCache—are fully implemented on both client and server).
  • The OCPP 2.0.1 customData vendor extension container is not modelled on any message type. Unknown JSON keys are ignored on decode, so an inbound customData object is dropped rather than surfaced. If you need vendor extensions, read the raw OcppCall payload instead of the typed model.
  • Security profiles: TLS/mTLS certificate management helpers and automated Basic auth challenge generation.
  • ISO 15118 Plug and Charge (certificates, Get15118EVCertificate, etc.).
  • OCPP 2.0.1 advanced device model reporting (NotifyReport, GetBaseReport, GetReport, SetNetworkProfile).
  • OCPP 2.0.1 advanced charging-profile reporting (GetChargingProfiles, ReportChargingProfiles, NotifyChargingLimit, ClearedChargingLimit).

Example

Check out the example directory for a complete runnable demonstration (dart_ocpp_example.dart) showing how to establish an OCPP 2.0.1 connection, perform a boot notification handshake, send status notifications, and listen for incoming commands.

License

MIT

Libraries

dart_ocpp
OCPP 1.6-J and 2.0.1 Central System (server) and Charge Point (client) library over WebSocket, with typed message models and 1.6<->2.0.1 migration helpers.