X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FHelpers.ts;h=492d26aa10dbeb5a5d028e1a7d6d111c291ac368;hb=de7b9e0583275225509c099f75a2801371da54d0;hp=9de547776ed470188274cc066bf7b51a3e09fea7;hpb=6fc0c6f3db444377c0fdea238183a14823278046;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/Helpers.ts b/src/charging-station/Helpers.ts index 9de54777..492d26aa 100644 --- a/src/charging-station/Helpers.ts +++ b/src/charging-station/Helpers.ts @@ -1,10 +1,12 @@ import { createHash, randomBytes } from 'node:crypto'; import type { EventEmitter } from 'node:events'; import { basename, dirname, join } from 'node:path'; +import { env } from 'node:process'; import { fileURLToPath } from 'node:url'; import chalk from 'chalk'; import { + type Interval, addDays, addSeconds, addWeeks, @@ -18,6 +20,7 @@ import { isWithinInterval, toDate, } from 'date-fns'; +import { maxTime } from 'date-fns/constants'; import type { ChargingStation } from './ChargingStation'; import { getConfigurationKey } from './ConfigurationKeyUtils'; @@ -31,6 +34,7 @@ import { ChargingProfileKindType, ChargingRateUnitType, type ChargingSchedulePeriod, + type ChargingStationConfiguration, type ChargingStationInfo, type ChargingStationTemplate, ChargingStationWorkerMessageEvents, @@ -72,10 +76,13 @@ const moduleName = 'Helpers'; export const getChargingStationId = ( index: number, - stationTemplate: ChargingStationTemplate, + stationTemplate: ChargingStationTemplate | undefined, ): string => { + if (stationTemplate === undefined) { + return "Unknown 'chargingStationId'"; + } // In case of multiple instances: add instance index to charging station id - const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0; + const instanceIndex = env.CF_INSTANCE_INDEX ?? 0; const idSuffix = stationTemplate?.nameSuffix ?? ''; const idStr = `000000000${index.toString()}`; return stationTemplate?.fixedName @@ -173,9 +180,9 @@ export const getPhaseRotationValue = ( } else if (connectorId > 0 && numberOfPhases === 0) { return `${connectorId}.${ConnectorPhaseRotation.NotApplicable}`; // AC - } else if (connectorId > 0 && numberOfPhases === 1) { + } else if (connectorId >= 0 && numberOfPhases === 1) { return `${connectorId}.${ConnectorPhaseRotation.NotApplicable}`; - } else if (connectorId > 0 && numberOfPhases === 3) { + } else if (connectorId >= 0 && numberOfPhases === 3) { return `${connectorId}.${ConnectorPhaseRotation.RST}`; } }; @@ -248,6 +255,23 @@ export const checkTemplate = ( } }; +export const checkConfiguration = ( + stationConfiguration: ChargingStationConfiguration | undefined, + logPrefix: string, + configurationFile: string, +): void => { + if (isNullOrUndefined(stationConfiguration)) { + const errorMsg = `Failed to read charging station configuration file ${configurationFile}`; + logger.error(`${logPrefix} ${errorMsg}`); + throw new BaseError(errorMsg); + } + if (isEmptyObject(stationConfiguration!)) { + const errorMsg = `Empty charging station configuration from file ${configurationFile}`; + logger.error(`${logPrefix} ${errorMsg}`); + throw new BaseError(errorMsg); + } +}; + export const checkConnectorsConfiguration = ( stationTemplate: ChargingStationTemplate, logPrefix: string, @@ -261,7 +285,7 @@ export const checkConnectorsConfiguration = ( checkConfiguredMaxConnectors(configuredMaxConnectors, logPrefix, templateFile); const templateMaxConnectors = getMaxNumberOfConnectors(stationTemplate.Connectors!); checkTemplateMaxConnectors(templateMaxConnectors, logPrefix, templateFile); - const templateMaxAvailableConnectors = stationTemplate.Connectors![0] + const templateMaxAvailableConnectors = stationTemplate.Connectors?.[0] ? templateMaxConnectors - 1 : templateMaxConnectors; if ( @@ -338,6 +362,12 @@ export const initializeConnectorsMapStatus = ( }; export const resetConnectorStatus = (connectorStatus: ConnectorStatus): void => { + connectorStatus.chargingProfiles = + connectorStatus.transactionId && isNotEmptyArray(connectorStatus.chargingProfiles) + ? connectorStatus.chargingProfiles?.filter( + (chargingProfile) => chargingProfile.transactionId !== connectorStatus.transactionId, + ) + : []; connectorStatus.idTagLocalAuthorized = false; connectorStatus.idTagAuthorized = false; connectorStatus.transactionRemoteStarted = false; @@ -355,7 +385,7 @@ export const createBootNotificationRequest = ( stationInfo: ChargingStationInfo, bootReason: BootReasonEnumType = BootReasonEnumType.PowerUp, ): BootNotificationRequest => { - const ocppVersion = stationInfo.ocppVersion ?? OCPPVersion.VERSION_16; + const ocppVersion = stationInfo.ocppVersion!; switch (ocppVersion) { case OCPPVersion.VERSION_16: return { @@ -445,12 +475,9 @@ export const stationTemplateToStationInfo = ( export const createSerialNumber = ( stationTemplate: ChargingStationTemplate, stationInfo: ChargingStationInfo, - params: { + params?: { randomSerialNumberUpperCase?: boolean; randomSerialNumber?: boolean; - } = { - randomSerialNumberUpperCase: true, - randomSerialNumber: true, }, ): void => { params = { ...{ randomSerialNumberUpperCase: true, randomSerialNumber: true }, ...params }; @@ -516,7 +543,7 @@ export const getAmperageLimitationUnitDivider = (stationInfo: ChargingStationInf /** * Gets the connector cloned charging profiles applying a power limitation - * and sorted by connector id ascending then stack level descending + * and sorted by connector id descending then stack level descending * * @param chargingStation - * @param connectorId - @@ -527,10 +554,10 @@ export const getConnectorChargingProfiles = ( connectorId: number, ) => { return cloneObject( - (chargingStation.getConnectorStatus(0)?.chargingProfiles ?? []) + (chargingStation.getConnectorStatus(connectorId)?.chargingProfiles ?? []) .sort((a, b) => b.stackLevel - a.stackLevel) .concat( - (chargingStation.getConnectorStatus(connectorId)?.chargingProfiles ?? []).sort( + (chargingStation.getConnectorStatus(0)?.chargingProfiles ?? []).sort( (a, b) => b.stackLevel - a.stackLevel, ), ), @@ -554,14 +581,14 @@ export const getChargingStationConnectorChargingProfilesPowerLimit = ( if (!isNullOrUndefined(result)) { limit = result?.limit; chargingProfile = result?.chargingProfile; - switch (chargingStation.getCurrentOutType()) { + switch (chargingStation.stationInfo?.currentOutType) { case CurrentType.AC: limit = chargingProfile?.chargingSchedule?.chargingRateUnit === ChargingRateUnitType.WATT ? limit : ACElectricUtils.powerTotal( chargingStation.getNumberOfPhases(), - chargingStation.getVoltageOut(), + chargingStation.stationInfo.voltageOut!, limit!, ); break; @@ -569,10 +596,10 @@ export const getChargingStationConnectorChargingProfilesPowerLimit = ( limit = chargingProfile?.chargingSchedule?.chargingRateUnit === ChargingRateUnitType.WATT ? limit - : DCElectricUtils.power(chargingStation.getVoltageOut(), limit!); + : DCElectricUtils.power(chargingStation.stationInfo.voltageOut!, limit!); } const connectorMaximumPower = - chargingStation.getMaximumPower() / chargingStation.powerDivider; + chargingStation.stationInfo.maximumPower! / chargingStation.powerDivider; if (limit! > connectorMaximumPower) { logger.error( `${chargingStation.logPrefix()} ${moduleName}.getChargingStationConnectorChargingProfilesPowerLimit: Charging profile id ${chargingProfile?.chargingProfileId} limit ${limit} is greater than connector id ${connectorId} maximum ${connectorMaximumPower}: %j`, @@ -641,7 +668,7 @@ const getConfiguredMaxNumberOfConnectors = (stationTemplate: ChargingStationTemp } else if (isUndefined(stationTemplate.numberOfConnectors) === false) { configuredMaxNumberOfConnectors = stationTemplate.numberOfConnectors as number; } else if (stationTemplate.Connectors && !stationTemplate.Evses) { - configuredMaxNumberOfConnectors = stationTemplate.Connectors[0] + configuredMaxNumberOfConnectors = stationTemplate.Connectors?.[0] ? getMaxNumberOfConnectors(stationTemplate.Connectors) - 1 : getMaxNumberOfConnectors(stationTemplate.Connectors); } else if (stationTemplate.Evses && !stationTemplate.Connectors) { @@ -705,12 +732,12 @@ const warnDeprecatedTemplateKey = ( templateFile: string, logMsgToAppend = '', ): void => { - if (!isUndefined(template[key as keyof ChargingStationTemplate])) { + if (!isUndefined(template?.[key as keyof ChargingStationTemplate])) { const logMsg = `Deprecated template key '${key}' usage in file '${templateFile}'${ isNotEmptyString(logMsgToAppend) ? `. ${logMsgToAppend}` : '' }`; logger.warn(`${logPrefix} ${logMsg}`); - console.warn(chalk.yellow(`${logMsg}`)); + console.warn(`${chalk.green(logPrefix)} ${chalk.yellow(logMsg)}`); } }; @@ -719,7 +746,7 @@ const convertDeprecatedTemplateKey = ( deprecatedKey: string, key?: string, ): void => { - if (!isUndefined(template[deprecatedKey as keyof ChargingStationTemplate])) { + if (!isUndefined(template?.[deprecatedKey as keyof ChargingStationTemplate])) { if (!isUndefined(key)) { (template as unknown as Record)[key!] = template[deprecatedKey as keyof ChargingStationTemplate]; @@ -734,7 +761,7 @@ interface ChargingProfilesLimit { } /** - * Charging profiles should already be sorted by connector id ascending then stack level descending + * Charging profiles shall already be sorted by connector id descending then stack level descending * * @param chargingStation - * @param connectorId - @@ -751,27 +778,34 @@ const getLimitFromChargingProfiles = ( const debugLogMsg = `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Matching charging profile found for power limitation: %j`; const currentDate = new Date(); const connectorStatus = chargingStation.getConnectorStatus(connectorId)!; - if (!isArraySorted(chargingProfiles, (a, b) => b.stackLevel - a.stackLevel)) { - logger.warn( - `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profiles are not sorted by stack level. Trying to sort them`, - ); - chargingProfiles.sort((a, b) => b.stackLevel - a.stackLevel); - } for (const chargingProfile of chargingProfiles) { const chargingSchedule = chargingProfile.chargingSchedule; - if (connectorStatus?.transactionStarted && isNullOrUndefined(chargingSchedule?.startSchedule)) { + if (isNullOrUndefined(chargingSchedule?.startSchedule) && connectorStatus?.transactionStarted) { logger.debug( `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no startSchedule defined. Trying to set it to the connector current transaction start date`, ); // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction chargingSchedule.startSchedule = connectorStatus?.transactionStart; } - if (!isDate(chargingSchedule?.startSchedule)) { + if ( + !isNullOrUndefined(chargingSchedule?.startSchedule) && + !isDate(chargingSchedule?.startSchedule) + ) { logger.warn( - `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} startSchedule property is not a Date object. Trying to convert it to a Date object`, + `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} startSchedule property is not a Date instance. Trying to convert it to a Date instance`, ); chargingSchedule.startSchedule = convertToDate(chargingSchedule?.startSchedule)!; } + if ( + !isNullOrUndefined(chargingSchedule?.startSchedule) && + isNullOrUndefined(chargingSchedule?.duration) + ) { + logger.debug( + `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no duration defined and will be set to the maximum time allowed`, + ); + // OCPP specifies that if duration is not defined, it should be infinite + chargingSchedule.duration = differenceInSeconds(maxTime, chargingSchedule.startSchedule!); + } if (!prepareChargingProfileKind(connectorStatus, chargingProfile, currentDate, logPrefix)) { continue; } @@ -780,7 +814,6 @@ const getLimitFromChargingProfiles = ( } // Check if the charging profile is active if ( - isValidTime(chargingSchedule?.startSchedule) && isWithinInterval(currentDate, { start: chargingSchedule.startSchedule!, end: addSeconds(chargingSchedule.startSchedule!, chargingSchedule.duration!), @@ -802,7 +835,7 @@ const getLimitFromChargingProfiles = ( ); chargingSchedule.chargingSchedulePeriod.sort(chargingSchedulePeriodCompareFn); } - // Check if the first schedule period start period is equal to 0 + // Check if the first schedule period startPeriod property is equal to 0 if (chargingSchedule.chargingSchedulePeriod[0].startPeriod !== 0) { logger.error( `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} first schedule period start period ${chargingSchedule.chargingSchedulePeriod[0].startPeriod} is not equal to 0`, @@ -886,8 +919,10 @@ export const prepareChargingProfileKind = ( ); delete chargingProfile.chargingSchedule.startSchedule; } - connectorStatus?.transactionStarted && - (chargingProfile.chargingSchedule.startSchedule = connectorStatus?.transactionStart); + if (connectorStatus?.transactionStarted) { + chargingProfile.chargingSchedule.startSchedule = connectorStatus?.transactionStart; + } + // FIXME: Handle relative charging profile duration break; } return true; @@ -909,16 +944,30 @@ export const canProceedChargingProfile = ( ); return false; } - const chargingSchedule = chargingProfile.chargingSchedule; - if (isNullOrUndefined(chargingSchedule?.startSchedule)) { + if ( + isNullOrUndefined(chargingProfile.chargingSchedule.startSchedule) || + isNullOrUndefined(chargingProfile.chargingSchedule.duration) + ) { + logger.error( + `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has no startSchedule or duration defined`, + ); + return false; + } + if ( + !isNullOrUndefined(chargingProfile.chargingSchedule.startSchedule) && + !isValidTime(chargingProfile.chargingSchedule.startSchedule) + ) { logger.error( - `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has no startSchedule defined`, + `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has an invalid startSchedule date defined`, ); return false; } - if (isNullOrUndefined(chargingSchedule?.duration)) { + if ( + !isNullOrUndefined(chargingProfile.chargingSchedule.duration) && + !Number.isSafeInteger(chargingProfile.chargingSchedule.duration) + ) { logger.error( - `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has no duration defined, not yet supported`, + `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has non integer duration defined`, ); return false; } @@ -938,6 +987,15 @@ const canProceedRecurringChargingProfile = ( ); return false; } + if ( + chargingProfile.chargingProfileKind === ChargingProfileKindType.RECURRING && + isNullOrUndefined(chargingProfile.chargingSchedule.startSchedule) + ) { + logger.error( + `${logPrefix} ${moduleName}.canProceedRecurringChargingProfile: Recurring charging profile id ${chargingProfile.chargingProfileId} has no startSchedule defined`, + ); + return false; + } return true; };