To implement the actual OCPP protocol, you must subclass ocpp.v16.ChargePoint (or the version appropriate for your needs). This class handles message routing and validation.
Key Implementation Steps:
- Subclass
ChargePoint: Create a class that inherits from ocpp.v16.ChargePoint. - Register Handlers: Use the
@on(Action.ACTION_NAME) decorator to register methods that handle specific OCPP actions (e.g., Action.boot_notification). - Handle Arguments: The library automatically converts OCPP
camelCase JSON keys to Pythonic snake_case. Required arguments from the OCPP payload should be defined as named parameters in your handler, while optional arguments can be captured using **kwargs. - Return Results: Handlers must return an instance of a
call_result class (e.g., call_result.BootNotification) to send a valid response back to the client. - Connection Lifecycle: In your WebSocket
on_connect handler, extract the charge_point_id from the connection path, instantiate your custom ChargePoint class, and call await charge_point.start().
Example Implementation:
from datetime import datetime, timezone
import websockets
from ocpp.routing import on
from ocpp.v16 import ChargePoint as cp
from ocpp.v16 import call_result
from ocpp.v16.enums import Action, RegistrationStatus
class MyChargePoint(cp):
@on(Action.boot_notification)
async def on_boot_notification(
self, charge_point_vendor, charge_point_model, **kwargs
):
return call_result.BootNotification(
current_time=datetime.now(tz=timezone.utc).isoformat(),
interval=10,
status=RegistrationStatus.accepted,
)
async def on_connect(connection: websockets.ServerConnection):
# Extract ID from path, e.g., /cp_id_1 -> cp_id_1
charge_point_id = connection.request.path.split("/")[-1]
charge_point = MyChargePoint(charge_point_id, connection)
await charge_point.start()
from datetime import datetime, timezone
import websockets
from ocpp.routing import on
from ocpp.v16 import ChargePoint as cp
from ocpp.v16 import call_result
from ocpp.v16.enums import Action, RegistrationStatus
class MyChargePoint(cp):
@on(Action.boot_notification)
async def on_boot_notification(
self, charge_point_vendor, charge_point_model, **kwargs
):
return call_result.BootNotification(
current_time=datetime.now(tz=timezone.utc).isoformat(),
interval=10,
status=RegistrationStatus.accepted,
)
async def on_connect(connection: websockets.ServerConnection):
charge_point_id = connection.request.path.split("/")[-1]
charge_point = MyChargePoint(charge_point_id, connection)
await charge_point.start()