X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2Focpp%2FOCPPServiceUtils.ts;h=d09d8b1a1afaffc72b9891ab52f72b48f6282c69;hb=3dcf7b670fa7a199022988902032d4225f27865e;hp=ad78d347b965ddef05d06777388461cce61e6a2c;hpb=2329015067d5715c3eb0b56984a66cdc1fe31452;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ocpp/OCPPServiceUtils.ts b/src/charging-station/ocpp/OCPPServiceUtils.ts index ad78d347..d09d8b1a 100644 --- a/src/charging-station/ocpp/OCPPServiceUtils.ts +++ b/src/charging-station/ocpp/OCPPServiceUtils.ts @@ -1,16 +1,42 @@ -import type { DefinedError, ErrorObject } from 'ajv'; - -import BaseError from '../../exception/BaseError'; -import type { SampledValueTemplate } from '../../types/MeasurandPerPhaseSampledValueTemplates'; -import { StandardParametersKey } from '../../types/ocpp/Configuration'; -import { ErrorType } from '../../types/ocpp/ErrorType'; -import { MeterValueMeasurand, type MeterValuePhase } from '../../types/ocpp/MeterValues'; -import { IncomingRequestCommand, RequestCommand } from '../../types/ocpp/Requests'; -import Constants from '../../utils/Constants'; -import logger from '../../utils/Logger'; -import Utils from '../../utils/Utils'; -import type ChargingStation from '../ChargingStation'; -import { ChargingStationConfigurationUtils } from '../ChargingStationConfigurationUtils'; +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import type { DefinedError, ErrorObject, JSONSchemaType } from 'ajv'; +import { isDate } from 'date-fns'; + +import { OCPP16Constants } from './1.6/OCPP16Constants'; +import { OCPP20Constants } from './2.0/OCPP20Constants'; +import { OCPPConstants } from './OCPPConstants'; +import { type ChargingStation, getConfigurationKey } from '../../charging-station'; +import { BaseError } from '../../exception'; +import { + ChargePointErrorCode, + type ConnectorStatusEnum, + ErrorType, + FileType, + IncomingRequestCommand, + type JsonType, + MessageTrigger, + MessageType, + MeterValueMeasurand, + type MeterValuePhase, + type OCPP16StatusNotificationRequest, + type OCPP20StatusNotificationRequest, + OCPPVersion, + RequestCommand, + type SampledValueTemplate, + StandardParametersKey, + type StatusNotificationRequest, + type StatusNotificationResponse, +} from '../../types'; +import { + handleFileException, + isNotEmptyArray, + isNotEmptyString, + logPrefix, + logger, +} from '../../utils'; export class OCPPServiceUtils { protected constructor() { @@ -33,11 +59,24 @@ export class OCPPServiceUtils { return ErrorType.FORMAT_VIOLATION; } + public static getMessageTypeString(messageType: MessageType): string { + switch (messageType) { + case MessageType.CALL_MESSAGE: + return 'request'; + case MessageType.CALL_RESULT_MESSAGE: + return 'response'; + case MessageType.CALL_ERROR_MESSAGE: + return 'error'; + default: + return 'unknown'; + } + } + public static isRequestCommandSupported( chargingStation: ChargingStation, - command: RequestCommand + command: RequestCommand, ): boolean { - const isRequestCommand = Object.values(RequestCommand).includes(command); + const isRequestCommand = Object.values(RequestCommand).includes(command); if ( isRequestCommand === true && !chargingStation.stationInfo?.commandsSupport?.outgoingCommands @@ -55,9 +94,10 @@ export class OCPPServiceUtils { public static isIncomingRequestCommandSupported( chargingStation: ChargingStation, - command: IncomingRequestCommand + command: IncomingRequestCommand, ): boolean { - const isIncomingRequestCommand = Object.values(IncomingRequestCommand).includes(command); + const isIncomingRequestCommand = + Object.values(IncomingRequestCommand).includes(command); if ( isIncomingRequestCommand === true && !chargingStation.stationInfo?.commandsSupport?.incomingCommands @@ -73,67 +113,248 @@ export class OCPPServiceUtils { return false; } + public static isMessageTriggerSupported( + chargingStation: ChargingStation, + messageTrigger: MessageTrigger, + ): boolean { + const isMessageTrigger = Object.values(MessageTrigger).includes(messageTrigger); + if (isMessageTrigger === true && !chargingStation.stationInfo?.messageTriggerSupport) { + return true; + } else if (isMessageTrigger === true && chargingStation.stationInfo?.messageTriggerSupport) { + return chargingStation.stationInfo?.messageTriggerSupport[messageTrigger] ?? false; + } + logger.error( + `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`, + ); + return false; + } + + public static isConnectorIdValid( + chargingStation: ChargingStation, + ocppCommand: IncomingRequestCommand, + connectorId: number, + ): boolean { + if (connectorId < 0) { + logger.error( + `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector id ${connectorId}`, + ); + return false; + } + return true; + } + + public static convertDateToISOString(obj: T): void { + for (const key in obj) { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion + if (isDate(obj![key])) { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion + (obj![key] as string) = (obj![key] as Date).toISOString(); + // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion + } else if (obj![key] !== null && typeof obj![key] === 'object') { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion + OCPPServiceUtils.convertDateToISOString(obj![key] as T); + } + } + } + + public static buildStatusNotificationRequest( + chargingStation: ChargingStation, + connectorId: number, + status: ConnectorStatusEnum, + evseId?: number, + ): StatusNotificationRequest { + switch (chargingStation.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16) { + case OCPPVersion.VERSION_16: + return { + connectorId, + status, + errorCode: ChargePointErrorCode.NO_ERROR, + } as OCPP16StatusNotificationRequest; + case OCPPVersion.VERSION_20: + case OCPPVersion.VERSION_201: + return { + timestamp: new Date(), + connectorStatus: status, + connectorId, + evseId, + } as OCPP20StatusNotificationRequest; + default: + throw new BaseError('Cannot build status notification payload: OCPP version not supported'); + } + } + + public static startHeartbeatInterval(chargingStation: ChargingStation, interval: number): void { + if (!chargingStation.heartbeatSetInterval) { + chargingStation.startHeartbeat(); + } else if (chargingStation.getHeartbeatInterval() !== interval) { + chargingStation.restartHeartbeat(); + } + } + + public static async sendAndSetConnectorStatus( + chargingStation: ChargingStation, + connectorId: number, + status: ConnectorStatusEnum, + evseId?: number, + options?: { send: boolean }, + ) { + options = { send: true, ...options }; + if (options.send) { + OCPPServiceUtils.checkConnectorStatusTransition(chargingStation, connectorId, status); + await chargingStation.ocppRequestService.requestHandler< + StatusNotificationRequest, + StatusNotificationResponse + >( + chargingStation, + RequestCommand.STATUS_NOTIFICATION, + OCPPServiceUtils.buildStatusNotificationRequest( + chargingStation, + connectorId, + status, + evseId, + ), + ); + } + chargingStation.getConnectorStatus(connectorId)!.status = status; + } + + protected static checkConnectorStatusTransition( + chargingStation: ChargingStation, + connectorId: number, + status: ConnectorStatusEnum, + ): boolean { + const fromStatus = chargingStation.getConnectorStatus(connectorId)!.status; + let transitionAllowed = false; + switch (chargingStation.stationInfo.ocppVersion) { + case OCPPVersion.VERSION_16: + if ( + (connectorId === 0 && + OCPP16Constants.ChargePointStatusChargingStationTransitions.findIndex( + (transition) => transition.from === fromStatus && transition.to === status, + ) !== -1) || + (connectorId > 0 && + OCPP16Constants.ChargePointStatusConnectorTransitions.findIndex( + (transition) => transition.from === fromStatus && transition.to === status, + ) !== -1) + ) { + transitionAllowed = true; + } + break; + case OCPPVersion.VERSION_20: + case OCPPVersion.VERSION_201: + if ( + (connectorId === 0 && + OCPP20Constants.ChargingStationStatusTransitions.findIndex( + (transition) => transition.from === fromStatus && transition.to === status, + ) !== -1) || + (connectorId > 0 && + OCPP20Constants.ConnectorStatusTransitions.findIndex( + (transition) => transition.from === fromStatus && transition.to === status, + ) !== -1) + ) { + transitionAllowed = true; + } + break; + default: + throw new BaseError( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + `Cannot check connector status transition: OCPP version ${chargingStation.stationInfo.ocppVersion} not supported`, + ); + } + if (transitionAllowed === false) { + logger.warn( + `${chargingStation.logPrefix()} OCPP ${ + chargingStation.stationInfo.ocppVersion + } connector id ${connectorId} status transition from '${ + chargingStation.getConnectorStatus(connectorId)!.status + }' to '${status}' is not allowed`, + ); + } + return transitionAllowed; + } + + protected static parseJsonSchemaFile( + relativePath: string, + ocppVersion: OCPPVersion, + moduleName?: string, + methodName?: string, + ): JSONSchemaType { + const filePath = join(dirname(fileURLToPath(import.meta.url)), relativePath); + try { + return JSON.parse(readFileSync(filePath, 'utf8')) as JSONSchemaType; + } catch (error) { + handleFileException( + filePath, + FileType.JsonSchema, + error as NodeJS.ErrnoException, + OCPPServiceUtils.logPrefix(ocppVersion, moduleName, methodName), + { throwError: false }, + ); + return {} as JSONSchemaType; + } + } + protected static getSampledValueTemplate( chargingStation: ChargingStation, connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, - phase?: MeterValuePhase + phase?: MeterValuePhase, ): SampledValueTemplate | undefined { const onPhaseStr = phase ? `on phase ${phase} ` : ''; - if (Constants.SUPPORTED_MEASURANDS.includes(measurand) === false) { + if (OCPPConstants.OCPP_MEASURANDS_SUPPORTED.includes(measurand) === false) { logger.warn( - `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}` + `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`, ); return; } if ( measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && - ChargingStationConfigurationUtils.getConfigurationKey( + getConfigurationKey( chargingStation, - StandardParametersKey.MeterValuesSampledData - )?.value.includes(measurand) === false + StandardParametersKey.MeterValuesSampledData, + )?.value?.includes(measurand) === false ) { logger.debug( - `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${ + `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId} not found in '${ StandardParametersKey.MeterValuesSampledData - }' OCPP parameter` + }' OCPP parameter`, ); return; } const sampledValueTemplates: SampledValueTemplate[] = - chargingStation.getConnectorStatus(connectorId).MeterValues; + chargingStation.getConnectorStatus(connectorId)!.MeterValues; for ( let index = 0; - Utils.isEmptyArray(sampledValueTemplates) === false && index < sampledValueTemplates.length; + isNotEmptyArray(sampledValueTemplates) === true && index < sampledValueTemplates.length; index++ ) { if ( - Constants.SUPPORTED_MEASURANDS.includes( + OCPPConstants.OCPP_MEASURANDS_SUPPORTED.includes( sampledValueTemplates[index]?.measurand ?? - MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER + MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, ) === false ) { logger.warn( - `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}` + `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`, ); } else if ( phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand && - ChargingStationConfigurationUtils.getConfigurationKey( + getConfigurationKey( chargingStation, - StandardParametersKey.MeterValuesSampledData - )?.value.includes(measurand) === true + StandardParametersKey.MeterValuesSampledData, + )?.value?.includes(measurand) === true ) { return sampledValueTemplates[index]; } else if ( !phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand && - ChargingStationConfigurationUtils.getConfigurationKey( + getConfigurationKey( chargingStation, - StandardParametersKey.MeterValuesSampledData - )?.value.includes(measurand) === true + StandardParametersKey.MeterValuesSampledData, + )?.value?.includes(measurand) === true ) { return sampledValueTemplates[index]; } else if ( @@ -145,12 +366,12 @@ export class OCPPServiceUtils { } } if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) { - const errorMsg = `Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`; + const errorMsg = `Missing MeterValues for default measurand '${measurand}' in template on connector id ${connectorId}`; logger.error(`${chargingStation.logPrefix()} ${errorMsg}`); throw new BaseError(errorMsg); } logger.debug( - `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}` + `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`, ); } @@ -160,13 +381,31 @@ export class OCPPServiceUtils { options: { limitationEnabled?: boolean; unitMultiplier?: number } = { limitationEnabled: true, unitMultiplier: 1, - } + }, ): number { - options.limitationEnabled = options?.limitationEnabled ?? true; - options.unitMultiplier = options?.unitMultiplier ?? 1; - const numberValue = isNaN(parseInt(value)) ? Infinity : parseInt(value); + options = { + ...{ + limitationEnabled: true, + unitMultiplier: 1, + }, + ...options, + }; + const parsedInt = parseInt(value); + const numberValue = isNaN(parsedInt) ? Infinity : parsedInt; return options?.limitationEnabled - ? Math.min(numberValue * options.unitMultiplier, limit) - : numberValue * options.unitMultiplier; + ? Math.min(numberValue * options.unitMultiplier!, limit) + : numberValue * options.unitMultiplier!; } + + private static logPrefix = ( + ocppVersion: OCPPVersion, + moduleName?: string, + methodName?: string, + ): string => { + const logMsg = + isNotEmptyString(moduleName) && isNotEmptyString(methodName) + ? ` OCPP ${ocppVersion} | ${moduleName}.${methodName}:` + : ` OCPP ${ocppVersion} |`; + return logPrefix(logMsg); + }; }