Overview
This is a comprehensive implementation of the Open Charge Point Protocol (OCPP) 2.1 specification, providing both CSMS (Central System Management System) server and CP (Charge Point) client functionality. The implementation is designed for educational purposes with extensive comments and documentation.
Features
CSMS (Central System Management System) Server
- WebSocket Server: Handles multiple CP connections simultaneously
- Message Processing: Complete OCPP 2.1 message handling
- Connection Management: Automatic connection monitoring and cleanup
- Transaction Management: Track and manage charging transactions
- Status Monitoring: Real-time status updates from charging stations
- Security: Authentication and authorization support
- Logging: Comprehensive logging with structured output
- Statistics: Real-time performance monitoring
CP (Charge Point) Client
- WebSocket Client: Connects to CSMS server
- Boot Process: Automatic boot notification and authentication
- Heartbeat: Periodic heartbeat to maintain connection
- Status Reporting: Real-time status notifications
- Transaction Handling: Start, stop, and manage transactions
- Meter Values: Periodic meter value reporting
- Data Transfer: Vendor-specific data exchange
- Error Handling: Robust error handling and recovery
Architecture
Message Flow
CP Client <---> WebSocket <---> CSMS Server
| |
| |
v v
Local State Database
Management Storage
Key Components
-
Base Classes (
ocpp/base/) - Message types and enums - Exception handling - Common data structures -
CSMS Server (
ocpp/csms/) - WebSocket server implementation - Message handlers - Connection management - Business logic -
CP Client (
ocpp/cp/) - WebSocket client implementation - Message handlers - State management - Event simulation -
Configuration (
config/) - Settings management - Logging configuration - Environment variables -
Examples (
examples/) - Server example - Client example - Integration tests
Installation
Prerequisites
- Python 3.8+
- pip package manager
Dependencies
pip install -r requirements.txt
Required Packages
websockets: WebSocket communicationpydantic: Data validationasyncio: Asynchronous programmingjsonschema: JSON schema validationcryptography: Security featuresaiofiles: Async file operationsaiosqlite: Async database operations
Usage
Running CSMS Server
from examples.csms_server_example import CSMSServerExample
async def main():
server = CSMSServerExample()
await server.start()
asyncio.run(main())
Running CP Client
from examples.cp_client_example import CPClientExample
async def main():
client = CPClientExample()
await client.start()
asyncio.run(main())
Configuration
The implementation uses environment variables and configuration files for settings:
# Environment variables
export CSMS_HOST=0.0.0.0
export CSMS_PORT=9000
export CP_CSMS_URL=ws://localhost:9000
export LOG_LEVEL=INFO
Customization
Adding Custom Message Handlers
class CustomCSMSServer(CSMSServer):
async def _handle_custom_action(self, payload):
# Custom handler implementation
return {"status": "Accepted"}
Extending Message Types
class CustomMessageType(OCPPBaseMessage):
custom_field: str
custom_data: Optional[Dict[str, Any]]
OCPP 2.1 Compliance
Supported Message Types
Core Profile
Authorize: User authorizationBootNotification: Station boot processHeartbeat: Connection keep-aliveStatusNotification: Status updatesTransactionEvent: Transaction managementMeterValues: Energy measurementDataTransfer: Vendor-specific data
Security Profile
SecurityEventNotification: Security eventsSignCertificate: Certificate signingCertificateSigned: Certificate installationGetInstalledCertificateIds: Certificate managementDeleteCertificate: Certificate removalInstallCertificate: Certificate installationGetCertificateStatus: Certificate validationGetCertificateChainStatus: Certificate chain validation
Smart Charging Profile
SetChargingProfile: Charging profile managementGetChargingProfiles: Profile retrievalClearChargingProfile: Profile removalReportChargingProfiles: Profile reporting
Tariff and Cost Profile
GetTariffs: Tariff informationSetDefaultTariff: Default tariff settingClearTariffs: Tariff removalCostUpdated: Cost updatesChangeTransactionTariff: Tariff changes
Display Messages Profile
SetDisplayMessage: Message displayGetDisplayMessages: Message retrievalClearDisplayMessage: Message removalNotifyDisplayMessages: Message notifications
Monitoring Profile
SetVariableMonitoring: Variable monitoringClearVariableMonitoring: Monitor removalSetMonitoringBase: Monitoring baseSetMonitoringLevel: Monitoring levelGetMonitoringReport: Report generationNotifyMonitoringReport: Report notifications
Reporting Profile
GetReport: Report generationNotifyReport: Report notificationsGetBaseReport: Base report generation
Additional Features
TriggerMessage: Message triggeringChangeAvailability: Availability changesUnlockConnector: Connector unlockingReset: Station resetClearCache: Cache clearingUpdateFirmware: Firmware updatesSendLocalList: Local authorization listGetLocalListVersion: List versionReserveNow: Reservation managementCancelReservation: Reservation cancellationReservationStatusUpdate: Reservation statusGetLog: Log retrievalGet15118EVCertificate: ISO 15118 certificates
Error Handling
The implementation includes comprehensive error handling:
try:
response = await client.send_message(message)
except OCPPTimeoutError:
# Handle timeout
except OCPPConnectionError:
# Handle connection issues
except OCPPValidationError:
# Handle validation errors
Security Features
- TLS Support: Encrypted communication
- Certificate Management: X.509 certificate handling
- Authentication: User authentication
- Authorization: Access control
- Security Events: Security monitoring
Testing
Unit Tests
pytest tests/test_csms.py
pytest tests/test_cp.py
Integration Tests
pytest tests/test_integration.py
Manual Testing
- Start CSMS server:
python examples/csms_server_example.py
- Start CP client:
python examples/cp_client_example.py
- Run integration test:
python examples/integration_test.py
Performance Considerations
Scalability
- Connection Pooling: Efficient connection management
- Async Operations: Non-blocking I/O
- Message Queuing: Buffered message processing
- Resource Management: Automatic cleanup
Monitoring
- Statistics: Real-time performance metrics
- Logging: Structured logging with context
- Health Checks: Connection health monitoring
- Error Tracking: Comprehensive error reporting
Troubleshooting
Common Issues
-
Connection Failures - Check network connectivity - Verify WebSocket URL - Check firewall settings
-
Authentication Errors - Verify station credentials - Check certificate validity - Review security settings
-
Message Errors - Validate message format - Check required fields - Review error logs
Debugging
Enable debug logging:
import logging
logging.getLogger("ocpp").setLevel(logging.DEBUG)
Log Analysis
The implementation provides structured logging:
{
"timestamp": "2024-01-01T12:00:00Z",
"level": "INFO",
"logger": "ocpp.csms.server",
"message": "Message received",
"ocpp_message_type": "AuthorizeRequest",
"ocpp_direction": "request",
"charging_station_id": "CP001"
}
Contributing
Code Style
- Follow PEP 8 guidelines
- Use type hints
- Add comprehensive comments
- Include docstrings
Testing
- Write unit tests for new features
- Update integration tests
- Ensure all tests pass
Documentation
- Update README.md
- Add code comments
- Update API documentation
License
This implementation is provided for educational purposes. Please refer to the OCPP 2.1 specification for official licensing terms.
References
Support
For questions and support: - Review the documentation - Check the examples - Run the integration tests - Examine the logs
Future Enhancements
- Database Integration: Persistent storage
- REST API: HTTP interface
- MQTT Support: MQTT transport
- Load Balancing: Multiple server instances
- Metrics: Prometheus integration
- Dashboard: Web-based monitoring
- Mobile App: Mobile interface
- Cloud Integration: Cloud deployment