Skip to main content

Спецификация OCPP модуля для зарядных станций

1. Обзор задачи

1.1 Архитектура взаимодействия

graph TB
    subgraph "Backend Infrastructure"
        CSMS[Central System Management Service]
    end
    
    subgraph "EV Charging Station"
        subgraph "Ваша зона ответственности"
            OCPP[OCPP Communication Module]
            WS[WebSocket Client]
            PARSER[Message Parser/Generator]
            QUEUE[Message Queue]
        end
        
        subgraph "Station System (существующее)"
            STATION[Station Controller]
            HARDWARE[Hardware Controllers]
        end
    end
    
    CSMS <--> WS
    WS <--> OCPP
    OCPP <--> PARSER
    OCPP <--> QUEUE
    OCPP <--> STATION
    STATION <--> HARDWARE

1.2 Задача модуля

Основная функция: Обеспечить двустороннюю связь между зарядной станцией и CSMS по протоколу OCPP 2.0.1

Интерфейсы:

  • Внешний: WebSocket соединение с CSMS
  • Внутренний: API для интеграции с системой станции

2. Интерфейс OCPP модуля

2.1 API для интеграции с системой станции

flowchart LR
    subgraph "Station System"
        CONTROLLER[Station Controller]
    end
    
    subgraph "OCPP Module API"
        direction TB
        IN[Incoming Events]
        OUT[Outgoing Commands]
        STATUS[Status Queries]
        CONFIG[Configuration]
    end
    
    subgraph "CSMS"
        BACKEND[Backend Server]
    end
    
    CONTROLLER -->|Events| IN
    OUT -->|Commands| CONTROLLER
    CONTROLLER -->|Query| STATUS
    CONTROLLER -->|Setup| CONFIG
    
    IN -.->|OCPP Messages| BACKEND
    BACKEND -.->|OCPP Messages| OUT

2.2 Входящие события от станции

{
  "eventType": "station_event",
  "events": [
    {
      "type": "cable_connected",
      "evseId": 1,
      "connectorId": 1,
      "timestamp": "2025-07-12T10:30:00Z"
    },
    {
      "type": "rfid_scanned", 
      "rfidToken": "RFID_12345",
      "evseId": 1,
      "timestamp": "2025-07-12T10:30:00Z"
    },
    {
      "type": "charging_started",
      "transactionId": "TXN_123",
      "evseId": 1,
      "connectorId": 1,
      "timestamp": "2025-07-12T10:30:00Z"
    },
    {
      "type": "meter_reading",
      "evseId": 1,
      "readings": {
        "energy": 5.2,
        "power": 7.2,
        "voltage": 230.5,
        "current": 31.2
      },
      "timestamp": "2025-07-12T10:31:00Z"
    },
    {
      "type": "charging_stopped",
      "transactionId": "TXN_123", 
      "reason": "user_stopped",
      "finalEnergy": 8.5,
      "timestamp": "2025-07-12T10:45:00Z"
    },
    {
      "type": "error_detected",
      "errorCode": "connector_lock_failure",
      "severity": "alert",
      "component": "charging_connector",
      "timestamp": "2025-07-12T10:35:00Z"
    },
    {
      "type": "status_changed",
      "evseId": 1,
      "connectorId": 1,
      "newStatus": "available",
      "timestamp": "2025-07-12T10:30:00Z"
    }
  ]
}

2.3 Исходящие команды к станции

{
  "commandType": "csms_command",
  "commands": [
    {
      "type": "authorize_user",
      "rfidToken": "RFID_12345",
      "authStatus": "accepted",
      "expiryDate": "2025-12-31T23:59:59Z"
    },
    {
      "type": "start_charging",
      "evseId": 1,
      "rfidToken": "RFID_12345",
      "chargingProfile": {
        "maxPower": 7200,
        "phases": 1
      }
    },
    {
      "type": "stop_charging",
      "transactionId": "TXN_123",
      "reason": "remote_stop"
    },
    {
      "type": "request_data",
      "dataType": "battery_status",
      "requestId": "REQ_001"
    },
    {
      "type": "update_configuration",
      "parameters": {
        "heartbeatInterval": 300,
        "meterValueSampleInterval": 60
      }
    },
    {
      "type": "reset_station",
      "resetType": "soft"
    }
  ]
}

3. OCPP Communication Flow

3.1 Установка соединения

sequenceDiagram
    participant Station as Station System
    participant OCPP as OCPP Module
    participant CSMS as CSMS Server
    
    Station->>OCPP: Initialize Connection
    Note over OCPP: Config: server URL, API key, station ID
    
    OCPP->>CSMS: WebSocket Connect
    Note over OCPP,CSMS: wss://csms.server.com/ocpp/{stationId}<br/>Authorization: Bearer {apiKey}
    
    CSMS->>OCPP: Connection Accepted
    
    OCPP->>CSMS: BootNotification
    Note over OCPP: Station info, firmware version
    
    CSMS->>OCPP: BootNotification Response
    Note over CSMS: Status: Accepted, Heartbeat interval
    
    OCPP->>Station: Connection Established
    
    loop Heartbeat
        OCPP->>CSMS: Heartbeat (every interval)
        CSMS->>OCPP: Heartbeat Response
    end

3.2 Обработка событий станции

sequenceDiagram
    participant Station as Station System
    participant OCPP as OCPP Module  
    participant CSMS as CSMS Server
    
    Note over Station,CSMS: Пользователь подключил кабель
    Station->>OCPP: cable_connected event
    OCPP->>CSMS: StatusNotification (Preparing)
    CSMS->>OCPP: StatusNotification Response
    
    Note over Station,CSMS: Пользователь приложил RFID
    Station->>OCPP: rfid_scanned event
    OCPP->>CSMS: Authorize
    CSMS->>OCPP: Authorize Response (Accepted)
    OCPP->>Station: authorize_user command
    
    Note over Station,CSMS: Станция начала зарядку
    Station->>OCPP: charging_started event
    OCPP->>CSMS: TransactionEvent (Started)
    CSMS->>OCPP: TransactionEvent Response
    
    Note over Station,CSMS: Периодические показания счетчика
    loop Every 60 seconds
        Station->>OCPP: meter_reading event
        OCPP->>CSMS: MeterValues
        CSMS->>OCPP: MeterValues Response
    end

3.3 Обработка команд от CSMS

sequenceDiagram
    participant CSMS as CSMS Server
    participant OCPP as OCPP Module
    participant Station as Station System
    
    Note over CSMS,Station: Удаленный запуск зарядки
    CSMS->>OCPP: RemoteStartTransaction
    OCPP->>Station: start_charging command
    Station->>OCPP: Command accepted
    OCPP->>CSMS: RemoteStartTransaction Response (Accepted)
    
    Note over CSMS,Station: Запрос данных о батарее
    CSMS->>OCPP: GetReport (Battery)
    OCPP->>Station: request_data command
    Station->>OCPP: Data response
    OCPP->>CSMS: GetReport Response
    OCPP->>CSMS: NotifyReport (Battery data)

4. Детальная спецификация OCPP сообщений

4.1 Исходящие сообщения (Station → CSMS)

BootNotification (при запуске)

{
  "reason": "PowerUp",
  "chargingStation": {
    "model": "получить_от_station_system",
    "vendorName": "получить_от_station_system", 
    "firmwareVersion": "получить_от_station_system",
    "serialNumber": "получить_от_station_system"
  }
}

StatusNotification (при изменении статуса)

{
  "timestamp": "получить_от_station_system",
  "connectorStatus": "Available|Preparing|Charging|SuspendedEVSE|SuspendedEV|Finishing|Reserved|Unavailable|Faulted",
  "evseId": "получить_от_station_system",
  "connectorId": "получить_от_station_system"
}

TransactionEvent (события транзакции)

{
  "eventType": "Started|Updated|Ended", 
  "timestamp": "получить_от_station_system",
  "triggerReason": "Authorized|CablePluggedIn|ChargingRateChanged|ChargingStateChanged|Deauthorized|EnergyLimitReached|EVCommunicationLost|EVConnectTimeout|MeterValueClock|MeterValuePeriodic|TimeLimitReached|Trigger|UnlockCommand|StopAuthorized|EVDeparted|EVDetected|RemoteStop|RemoteStart|AbnormalCondition|SignedDataReceived|ResetCommand",
  "seqNo": "incremental_number",
  "transactionInfo": {
    "transactionId": "получить_от_station_system",
    "chargingState": "Charging|EVConnected|SuspendedEV|SuspendedEVSE|Idle"
  },
  "evse": {
    "id": "получить_от_station_system",
    "connectorId": "получить_от_station_system"
  },
  "idToken": {
    "idToken": "получить_от_station_system",
    "type": "ISO14443|ISO15693|KeyCode|Local|MacAddress|NoAuthorization"
  },
  "meterValue": [
    {
      "timestamp": "получить_от_station_system",
      "sampledValue": [
        {
          "value": "получить_от_station_system",
          "measurand": "Energy.Active.Import.Register|Power.Active.Import|Voltage|Current.Import|Temperature",
          "unit": "kWh|kW|V|A|Celsius"
        }
      ]
    }
  ]
}

MeterValues (телеметрия)

{
  "evseId": "получить_от_station_system",
  "meterValue": [
    {
      "timestamp": "получить_от_station_system",
      "sampledValue": [
        {
          "value": "получить_от_station_system",
          "measurand": "Energy.Active.Import.Register|Power.Active.Import|Voltage|Current.Import|Temperature",
          "unit": "kWh|kW|V|A|Celsius"
        }
      ]
    }
  ]
}

NotifyEvent (ошибки и события)

{
  "generatedAt": "текущее_время",
  "eventData": [
    {
      "eventId": "уникальный_id",
      "timestamp": "получить_от_station_system",
      "trigger": "Alerting|Delta|Periodic",
      "eventType": "получить_от_station_system",
      "component": {
        "name": "получить_от_station_system"
      },
      "variable": {
        "name": "получить_от_station_system"
      },
      "eventNotificationType": "HardWiredNotification|HardWiredMonitor|PreconfiguredMonitor|CustomMonitor"
    }
  ]
}

Authorize (авторизация)

{
  "idToken": {
    "idToken": "получить_от_station_system",
    "type": "ISO14443|ISO15693|KeyCode|Local|MacAddress|NoAuthorization"
  },
  "evseId": "получить_от_station_system"
}

4.2 Входящие сообщения (CSMS → Station)

RemoteStartTransaction

Получили от CSMS:

{
  "idToken": {
    "idToken": "RFID_12345",
    "type": "ISO14443"
  },
  "evseId": 1,
  "chargingProfile": {
    "id": 1,
    "stackLevel": 0,
    "chargingProfilePurpose": "TxProfile",
    "chargingProfileKind": "Absolute",
    "chargingSchedule": [
      {
        "id": 1,
        "startSchedule": "2025-07-12T10:30:00Z",
        "duration": 3600,
        "chargingRateUnit": "W",
        "chargingSchedulePeriod": [
          {
            "startPeriod": 0,
            "limit": 7200
          }
        ]
      }
    ]
  }
}

Отправить в station_system:

{
  "type": "start_charging",
  "evseId": 1,
  "rfidToken": "RFID_12345", 
  "maxPower": 7200,
  "duration": 3600
}

Ответ CSMS:

{
  "status": "Accepted|Rejected",
  "statusInfo": {
    "reasonCode": "NoError|Busy|Occupied|Faulted"
  }
}

RemoteStopTransaction

Получили от CSMS:

{
  "transactionId": "TXN_123456"
}

Отправить в station_system:

{
  "type": "stop_charging",
  "transactionId": "TXN_123456",
  "reason": "remote_stop"
}

GetReport

Получили от CSMS:

{
  "requestId": 1,
  "componentVariable": [
    {
      "component": {"name": "BatteryManagement"},
      "variable": {"name": "StateOfCharge"}
    }
  ]
}

Отправить в station_system:

{
  "type": "request_data",
  "requestId": 1,
  "dataType": "battery_status"
}

Получить от station_system:

{
  "requestId": 1,
  "batteryLevel": 85,
  "batteryVoltage": 48.2,
  "batteryTemperature": 25.5
}

Отправить CSMS (NotifyReport):

{
  "requestId": 1,
  "generatedAt": "текущее_время",
  "reportData": [
    {
      "component": {"name": "BatteryManagement"},
      "variable": {"name": "StateOfCharge"},
      "variableAttribute": {
        "value": "85",
        "unit": "Percent"
      }
    }
  ]
}

5. Обработка ошибок и переподключение

5.1 Стратегия переподключения

flowchart TD
    DISCONNECT[Connection Lost] --> LOG[Log Disconnect Event]
    LOG --> QUEUE[Queue Outgoing Messages]
    QUEUE --> WAIT[Wait Period]
    WAIT --> RETRY[Attempt Reconnection]
    RETRY --> SUCCESS{Connected?}
    
    SUCCESS -->|Yes| BOOT[Send BootNotification]
    SUCCESS -->|No| BACKOFF[Increase Wait Period]
    
    BACKOFF --> MAXWAIT{Max Wait Reached?}
    MAXWAIT -->|No| WAIT
    MAXWAIT -->|Yes| RESET[Reset Wait Period]
    RESET --> WAIT
    
    BOOT --> SYNC[Send Queued Messages]
    SYNC --> OPERATIONAL[Operational Mode]

5.2 Обработка таймаутов

sequenceDiagram
    participant OCPP as OCPP Module
    participant CSMS as CSMS Server
    participant Station as Station System
    
    OCPP->>CSMS: Request Message
    Note over OCPP: Start 30s timeout timer
    
    alt Response received
        CSMS->>OCPP: Response Message
        Note over OCPP: Clear timeout, process response
    else Timeout occurred
        Note over OCPP: 30s elapsed, no response
        OCPP->>Station: Notify timeout error
        OCPP->>OCPP: Queue message for retry
    end

6. Конфигурация модуля

6.1 Параметры подключения

{
  "connection": {
    "serverUrl": "wss://csms.example.com/ocpp",
    "stationId": "STATION_001",
    "apiKey": "your-api-key-here",
    "reconnectInterval": 30,
    "maxReconnectInterval": 300,
    "messageTimeout": 30,
    "heartbeatInterval": 300
  },
  "station": {
    "model": "EV-CHARGER-V1",
    "vendorName": "YourCompany",
    "serialNumber": "SN123456789",
    "firmwareVersion": "1.0.0"
  },
  "intervals": {
    "meterValueSampleInterval": 60,
    "clockAlignedDataInterval": 900,
    "connectionTimeOut": 60
  }
}

6.2 Методы управления

// Псевдокод API модуля
class OCPPModule {
    // Инициализация
    initialize(config) { }
    
    // Управление соединением
    connect() { }
    disconnect() { }
    isConnected() { }
    
    // Отправка событий от станции
    sendStationEvent(event) { }
    
    // Получение команд для станции (callback)
    onStationCommand(callback) { }
    
    // Статус модуля
    getStatus() { }
    getLastError() { }
    
    // Логирование
    enableLogging(level) { }
}

7. Протокол взаимодействия с системой станции

7.1 Инициализация модуля

sequenceDiagram
    participant Station as Station System
    participant OCPP as OCPP Module
    
    Station->>OCPP: Initialize(config)
    OCPP->>OCPP: Load configuration
    OCPP->>Station: Initialization complete
    
    Station->>OCPP: SetEventHandler(callback)
    OCPP->>Station: Handler registered
    
    Station->>OCPP: Connect()
    OCPP->>OCPP: Establish WebSocket connection
    OCPP->>Station: onStationCommand("connection_established")

7.2 Обработка событий в runtime

sequenceDiagram
    participant Station as Station System
    participant OCPP as OCPP Module
    participant CSMS as CSMS Server
    
    Note over Station,CSMS: Обычный поток событий
    Station->>OCPP: sendStationEvent(cable_connected)
    OCPP->>CSMS: StatusNotification
    CSMS->>OCPP: StatusNotification Response
    
    Note over Station,CSMS: Команда от CSMS
    CSMS->>OCPP: RemoteStartTransaction
    OCPP->>Station: onStationCommand(start_charging)
    Station->>OCPP: Command response (accepted)
    OCPP->>CSMS: RemoteStartTransaction Response

Данная спецификация определяет требования к модулю OCPP коммуникации для интеграции с системой зарядной станции.