-// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
+// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
-import {
- AuthorizeRequest,
- OCPP16AuthorizeResponse,
- OCPP16StartTransactionResponse,
- OCPP16StopTransactionReason,
- OCPP16StopTransactionResponse,
- StartTransactionRequest,
- StopTransactionRequest,
-} from '../../../types/ocpp/1.6/Transaction';
-import {
- DiagnosticsStatusNotificationRequest,
- HeartbeatRequest,
- OCPP16BootNotificationRequest,
- OCPP16RequestCommand,
- StatusNotificationRequest,
-} from '../../../types/ocpp/1.6/Requests';
-import { MeterValuesRequest, OCPP16MeterValue } from '../../../types/ocpp/1.6/MeterValues';
+import type { JSONSchemaType } from 'ajv';
-import type ChargingStation from '../../ChargingStation';
-import Constants from '../../../utils/Constants';
-import { ErrorType } from '../../../types/ocpp/ErrorType';
-import { JsonType } from '../../../types/JsonType';
-import { OCPP16BootNotificationResponse } from '../../../types/ocpp/1.6/Responses';
-import { OCPP16ChargePointErrorCode } from '../../../types/ocpp/1.6/ChargePointErrorCode';
-import { OCPP16ChargePointStatus } from '../../../types/ocpp/1.6/ChargePointStatus';
-import { OCPP16DiagnosticsStatus } from '../../../types/ocpp/1.6/DiagnosticsStatus';
+import { OCPP16Constants } from './OCPP16Constants';
import { OCPP16ServiceUtils } from './OCPP16ServiceUtils';
-import OCPPError from '../../../exception/OCPPError';
-import OCPPRequestService from '../OCPPRequestService';
-import type OCPPResponseService from '../OCPPResponseService';
-import { SendParams } from '../../../types/ocpp/Requests';
-import Utils from '../../../utils/Utils';
+import type { ChargingStation } from '../../../charging-station';
+import { OCPPError } from '../../../exception';
+import {
+ ErrorType,
+ type JsonObject,
+ type JsonType,
+ type OCPP16AuthorizeRequest,
+ type OCPP16BootNotificationRequest,
+ OCPP16ChargePointStatus,
+ type OCPP16DataTransferRequest,
+ type OCPP16DiagnosticsStatusNotificationRequest,
+ type OCPP16FirmwareStatusNotificationRequest,
+ type OCPP16HeartbeatRequest,
+ type OCPP16MeterValuesRequest,
+ OCPP16RequestCommand,
+ type OCPP16StartTransactionRequest,
+ type OCPP16StatusNotificationRequest,
+ type OCPP16StopTransactionRequest,
+ OCPPVersion,
+ type RequestParams,
+} from '../../../types';
+import { Constants, generateUUID } from '../../../utils';
+import { OCPPRequestService } from '../OCPPRequestService';
+import type { OCPPResponseService } from '../OCPPResponseService';
const moduleName = 'OCPP16RequestService';
-export default class OCPP16RequestService extends OCPPRequestService {
- public constructor(chargingStation: ChargingStation, ocppResponseService: OCPPResponseService) {
- if (new.target?.name === moduleName) {
- throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
- }
- super(chargingStation, ocppResponseService);
- }
-
- public async sendHeartbeat(params?: SendParams): Promise<void> {
- const payload: HeartbeatRequest = {};
- await this.sendMessage(Utils.generateUUID(), payload, OCPP16RequestCommand.HEARTBEAT, params);
- }
-
- public async sendBootNotification(
- chargePointModel: string,
- chargePointVendor: string,
- chargeBoxSerialNumber?: string,
- firmwareVersion?: string,
- chargePointSerialNumber?: string,
- iccid?: string,
- imsi?: string,
- meterSerialNumber?: string,
- meterType?: string,
- params?: SendParams
- ): Promise<OCPP16BootNotificationResponse> {
- const payload: OCPP16BootNotificationRequest = {
- chargePointModel,
- chargePointVendor,
- ...(!Utils.isUndefined(chargeBoxSerialNumber) && { chargeBoxSerialNumber }),
- ...(!Utils.isUndefined(chargePointSerialNumber) && { chargePointSerialNumber }),
- ...(!Utils.isUndefined(firmwareVersion) && { firmwareVersion }),
- ...(!Utils.isUndefined(iccid) && { iccid }),
- ...(!Utils.isUndefined(imsi) && { imsi }),
- ...(!Utils.isUndefined(meterSerialNumber) && { meterSerialNumber }),
- ...(!Utils.isUndefined(meterType) && { meterType }),
- };
- return (await this.sendMessage(
- Utils.generateUUID(),
- payload,
- OCPP16RequestCommand.BOOT_NOTIFICATION,
- { ...params, skipBufferingOnError: true }
- )) as OCPP16BootNotificationResponse;
- }
-
- public async sendStatusNotification(
- connectorId: number,
- status: OCPP16ChargePointStatus,
- errorCode: OCPP16ChargePointErrorCode = OCPP16ChargePointErrorCode.NO_ERROR
- ): Promise<void> {
- const payload: StatusNotificationRequest = {
- connectorId,
- errorCode,
- status,
- };
- await this.sendMessage(Utils.generateUUID(), payload, OCPP16RequestCommand.STATUS_NOTIFICATION);
- }
-
- public async sendAuthorize(
- connectorId: number,
- idTag?: string
- ): Promise<OCPP16AuthorizeResponse> {
- const payload: AuthorizeRequest = {
- ...(!Utils.isUndefined(idTag) ? { idTag } : { idTag: Constants.DEFAULT_IDTAG }),
- };
- this.chargingStation.getConnectorStatus(connectorId).authorizeIdTag = idTag;
- return (await this.sendMessage(
- Utils.generateUUID(),
- payload,
- OCPP16RequestCommand.AUTHORIZE
- )) as OCPP16AuthorizeResponse;
- }
-
- public async sendStartTransaction(
- connectorId: number,
- idTag?: string
- ): Promise<OCPP16StartTransactionResponse> {
- const payload: StartTransactionRequest = {
- connectorId,
- ...(!Utils.isUndefined(idTag) ? { idTag } : { idTag: Constants.DEFAULT_IDTAG }),
- meterStart: this.chargingStation.getEnergyActiveImportRegisterByConnectorId(connectorId),
- timestamp: new Date().toISOString(),
- };
- return (await this.sendMessage(
- Utils.generateUUID(),
- payload,
- OCPP16RequestCommand.START_TRANSACTION
- )) as OCPP16StartTransactionResponse;
- }
+export class OCPP16RequestService extends OCPPRequestService {
+ protected jsonSchemas: Map<OCPP16RequestCommand, JSONSchemaType<JsonType>>;
- public async sendStopTransaction(
- transactionId: number,
- meterStop: number,
- idTag?: string,
- reason: OCPP16StopTransactionReason = OCPP16StopTransactionReason.NONE
- ): Promise<OCPP16StopTransactionResponse> {
- let connectorId: number;
- for (const id of this.chargingStation.connectors.keys()) {
- if (id > 0 && this.chargingStation.getConnectorStatus(id)?.transactionId === transactionId) {
- connectorId = id;
- break;
- }
- }
- const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
- this.chargingStation,
- connectorId,
- meterStop
- );
- // FIXME: should be a callback, each OCPP commands implementation must do only one job
- this.chargingStation.getBeginEndMeterValues() &&
- this.chargingStation.getOcppStrictCompliance() &&
- !this.chargingStation.getOutOfOrderEndMeterValues() &&
- (await this.sendTransactionEndMeterValues(
- connectorId,
- transactionId,
- transactionEndMeterValue
- ));
- const payload: StopTransactionRequest = {
- transactionId,
- ...(!Utils.isUndefined(idTag) && { idTag }),
- meterStop,
- timestamp: new Date().toISOString(),
- ...(reason && { reason }),
- ...(this.chargingStation.getTransactionDataMeterValues() && {
- transactionData: OCPP16ServiceUtils.buildTransactionDataMeterValues(
- this.chargingStation.getConnectorStatus(connectorId).transactionBeginMeterValue,
- transactionEndMeterValue
+ public constructor(ocppResponseService: OCPPResponseService) {
+ // if (new.target?.name === moduleName) {
+ // throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
+ // }
+ super(OCPPVersion.VERSION_16, ocppResponseService);
+ this.jsonSchemas = new Map<OCPP16RequestCommand, JSONSchemaType<JsonType>>([
+ [
+ OCPP16RequestCommand.AUTHORIZE,
+ OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16AuthorizeRequest>(
+ 'assets/json-schemas/ocpp/1.6/Authorize.json',
+ moduleName,
+ 'constructor',
),
- }),
- };
- return (await this.sendMessage(
- Utils.generateUUID(),
- payload,
- OCPP16RequestCommand.STOP_TRANSACTION
- )) as OCPP16StartTransactionResponse;
- }
-
- public async sendMeterValues(
- connectorId: number,
- transactionId: number,
- interval: number
- ): Promise<void> {
- const meterValue = OCPP16ServiceUtils.buildMeterValue(
- this.chargingStation,
- connectorId,
- transactionId,
- interval
- );
- const payload: MeterValuesRequest = {
- connectorId,
- transactionId,
- meterValue: [meterValue],
- };
- await this.sendMessage(Utils.generateUUID(), payload, OCPP16RequestCommand.METER_VALUES);
- }
-
- public async sendTransactionBeginMeterValues(
- connectorId: number,
- transactionId: number,
- beginMeterValue: OCPP16MeterValue
- ): Promise<void> {
- const payload: MeterValuesRequest = {
- connectorId,
- transactionId,
- meterValue: [beginMeterValue],
- };
- await this.sendMessage(Utils.generateUUID(), payload, OCPP16RequestCommand.METER_VALUES);
- }
-
- public async sendTransactionEndMeterValues(
- connectorId: number,
- transactionId: number,
- endMeterValue: OCPP16MeterValue
- ): Promise<void> {
- const payload: MeterValuesRequest = {
- connectorId,
- transactionId,
- meterValue: [endMeterValue],
- };
- await this.sendMessage(Utils.generateUUID(), payload, OCPP16RequestCommand.METER_VALUES);
+ ],
+ [
+ OCPP16RequestCommand.BOOT_NOTIFICATION,
+ OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16BootNotificationRequest>(
+ 'assets/json-schemas/ocpp/1.6/BootNotification.json',
+ moduleName,
+ 'constructor',
+ ),
+ ],
+ [
+ OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION,
+ OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DiagnosticsStatusNotificationRequest>(
+ 'assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotification.json',
+ moduleName,
+ 'constructor',
+ ),
+ ],
+ [
+ OCPP16RequestCommand.HEARTBEAT,
+ OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16HeartbeatRequest>(
+ 'assets/json-schemas/ocpp/1.6/Heartbeat.json',
+ moduleName,
+ 'constructor',
+ ),
+ ],
+ [
+ OCPP16RequestCommand.METER_VALUES,
+ OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16MeterValuesRequest>(
+ 'assets/json-schemas/ocpp/1.6/MeterValues.json',
+ moduleName,
+ 'constructor',
+ ),
+ ],
+ [
+ OCPP16RequestCommand.STATUS_NOTIFICATION,
+ OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StatusNotificationRequest>(
+ 'assets/json-schemas/ocpp/1.6/StatusNotification.json',
+ moduleName,
+ 'constructor',
+ ),
+ ],
+ [
+ OCPP16RequestCommand.START_TRANSACTION,
+ OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StartTransactionRequest>(
+ 'assets/json-schemas/ocpp/1.6/StartTransaction.json',
+ moduleName,
+ 'constructor',
+ ),
+ ],
+ [
+ OCPP16RequestCommand.STOP_TRANSACTION,
+ OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StopTransactionRequest>(
+ 'assets/json-schemas/ocpp/1.6/StopTransaction.json',
+ moduleName,
+ 'constructor',
+ ),
+ ],
+ [
+ OCPP16RequestCommand.DATA_TRANSFER,
+ OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferRequest>(
+ 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
+ moduleName,
+ 'constructor',
+ ),
+ ],
+ [
+ OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION,
+ OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16FirmwareStatusNotificationRequest>(
+ 'assets/json-schemas/ocpp/1.6/FirmwareStatusNotification.json',
+ moduleName,
+ 'constructor',
+ ),
+ ],
+ ]);
+ this.buildRequestPayload = this.buildRequestPayload.bind(this) as <Request extends JsonType>(
+ chargingStation: ChargingStation,
+ commandName: OCPP16RequestCommand,
+ commandParams?: JsonType,
+ ) => Request;
}
- public async sendDiagnosticsStatusNotification(
- diagnosticsStatus: OCPP16DiagnosticsStatus
- ): Promise<void> {
- const payload: DiagnosticsStatusNotificationRequest = {
- status: diagnosticsStatus,
- };
- await this.sendMessage(
- Utils.generateUUID(),
- payload,
- OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
+ public async requestHandler<RequestType extends JsonType, ResponseType extends JsonType>(
+ chargingStation: ChargingStation,
+ commandName: OCPP16RequestCommand,
+ commandParams?: JsonType,
+ params?: RequestParams,
+ ): Promise<ResponseType> {
+ // FIXME?: add sanity checks on charging station availability, connector availability, connector status, etc.
+ if (OCPP16ServiceUtils.isRequestCommandSupported(chargingStation, commandName) === true) {
+ return (await this.sendMessage(
+ chargingStation,
+ generateUUID(),
+ this.buildRequestPayload<RequestType>(chargingStation, commandName, commandParams),
+ commandName,
+ params,
+ )) as ResponseType;
+ }
+ // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
+ throw new OCPPError(
+ ErrorType.NOT_SUPPORTED,
+ `Unsupported OCPP command '${commandName}'`,
+ commandName,
+ commandParams,
);
}
- private buildCommandPayload(
+ private buildRequestPayload<Request extends JsonType>(
+ chargingStation: ChargingStation,
commandName: OCPP16RequestCommand,
- commandParams: JsonType
- ): JsonType {
+ commandParams?: JsonType,
+ ): Request {
+ let connectorId: number | undefined;
+ let energyActiveImportRegister: number;
+ commandParams = commandParams as JsonObject;
switch (commandName) {
- case OCPP16RequestCommand.AUTHORIZE:
- return {
- ...(!Utils.isUndefined(commandParams?.idTag)
- ? { idTag: commandParams.idTag }
- : { idTag: Constants.DEFAULT_IDTAG }),
- } as AuthorizeRequest;
case OCPP16RequestCommand.BOOT_NOTIFICATION:
- return {
- chargePointModel: commandParams?.chargePointModel,
- chargePointVendor: commandParams?.chargePointVendor,
- ...(!Utils.isUndefined(commandParams?.chargeBoxSerialNumber) && {
- chargeBoxSerialNumber: commandParams.chargeBoxSerialNumber,
- }),
- ...(!Utils.isUndefined(commandParams?.chargePointSerialNumber) && {
- chargePointSerialNumber: commandParams.chargePointSerialNumber,
- }),
- ...(!Utils.isUndefined(commandParams?.firmwareVersion) && {
- firmwareVersion: commandParams.firmwareVersion,
- }),
- ...(!Utils.isUndefined(commandParams?.iccid) && { iccid: commandParams.iccid }),
- ...(!Utils.isUndefined(commandParams?.imsi) && { imsi: commandParams.imsi }),
- ...(!Utils.isUndefined(commandParams?.meterSerialNumber) && {
- meterSerialNumber: commandParams.meterSerialNumber,
- }),
- ...(!Utils.isUndefined(commandParams?.meterType) && {
- meterType: commandParams.meterType,
- }),
- } as OCPP16BootNotificationRequest;
case OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION:
- return {
- status: commandParams?.diagnosticsStatus,
- } as DiagnosticsStatusNotificationRequest;
- case OCPP16RequestCommand.HEARTBEAT:
- return {} as HeartbeatRequest;
+ case OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION:
case OCPP16RequestCommand.METER_VALUES:
- return {
- connectorId: commandParams?.connectorId,
- transactionId: commandParams?.transactionId,
- meterValue: Array.isArray(commandParams?.meterValues)
- ? commandParams?.meterValues
- : [commandParams?.meterValue],
- } as MeterValuesRequest;
case OCPP16RequestCommand.STATUS_NOTIFICATION:
+ case OCPP16RequestCommand.DATA_TRANSFER:
+ return commandParams as unknown as Request;
+ case OCPP16RequestCommand.AUTHORIZE:
return {
- connectorId: commandParams?.connectorId,
- errorCode: commandParams?.errorCode,
- status: commandParams?.status,
- } as StatusNotificationRequest;
+ idTag: Constants.DEFAULT_IDTAG,
+ ...commandParams,
+ } as unknown as Request;
+ case OCPP16RequestCommand.HEARTBEAT:
+ return OCPP16Constants.OCPP_REQUEST_EMPTY as unknown as Request;
case OCPP16RequestCommand.START_TRANSACTION:
return {
- connectorId: commandParams?.connectorId,
- ...(!Utils.isUndefined(commandParams?.idTag)
- ? { idTag: commandParams?.idTag }
- : { idTag: Constants.DEFAULT_IDTAG }),
- meterStart: this.chargingStation.getEnergyActiveImportRegisterByConnectorId(
- commandParams?.connectorId as number
+ idTag: Constants.DEFAULT_IDTAG,
+ meterStart: chargingStation.getEnergyActiveImportRegisterByConnectorId(
+ commandParams?.connectorId as number,
+ true,
),
- timestamp: new Date().toISOString(),
- } as StartTransactionRequest;
+ timestamp: new Date(),
+ ...(OCPP16ServiceUtils.hasReservation(
+ chargingStation,
+ commandParams?.connectorId as number,
+ commandParams?.idTag as string,
+ ) && {
+ reservationId: chargingStation.getReservationBy(
+ 'connectorId',
+ chargingStation.getConnectorStatus(0)?.status === OCPP16ChargePointStatus.Reserved
+ ? 0
+ : (commandParams?.connectorId as number),
+ )!.reservationId,
+ }),
+ ...commandParams,
+ } as unknown as Request;
case OCPP16RequestCommand.STOP_TRANSACTION:
+ chargingStation.stationInfo?.transactionDataMeterValues &&
+ (connectorId = chargingStation.getConnectorIdByTransactionId(
+ commandParams?.transactionId as number,
+ )!);
+ energyActiveImportRegister = chargingStation.getEnergyActiveImportRegisterByTransactionId(
+ commandParams?.transactionId as number,
+ true,
+ );
return {
- transactionId: commandParams?.transactionId,
- ...(!Utils.isUndefined(commandParams?.idTag) && { idTag: commandParams.idTag }),
- meterStop: commandParams?.meterStop,
- timestamp: new Date().toISOString(),
- ...(commandParams?.reason && { reason: commandParams.reason }),
- ...(this.chargingStation.getTransactionDataMeterValues() && {
+ idTag: chargingStation.getTransactionIdTag(commandParams?.transactionId as number),
+ meterStop: energyActiveImportRegister,
+ timestamp: new Date(),
+ ...(chargingStation.stationInfo?.transactionDataMeterValues && {
transactionData: OCPP16ServiceUtils.buildTransactionDataMeterValues(
- this.chargingStation.getConnectorStatus(commandParams?.connectorId as number)
- .transactionBeginMeterValue,
+ chargingStation.getConnectorStatus(connectorId!)!.transactionBeginMeterValue!,
OCPP16ServiceUtils.buildTransactionEndMeterValue(
- this.chargingStation,
- commandParams?.connectorId as number,
- commandParams?.meterStop as number
- )
+ chargingStation,
+ connectorId!,
+ energyActiveImportRegister,
+ ),
),
}),
- } as StopTransactionRequest;
+ ...commandParams,
+ } as unknown as Request;
default:
+ // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
throw new OCPPError(
ErrorType.NOT_SUPPORTED,
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
- `Unsupported OCPP command: ${commandName}`,
+ `Unsupported OCPP command '${commandName}'`,
commandName,
- { commandName }
+ commandParams,
);
}
}