1 import { createHash
, randomBytes
} from
'node:crypto';
2 import type { EventEmitter
} from
'node:events';
3 import { basename
, dirname
, join
} from
'node:path';
4 import { env
} from
'node:process';
5 import { fileURLToPath
} from
'node:url';
7 import chalk from
'chalk';
24 import type { ChargingStation
} from
'./ChargingStation';
25 import { getConfigurationKey
} from
'./ConfigurationKeyUtils';
26 import { BaseError
} from
'../exception';
30 type BootNotificationRequest
,
33 ChargingProfileKindType
,
35 type ChargingSchedulePeriod
,
36 type ChargingStationInfo
,
37 type ChargingStationTemplate
,
38 ChargingStationWorkerMessageEvents
,
39 ConnectorPhaseRotation
,
44 type OCPP16BootNotificationRequest
,
45 type OCPP20BootNotificationRequest
,
49 ReservationTerminationReason
,
50 StandardParametersKey
,
51 SupportedFeatureProfiles
,
73 const moduleName
= 'Helpers';
75 export const getChargingStationId
= (
77 stationTemplate
: ChargingStationTemplate
,
79 // In case of multiple instances: add instance index to charging station id
80 const instanceIndex
= env
.CF_INSTANCE_INDEX
?? 0;
81 const idSuffix
= stationTemplate
?.nameSuffix
?? '';
82 const idStr
= `000000000${index.toString()}`;
83 return stationTemplate
?.fixedName
84 ? stationTemplate
.baseName
85 : `${stationTemplate.baseName}-${instanceIndex.toString()}${idStr.substring(
90 export const hasReservationExpired
= (reservation
: Reservation
): boolean => {
91 return isPast(reservation
.expiryDate
);
94 export const removeExpiredReservations
= async (
95 chargingStation
: ChargingStation
,
97 if (chargingStation
.hasEvses
) {
98 for (const evseStatus
of chargingStation
.evses
.values()) {
99 for (const connectorStatus
of evseStatus
.connectors
.values()) {
100 if (connectorStatus
.reservation
&& hasReservationExpired(connectorStatus
.reservation
)) {
101 await chargingStation
.removeReservation(
102 connectorStatus
.reservation
,
103 ReservationTerminationReason
.EXPIRED
,
109 for (const connectorStatus
of chargingStation
.connectors
.values()) {
110 if (connectorStatus
.reservation
&& hasReservationExpired(connectorStatus
.reservation
)) {
111 await chargingStation
.removeReservation(
112 connectorStatus
.reservation
,
113 ReservationTerminationReason
.EXPIRED
,
120 export const getNumberOfReservableConnectors
= (
121 connectors
: Map
<number, ConnectorStatus
>,
123 let numberOfReservableConnectors
= 0;
124 for (const [connectorId
, connectorStatus
] of connectors
) {
125 if (connectorId
=== 0) {
128 if (connectorStatus
.status === ConnectorStatusEnum
.Available
) {
129 ++numberOfReservableConnectors
;
132 return numberOfReservableConnectors
;
135 export const getHashId
= (index
: number, stationTemplate
: ChargingStationTemplate
): string => {
136 const chargingStationInfo
= {
137 chargePointModel
: stationTemplate
.chargePointModel
,
138 chargePointVendor
: stationTemplate
.chargePointVendor
,
139 ...(!isUndefined(stationTemplate
.chargeBoxSerialNumberPrefix
) && {
140 chargeBoxSerialNumber
: stationTemplate
.chargeBoxSerialNumberPrefix
,
142 ...(!isUndefined(stationTemplate
.chargePointSerialNumberPrefix
) && {
143 chargePointSerialNumber
: stationTemplate
.chargePointSerialNumberPrefix
,
145 ...(!isUndefined(stationTemplate
.meterSerialNumberPrefix
) && {
146 meterSerialNumber
: stationTemplate
.meterSerialNumberPrefix
,
148 ...(!isUndefined(stationTemplate
.meterType
) && {
149 meterType
: stationTemplate
.meterType
,
152 return createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
153 .update(`${JSON.stringify(chargingStationInfo)}${getChargingStationId(index, stationTemplate)}`)
157 export const checkChargingStation
= (
158 chargingStation
: ChargingStation
,
161 if (chargingStation
.started
=== false && chargingStation
.starting
=== false) {
162 logger
.warn(`${logPrefix} charging station is stopped, cannot proceed`);
168 export const getPhaseRotationValue
= (
170 numberOfPhases
: number,
171 ): string | undefined => {
173 if (connectorId
=== 0 && numberOfPhases
=== 0) {
174 return `${connectorId}.${ConnectorPhaseRotation.RST}`;
175 } else if (connectorId
> 0 && numberOfPhases
=== 0) {
176 return `${connectorId}.${ConnectorPhaseRotation.NotApplicable}`;
178 } else if (connectorId
>= 0 && numberOfPhases
=== 1) {
179 return `${connectorId}.${ConnectorPhaseRotation.NotApplicable}`;
180 } else if (connectorId
>= 0 && numberOfPhases
=== 3) {
181 return `${connectorId}.${ConnectorPhaseRotation.RST}`;
185 export const getMaxNumberOfEvses
= (evses
: Record
<string, EvseTemplate
>): number => {
189 return Object.keys(evses
).length
;
192 const getMaxNumberOfConnectors
= (connectors
: Record
<string, ConnectorStatus
>): number => {
196 return Object.keys(connectors
).length
;
199 export const getBootConnectorStatus
= (
200 chargingStation
: ChargingStation
,
202 connectorStatus
: ConnectorStatus
,
203 ): ConnectorStatusEnum
=> {
204 let connectorBootStatus
: ConnectorStatusEnum
;
206 !connectorStatus
?.status &&
207 (chargingStation
.isChargingStationAvailable() === false ||
208 chargingStation
.isConnectorAvailable(connectorId
) === false)
210 connectorBootStatus
= ConnectorStatusEnum
.Unavailable
;
211 } else if (!connectorStatus
?.status && connectorStatus
?.bootStatus
) {
212 // Set boot status in template at startup
213 connectorBootStatus
= connectorStatus
?.bootStatus
;
214 } else if (connectorStatus
?.status) {
215 // Set previous status at startup
216 connectorBootStatus
= connectorStatus
?.status;
218 // Set default status
219 connectorBootStatus
= ConnectorStatusEnum
.Available
;
221 return connectorBootStatus
;
224 export const checkTemplate
= (
225 stationTemplate
: ChargingStationTemplate
,
227 templateFile
: string,
229 if (isNullOrUndefined(stationTemplate
)) {
230 const errorMsg
= `Failed to read charging station template file ${templateFile}`;
231 logger
.error(`${logPrefix} ${errorMsg}`);
232 throw new BaseError(errorMsg
);
234 if (isEmptyObject(stationTemplate
)) {
235 const errorMsg
= `Empty charging station information from template file ${templateFile}`;
236 logger
.error(`${logPrefix} ${errorMsg}`);
237 throw new BaseError(errorMsg
);
239 if (isEmptyObject(stationTemplate
.AutomaticTransactionGenerator
!)) {
240 stationTemplate
.AutomaticTransactionGenerator
= Constants
.DEFAULT_ATG_CONFIGURATION
;
242 `${logPrefix} Empty automatic transaction generator configuration from template file ${templateFile}, set to default: %j`,
243 Constants
.DEFAULT_ATG_CONFIGURATION
,
246 if (isNullOrUndefined(stationTemplate
.idTagsFile
) || isEmptyString(stationTemplate
.idTagsFile
)) {
248 `${logPrefix} Missing id tags file in template file ${templateFile}. That can lead to issues with the Automatic Transaction Generator`,
253 export const checkConnectorsConfiguration
= (
254 stationTemplate
: ChargingStationTemplate
,
256 templateFile
: string,
258 configuredMaxConnectors
: number;
259 templateMaxConnectors
: number;
260 templateMaxAvailableConnectors
: number;
262 const configuredMaxConnectors
= getConfiguredMaxNumberOfConnectors(stationTemplate
);
263 checkConfiguredMaxConnectors(configuredMaxConnectors
, logPrefix
, templateFile
);
264 const templateMaxConnectors
= getMaxNumberOfConnectors(stationTemplate
.Connectors
!);
265 checkTemplateMaxConnectors(templateMaxConnectors
, logPrefix
, templateFile
);
266 const templateMaxAvailableConnectors
= stationTemplate
.Connectors
?.[0]
267 ? templateMaxConnectors
- 1
268 : templateMaxConnectors
;
270 configuredMaxConnectors
> templateMaxAvailableConnectors
&&
271 !stationTemplate
?.randomConnectors
274 `${logPrefix} Number of connectors exceeds the number of connector configurations in template ${templateFile}, forcing random connector configurations affectation`,
276 stationTemplate
.randomConnectors
= true;
278 return { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
};
281 export const checkStationInfoConnectorStatus
= (
283 connectorStatus
: ConnectorStatus
,
285 templateFile
: string,
287 if (!isNullOrUndefined(connectorStatus
?.status)) {
289 `${logPrefix} Charging station information from template ${templateFile} with connector id ${connectorId} status configuration defined, undefine it`,
291 delete connectorStatus
.status;
295 export const buildConnectorsMap
= (
296 connectors
: Record
<string, ConnectorStatus
>,
298 templateFile
: string,
299 ): Map
<number, ConnectorStatus
> => {
300 const connectorsMap
= new Map
<number, ConnectorStatus
>();
301 if (getMaxNumberOfConnectors(connectors
) > 0) {
302 for (const connector
in connectors
) {
303 const connectorStatus
= connectors
[connector
];
304 const connectorId
= convertToInt(connector
);
305 checkStationInfoConnectorStatus(connectorId
, connectorStatus
, logPrefix
, templateFile
);
306 connectorsMap
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
310 `${logPrefix} Charging station information from template ${templateFile} with no connectors, cannot build connectors map`,
313 return connectorsMap
;
316 export const initializeConnectorsMapStatus
= (
317 connectors
: Map
<number, ConnectorStatus
>,
320 for (const connectorId
of connectors
.keys()) {
321 if (connectorId
> 0 && connectors
.get(connectorId
)?.transactionStarted
=== true) {
323 `${logPrefix} Connector id ${connectorId} at initialization has a transaction started with id ${connectors.get(
328 if (connectorId
=== 0) {
329 connectors
.get(connectorId
)!.availability
= AvailabilityType
.Operative
;
330 if (isUndefined(connectors
.get(connectorId
)?.chargingProfiles
)) {
331 connectors
.get(connectorId
)!.chargingProfiles
= [];
335 isNullOrUndefined(connectors
.get(connectorId
)?.transactionStarted
)
337 initializeConnectorStatus(connectors
.get(connectorId
)!);
342 export const resetConnectorStatus
= (connectorStatus
: ConnectorStatus
): void => {
343 connectorStatus
.chargingProfiles
=
344 connectorStatus
.transactionId
&& isNotEmptyArray(connectorStatus
.chargingProfiles
)
345 ? connectorStatus
.chargingProfiles
?.filter(
346 (chargingProfile
) => chargingProfile
.transactionId
!== connectorStatus
.transactionId
,
349 connectorStatus
.idTagLocalAuthorized
= false;
350 connectorStatus
.idTagAuthorized
= false;
351 connectorStatus
.transactionRemoteStarted
= false;
352 connectorStatus
.transactionStarted
= false;
353 delete connectorStatus
?.transactionStart
;
354 delete connectorStatus
?.transactionId
;
355 delete connectorStatus
?.localAuthorizeIdTag
;
356 delete connectorStatus
?.authorizeIdTag
;
357 delete connectorStatus
?.transactionIdTag
;
358 connectorStatus
.transactionEnergyActiveImportRegisterValue
= 0;
359 delete connectorStatus
?.transactionBeginMeterValue
;
362 export const createBootNotificationRequest
= (
363 stationInfo
: ChargingStationInfo
,
364 bootReason
: BootReasonEnumType
= BootReasonEnumType
.PowerUp
,
365 ): BootNotificationRequest
=> {
366 const ocppVersion
= stationInfo
.ocppVersion
!;
367 switch (ocppVersion
) {
368 case OCPPVersion
.VERSION_16
:
370 chargePointModel
: stationInfo
.chargePointModel
,
371 chargePointVendor
: stationInfo
.chargePointVendor
,
372 ...(!isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
373 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
375 ...(!isUndefined(stationInfo
.chargePointSerialNumber
) && {
376 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
378 ...(!isUndefined(stationInfo
.firmwareVersion
) && {
379 firmwareVersion
: stationInfo
.firmwareVersion
,
381 ...(!isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
382 ...(!isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
383 ...(!isUndefined(stationInfo
.meterSerialNumber
) && {
384 meterSerialNumber
: stationInfo
.meterSerialNumber
,
386 ...(!isUndefined(stationInfo
.meterType
) && {
387 meterType
: stationInfo
.meterType
,
389 } as OCPP16BootNotificationRequest
;
390 case OCPPVersion
.VERSION_20
:
391 case OCPPVersion
.VERSION_201
:
395 model
: stationInfo
.chargePointModel
,
396 vendorName
: stationInfo
.chargePointVendor
,
397 ...(!isUndefined(stationInfo
.firmwareVersion
) && {
398 firmwareVersion
: stationInfo
.firmwareVersion
,
400 ...(!isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
401 serialNumber
: stationInfo
.chargeBoxSerialNumber
,
403 ...((!isUndefined(stationInfo
.iccid
) || !isUndefined(stationInfo
.imsi
)) && {
405 ...(!isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
406 ...(!isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
410 } as OCPP20BootNotificationRequest
;
414 export const warnTemplateKeysDeprecation
= (
415 stationTemplate
: ChargingStationTemplate
,
417 templateFile
: string,
419 const templateKeys
: { deprecatedKey
: string; key
?: string }[] = [
420 { deprecatedKey
: 'supervisionUrl', key
: 'supervisionUrls' },
421 { deprecatedKey
: 'authorizationFile', key
: 'idTagsFile' },
422 { deprecatedKey
: 'payloadSchemaValidation', key
: 'ocppStrictCompliance' },
423 { deprecatedKey
: 'mustAuthorizeAtRemoteStart', key
: 'remoteAuthorization' },
425 for (const templateKey
of templateKeys
) {
426 warnDeprecatedTemplateKey(
428 templateKey
.deprecatedKey
,
431 !isUndefined(templateKey
.key
) ? `Use '${templateKey.key}' instead` : undefined,
433 convertDeprecatedTemplateKey(stationTemplate
, templateKey
.deprecatedKey
, templateKey
.key
);
437 export const stationTemplateToStationInfo
= (
438 stationTemplate
: ChargingStationTemplate
,
439 ): ChargingStationInfo
=> {
440 stationTemplate
= cloneObject
<ChargingStationTemplate
>(stationTemplate
);
441 delete stationTemplate
.power
;
442 delete stationTemplate
.powerUnit
;
443 delete stationTemplate
.Connectors
;
444 delete stationTemplate
.Evses
;
445 delete stationTemplate
.Configuration
;
446 delete stationTemplate
.AutomaticTransactionGenerator
;
447 delete stationTemplate
.chargeBoxSerialNumberPrefix
;
448 delete stationTemplate
.chargePointSerialNumberPrefix
;
449 delete stationTemplate
.meterSerialNumberPrefix
;
450 return stationTemplate
as ChargingStationInfo
;
453 export const createSerialNumber
= (
454 stationTemplate
: ChargingStationTemplate
,
455 stationInfo
: ChargingStationInfo
,
457 randomSerialNumberUpperCase
?: boolean;
458 randomSerialNumber
?: boolean;
461 params
= { ...{ randomSerialNumberUpperCase
: true, randomSerialNumber
: true }, ...params
};
462 const serialNumberSuffix
= params
?.randomSerialNumber
463 ? getRandomSerialNumberSuffix({
464 upperCase
: params
.randomSerialNumberUpperCase
,
467 isNotEmptyString(stationTemplate
?.chargePointSerialNumberPrefix
) &&
468 (stationInfo
.chargePointSerialNumber
= `${stationTemplate.chargePointSerialNumberPrefix}${serialNumberSuffix}`);
469 isNotEmptyString(stationTemplate
?.chargeBoxSerialNumberPrefix
) &&
470 (stationInfo
.chargeBoxSerialNumber
= `${stationTemplate.chargeBoxSerialNumberPrefix}${serialNumberSuffix}`);
471 isNotEmptyString(stationTemplate
?.meterSerialNumberPrefix
) &&
472 (stationInfo
.meterSerialNumber
= `${stationTemplate.meterSerialNumberPrefix}${serialNumberSuffix}`);
475 export const propagateSerialNumber
= (
476 stationTemplate
: ChargingStationTemplate
,
477 stationInfoSrc
: ChargingStationInfo
,
478 stationInfoDst
: ChargingStationInfo
,
480 if (!stationInfoSrc
|| !stationTemplate
) {
482 'Missing charging station template or existing configuration to propagate serial number',
485 stationTemplate
?.chargePointSerialNumberPrefix
&& stationInfoSrc
?.chargePointSerialNumber
486 ? (stationInfoDst
.chargePointSerialNumber
= stationInfoSrc
.chargePointSerialNumber
)
487 : stationInfoDst
?.chargePointSerialNumber
&& delete stationInfoDst
.chargePointSerialNumber
;
488 stationTemplate
?.chargeBoxSerialNumberPrefix
&& stationInfoSrc
?.chargeBoxSerialNumber
489 ? (stationInfoDst
.chargeBoxSerialNumber
= stationInfoSrc
.chargeBoxSerialNumber
)
490 : stationInfoDst
?.chargeBoxSerialNumber
&& delete stationInfoDst
.chargeBoxSerialNumber
;
491 stationTemplate
?.meterSerialNumberPrefix
&& stationInfoSrc
?.meterSerialNumber
492 ? (stationInfoDst
.meterSerialNumber
= stationInfoSrc
.meterSerialNumber
)
493 : stationInfoDst
?.meterSerialNumber
&& delete stationInfoDst
.meterSerialNumber
;
496 export const hasFeatureProfile
= (
497 chargingStation
: ChargingStation
,
498 featureProfile
: SupportedFeatureProfiles
,
499 ): boolean | undefined => {
500 return getConfigurationKey(
502 StandardParametersKey
.SupportedFeatureProfiles
,
503 )?.value
?.includes(featureProfile
);
506 export const getAmperageLimitationUnitDivider
= (stationInfo
: ChargingStationInfo
): number => {
508 switch (stationInfo
.amperageLimitationUnit
) {
509 case AmpereUnits
.DECI_AMPERE
:
512 case AmpereUnits
.CENTI_AMPERE
:
515 case AmpereUnits
.MILLI_AMPERE
:
523 * Gets the connector cloned charging profiles applying a power limitation
524 * and sorted by connector id descending then stack level descending
526 * @param chargingStation -
527 * @param connectorId -
528 * @returns connector charging profiles array
530 export const getConnectorChargingProfiles
= (
531 chargingStation
: ChargingStation
,
534 return cloneObject
<ChargingProfile
[]>(
535 (chargingStation
.getConnectorStatus(connectorId
)?.chargingProfiles
?? [])
536 .sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
538 (chargingStation
.getConnectorStatus(0)?.chargingProfiles
?? []).sort(
539 (a
, b
) => b
.stackLevel
- a
.stackLevel
,
545 export const getChargingStationConnectorChargingProfilesPowerLimit
= (
546 chargingStation
: ChargingStation
,
548 ): number | undefined => {
549 let limit
: number | undefined, chargingProfile
: ChargingProfile
| undefined;
550 // Get charging profiles sorted by connector id then stack level
551 const chargingProfiles
= getConnectorChargingProfiles(chargingStation
, connectorId
);
552 if (isNotEmptyArray(chargingProfiles
)) {
553 const result
= getLimitFromChargingProfiles(
557 chargingStation
.logPrefix(),
559 if (!isNullOrUndefined(result
)) {
560 limit
= result
?.limit
;
561 chargingProfile
= result
?.chargingProfile
;
562 switch (chargingStation
.stationInfo
?.currentOutType
) {
565 chargingProfile
?.chargingSchedule
?.chargingRateUnit
=== ChargingRateUnitType
.WATT
567 : ACElectricUtils
.powerTotal(
568 chargingStation
.getNumberOfPhases(),
569 chargingStation
.stationInfo
.voltageOut
!,
575 chargingProfile
?.chargingSchedule
?.chargingRateUnit
=== ChargingRateUnitType
.WATT
577 : DCElectricUtils
.power(chargingStation
.stationInfo
.voltageOut
!, limit
!);
579 const connectorMaximumPower
=
580 chargingStation
.stationInfo
.maximumPower
! / chargingStation
.powerDivider
;
581 if (limit
! > connectorMaximumPower
) {
583 `${chargingStation.logPrefix()} ${moduleName}.getChargingStationConnectorChargingProfilesPowerLimit: Charging profile id ${chargingProfile?.chargingProfileId} limit ${limit} is greater than connector id ${connectorId} maximum ${connectorMaximumPower}: %j`,
586 limit
= connectorMaximumPower
;
593 export const getDefaultVoltageOut
= (
594 currentType
: CurrentType
,
596 templateFile
: string,
598 const errorMsg
= `Unknown ${currentType} currentOutType in template file ${templateFile}, cannot define default voltage out`;
599 let defaultVoltageOut
: number;
600 switch (currentType
) {
602 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
605 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
608 logger
.error(`${logPrefix} ${errorMsg}`);
609 throw new BaseError(errorMsg
);
611 return defaultVoltageOut
;
614 export const getIdTagsFile
= (stationInfo
: ChargingStationInfo
): string | undefined => {
616 stationInfo
.idTagsFile
&&
617 join(dirname(fileURLToPath(import.meta
.url
)), 'assets', basename(stationInfo
.idTagsFile
))
621 export const waitChargingStationEvents
= async (
622 emitter
: EventEmitter
,
623 event
: ChargingStationWorkerMessageEvents
,
624 eventsToWait
: number,
625 ): Promise
<number> => {
626 return new Promise
<number>((resolve
) => {
628 if (eventsToWait
=== 0) {
631 emitter
.on(event
, () => {
633 if (events
=== eventsToWait
) {
640 const getConfiguredMaxNumberOfConnectors
= (stationTemplate
: ChargingStationTemplate
): number => {
641 let configuredMaxNumberOfConnectors
= 0;
642 if (isNotEmptyArray(stationTemplate
.numberOfConnectors
) === true) {
643 const numberOfConnectors
= stationTemplate
.numberOfConnectors
as number[];
644 configuredMaxNumberOfConnectors
=
645 numberOfConnectors
[Math.floor(secureRandom() * numberOfConnectors
.length
)];
646 } else if (isUndefined(stationTemplate
.numberOfConnectors
) === false) {
647 configuredMaxNumberOfConnectors
= stationTemplate
.numberOfConnectors
as number;
648 } else if (stationTemplate
.Connectors
&& !stationTemplate
.Evses
) {
649 configuredMaxNumberOfConnectors
= stationTemplate
.Connectors
?.[0]
650 ? getMaxNumberOfConnectors(stationTemplate
.Connectors
) - 1
651 : getMaxNumberOfConnectors(stationTemplate
.Connectors
);
652 } else if (stationTemplate
.Evses
&& !stationTemplate
.Connectors
) {
653 for (const evse
in stationTemplate
.Evses
) {
657 configuredMaxNumberOfConnectors
+= getMaxNumberOfConnectors(
658 stationTemplate
.Evses
[evse
].Connectors
,
662 return configuredMaxNumberOfConnectors
;
665 const checkConfiguredMaxConnectors
= (
666 configuredMaxConnectors
: number,
668 templateFile
: string,
670 if (configuredMaxConnectors
<= 0) {
672 `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors`,
677 const checkTemplateMaxConnectors
= (
678 templateMaxConnectors
: number,
680 templateFile
: string,
682 if (templateMaxConnectors
=== 0) {
684 `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration`,
686 } else if (templateMaxConnectors
< 0) {
688 `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined`,
693 const initializeConnectorStatus
= (connectorStatus
: ConnectorStatus
): void => {
694 connectorStatus
.availability
= AvailabilityType
.Operative
;
695 connectorStatus
.idTagLocalAuthorized
= false;
696 connectorStatus
.idTagAuthorized
= false;
697 connectorStatus
.transactionRemoteStarted
= false;
698 connectorStatus
.transactionStarted
= false;
699 connectorStatus
.energyActiveImportRegisterValue
= 0;
700 connectorStatus
.transactionEnergyActiveImportRegisterValue
= 0;
701 if (isUndefined(connectorStatus
.chargingProfiles
)) {
702 connectorStatus
.chargingProfiles
= [];
706 const warnDeprecatedTemplateKey
= (
707 template
: ChargingStationTemplate
,
710 templateFile
: string,
713 if (!isUndefined(template
?.[key
as keyof ChargingStationTemplate
])) {
714 const logMsg
= `Deprecated template key '${key}' usage in file '${templateFile}'${
715 isNotEmptyString(logMsgToAppend) ? `. ${logMsgToAppend}
` : ''
717 logger
.warn(`${logPrefix} ${logMsg}`);
718 console
.warn(`${chalk.green(logPrefix)} ${chalk.yellow(logMsg)}`);
722 const convertDeprecatedTemplateKey
= (
723 template
: ChargingStationTemplate
,
724 deprecatedKey
: string,
727 if (!isUndefined(template
?.[deprecatedKey
as keyof ChargingStationTemplate
])) {
728 if (!isUndefined(key
)) {
729 (template
as unknown
as Record
<string, unknown
>)[key
!] =
730 template
[deprecatedKey
as keyof ChargingStationTemplate
];
732 delete template
[deprecatedKey
as keyof ChargingStationTemplate
];
736 interface ChargingProfilesLimit
{
738 chargingProfile
: ChargingProfile
;
742 * Charging profiles shall already be sorted by connector id descending then stack level descending
744 * @param chargingStation -
745 * @param connectorId -
746 * @param chargingProfiles -
748 * @returns ChargingProfilesLimit
750 const getLimitFromChargingProfiles
= (
751 chargingStation
: ChargingStation
,
753 chargingProfiles
: ChargingProfile
[],
755 ): ChargingProfilesLimit
| undefined => {
756 const debugLogMsg
= `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Matching charging profile found for power limitation: %j`;
757 const currentDate
= new Date();
758 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
759 for (const chargingProfile
of chargingProfiles
) {
760 const chargingSchedule
= chargingProfile
.chargingSchedule
;
761 if (isNullOrUndefined(chargingSchedule
?.startSchedule
) && connectorStatus
?.transactionStarted
) {
763 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no startSchedule defined. Trying to set it to the connector current transaction start date`,
765 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
766 chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
769 !isNullOrUndefined(chargingSchedule
?.startSchedule
) &&
770 !isDate(chargingSchedule
?.startSchedule
)
773 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} startSchedule property is not a Date instance. Trying to convert it to a Date instance`,
775 chargingSchedule
.startSchedule
= convertToDate(chargingSchedule
?.startSchedule
)!;
778 !isNullOrUndefined(chargingSchedule
?.startSchedule
) &&
779 isNullOrUndefined(chargingSchedule
?.duration
)
782 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no duration defined and will be set to the maximum time allowed`,
784 // OCPP specifies that if duration is not defined, it should be infinite
785 chargingSchedule
.duration
= differenceInSeconds(maxTime
, chargingSchedule
.startSchedule
!);
787 if (!prepareChargingProfileKind(connectorStatus
, chargingProfile
, currentDate
, logPrefix
)) {
790 if (!canProceedChargingProfile(chargingProfile
, currentDate
, logPrefix
)) {
793 // Check if the charging profile is active
795 isWithinInterval(currentDate
, {
796 start
: chargingSchedule
.startSchedule
!,
797 end
: addSeconds(chargingSchedule
.startSchedule
!, chargingSchedule
.duration
!),
800 if (isNotEmptyArray(chargingSchedule
.chargingSchedulePeriod
)) {
801 const chargingSchedulePeriodCompareFn
= (
802 a
: ChargingSchedulePeriod
,
803 b
: ChargingSchedulePeriod
,
804 ) => a
.startPeriod
- b
.startPeriod
;
806 !isArraySorted
<ChargingSchedulePeriod
>(
807 chargingSchedule
.chargingSchedulePeriod
,
808 chargingSchedulePeriodCompareFn
,
812 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} schedule periods are not sorted by start period`,
814 chargingSchedule
.chargingSchedulePeriod
.sort(chargingSchedulePeriodCompareFn
);
816 // Check if the first schedule period startPeriod property is equal to 0
817 if (chargingSchedule
.chargingSchedulePeriod
[0].startPeriod
!== 0) {
819 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} first schedule period start period ${chargingSchedule.chargingSchedulePeriod[0].startPeriod} is not equal to 0`,
823 // Handle only one schedule period
824 if (chargingSchedule
.chargingSchedulePeriod
.length
=== 1) {
825 const result
: ChargingProfilesLimit
= {
826 limit
: chargingSchedule
.chargingSchedulePeriod
[0].limit
,
829 logger
.debug(debugLogMsg
, result
);
832 let previousChargingSchedulePeriod
: ChargingSchedulePeriod
| undefined;
833 // Search for the right schedule period
836 chargingSchedulePeriod
,
837 ] of chargingSchedule
.chargingSchedulePeriod
.entries()) {
838 // Find the right schedule period
841 addSeconds(chargingSchedule
.startSchedule
!, chargingSchedulePeriod
.startPeriod
),
845 // Found the schedule period: previous is the correct one
846 const result
: ChargingProfilesLimit
= {
847 limit
: previousChargingSchedulePeriod
!.limit
,
850 logger
.debug(debugLogMsg
, result
);
853 // Keep a reference to previous one
854 previousChargingSchedulePeriod
= chargingSchedulePeriod
;
855 // Handle the last schedule period within the charging profile duration
857 index
=== chargingSchedule
.chargingSchedulePeriod
.length
- 1 ||
858 (index
< chargingSchedule
.chargingSchedulePeriod
.length
- 1 &&
861 chargingSchedule
.startSchedule
!,
862 chargingSchedule
.chargingSchedulePeriod
[index
+ 1].startPeriod
,
864 chargingSchedule
.startSchedule
!,
865 ) > chargingSchedule
.duration
!)
867 const result
: ChargingProfilesLimit
= {
868 limit
: previousChargingSchedulePeriod
.limit
,
871 logger
.debug(debugLogMsg
, result
);
880 export const prepareChargingProfileKind
= (
881 connectorStatus
: ConnectorStatus
,
882 chargingProfile
: ChargingProfile
,
886 switch (chargingProfile
.chargingProfileKind
) {
887 case ChargingProfileKindType
.RECURRING
:
888 if (!canProceedRecurringChargingProfile(chargingProfile
, logPrefix
)) {
891 prepareRecurringChargingProfile(chargingProfile
, currentDate
, logPrefix
);
893 case ChargingProfileKindType
.RELATIVE
:
894 if (!isNullOrUndefined(chargingProfile
.chargingSchedule
.startSchedule
)) {
896 `${logPrefix} ${moduleName}.prepareChargingProfileKind: Relative charging profile id ${chargingProfile.chargingProfileId} has a startSchedule property defined. It will be ignored or used if the connector has a transaction started`,
898 delete chargingProfile
.chargingSchedule
.startSchedule
;
900 if (connectorStatus
?.transactionStarted
) {
901 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
903 // FIXME: Handle relative charging profile duration
909 export const canProceedChargingProfile
= (
910 chargingProfile
: ChargingProfile
,
915 (isValidTime(chargingProfile
.validFrom
) && isBefore(currentDate
, chargingProfile
.validFrom
!)) ||
916 (isValidTime(chargingProfile
.validTo
) && isAfter(currentDate
, chargingProfile
.validTo
!))
919 `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${
920 chargingProfile.chargingProfileId
921 } is not valid for the current date ${currentDate.toISOString()}`,
926 isNullOrUndefined(chargingProfile
.chargingSchedule
.startSchedule
) ||
927 isNullOrUndefined(chargingProfile
.chargingSchedule
.duration
)
930 `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has no startSchedule or duration defined`,
935 !isNullOrUndefined(chargingProfile
.chargingSchedule
.startSchedule
) &&
936 !isValidTime(chargingProfile
.chargingSchedule
.startSchedule
)
939 `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has an invalid startSchedule date defined`,
944 !isNullOrUndefined(chargingProfile
.chargingSchedule
.duration
) &&
945 !Number.isSafeInteger(chargingProfile
.chargingSchedule
.duration
)
948 `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has non integer duration defined`,
955 const canProceedRecurringChargingProfile
= (
956 chargingProfile
: ChargingProfile
,
960 chargingProfile
.chargingProfileKind
=== ChargingProfileKindType
.RECURRING
&&
961 isNullOrUndefined(chargingProfile
.recurrencyKind
)
964 `${logPrefix} ${moduleName}.canProceedRecurringChargingProfile: Recurring charging profile id ${chargingProfile.chargingProfileId} has no recurrencyKind defined`,
969 chargingProfile
.chargingProfileKind
=== ChargingProfileKindType
.RECURRING
&&
970 isNullOrUndefined(chargingProfile
.chargingSchedule
.startSchedule
)
973 `${logPrefix} ${moduleName}.canProceedRecurringChargingProfile: Recurring charging profile id ${chargingProfile.chargingProfileId} has no startSchedule defined`,
981 * Adjust recurring charging profile startSchedule to the current recurrency time interval if needed
983 * @param chargingProfile -
984 * @param currentDate -
987 const prepareRecurringChargingProfile
= (
988 chargingProfile
: ChargingProfile
,
992 const chargingSchedule
= chargingProfile
.chargingSchedule
;
993 let recurringIntervalTranslated
= false;
994 let recurringInterval
: Interval
;
995 switch (chargingProfile
.recurrencyKind
) {
996 case RecurrencyKindType
.DAILY
:
997 recurringInterval
= {
998 start
: chargingSchedule
.startSchedule
!,
999 end
: addDays(chargingSchedule
.startSchedule
!, 1),
1001 checkRecurringChargingProfileDuration(chargingProfile
, recurringInterval
, logPrefix
);
1003 !isWithinInterval(currentDate
, recurringInterval
) &&
1004 isBefore(recurringInterval
.end
, currentDate
)
1006 chargingSchedule
.startSchedule
= addDays(
1007 recurringInterval
.start
,
1008 differenceInDays(currentDate
, recurringInterval
.start
),
1010 recurringInterval
= {
1011 start
: chargingSchedule
.startSchedule
,
1012 end
: addDays(chargingSchedule
.startSchedule
, 1),
1014 recurringIntervalTranslated
= true;
1017 case RecurrencyKindType
.WEEKLY
:
1018 recurringInterval
= {
1019 start
: chargingSchedule
.startSchedule
!,
1020 end
: addWeeks(chargingSchedule
.startSchedule
!, 1),
1022 checkRecurringChargingProfileDuration(chargingProfile
, recurringInterval
, logPrefix
);
1024 !isWithinInterval(currentDate
, recurringInterval
) &&
1025 isBefore(recurringInterval
.end
, currentDate
)
1027 chargingSchedule
.startSchedule
= addWeeks(
1028 recurringInterval
.start
,
1029 differenceInWeeks(currentDate
, recurringInterval
.start
),
1031 recurringInterval
= {
1032 start
: chargingSchedule
.startSchedule
,
1033 end
: addWeeks(chargingSchedule
.startSchedule
, 1),
1035 recurringIntervalTranslated
= true;
1040 `${logPrefix} ${moduleName}.prepareRecurringChargingProfile: Recurring ${chargingProfile.recurrencyKind} charging profile id ${chargingProfile.chargingProfileId} is not supported`,
1043 if (recurringIntervalTranslated
&& !isWithinInterval(currentDate
, recurringInterval
!)) {
1045 `${logPrefix} ${moduleName}.prepareRecurringChargingProfile: Recurring ${
1046 chargingProfile.recurrencyKind
1047 } charging profile id ${chargingProfile.chargingProfileId} recurrency time interval [${toDate(
1048 recurringInterval!.start,
1049 ).toISOString()}, ${toDate(
1050 recurringInterval!.end,
1051 ).toISOString()}] has not been properly translated to current date ${currentDate.toISOString()} `,
1054 return recurringIntervalTranslated
;
1057 const checkRecurringChargingProfileDuration
= (
1058 chargingProfile
: ChargingProfile
,
1062 if (isNullOrUndefined(chargingProfile
.chargingSchedule
.duration
)) {
1064 `${logPrefix} ${moduleName}.checkRecurringChargingProfileDuration: Recurring ${
1065 chargingProfile.chargingProfileKind
1066 } charging profile id ${
1067 chargingProfile.chargingProfileId
1068 } duration is not defined, set it to the recurrency time interval duration ${differenceInSeconds(
1073 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(interval
.end
, interval
.start
);
1075 chargingProfile
.chargingSchedule
.duration
! > differenceInSeconds(interval
.end
, interval
.start
)
1078 `${logPrefix} ${moduleName}.checkRecurringChargingProfileDuration: Recurring ${
1079 chargingProfile.chargingProfileKind
1080 } charging profile id ${chargingProfile.chargingProfileId} duration ${
1081 chargingProfile.chargingSchedule.duration
1082 } is greater than the recurrency time interval duration ${differenceInSeconds(
1087 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(interval
.end
, interval
.start
);
1091 const getRandomSerialNumberSuffix
= (params
?: {
1092 randomBytesLength
?: number;
1093 upperCase
?: boolean;
1095 const randomSerialNumberSuffix
= randomBytes(params
?.randomBytesLength
?? 16).toString('hex');
1096 if (params
?.upperCase
) {
1097 return randomSerialNumberSuffix
.toUpperCase();
1099 return randomSerialNumberSuffix
;