1 import { createHash
, randomBytes
} from
'node:crypto';
2 import type { EventEmitter
} from
'node:events';
3 import { basename
, dirname
, join
} from
'node:path';
4 import { fileURLToPath
} from
'node:url';
6 import chalk from
'chalk';
23 import type { ChargingStation
} from
'./ChargingStation';
24 import { getConfigurationKey
} from
'./ConfigurationKeyUtils';
25 import { BaseError
} from
'../exception';
29 type BootNotificationRequest
,
32 ChargingProfileKindType
,
34 type ChargingSchedulePeriod
,
35 type ChargingStationInfo
,
36 type ChargingStationTemplate
,
37 ChargingStationWorkerMessageEvents
,
38 ConnectorPhaseRotation
,
43 type OCPP16BootNotificationRequest
,
44 type OCPP20BootNotificationRequest
,
48 ReservationTerminationReason
,
49 StandardParametersKey
,
50 SupportedFeatureProfiles
,
72 const moduleName
= 'Helpers';
74 export const getChargingStationId
= (
76 stationTemplate
: ChargingStationTemplate
,
78 // In case of multiple instances: add instance index to charging station id
79 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
80 const idSuffix
= stationTemplate
?.nameSuffix
?? '';
81 const idStr
= `000000000${index.toString()}`;
82 return stationTemplate
?.fixedName
83 ? stationTemplate
.baseName
84 : `${stationTemplate.baseName}-${instanceIndex.toString()}${idStr.substring(
89 export const hasReservationExpired
= (reservation
: Reservation
): boolean => {
90 return isPast(reservation
.expiryDate
);
93 export const removeExpiredReservations
= async (
94 chargingStation
: ChargingStation
,
96 if (chargingStation
.hasEvses
) {
97 for (const evseStatus
of chargingStation
.evses
.values()) {
98 for (const connectorStatus
of evseStatus
.connectors
.values()) {
99 if (connectorStatus
.reservation
&& hasReservationExpired(connectorStatus
.reservation
)) {
100 await chargingStation
.removeReservation(
101 connectorStatus
.reservation
,
102 ReservationTerminationReason
.EXPIRED
,
108 for (const connectorStatus
of chargingStation
.connectors
.values()) {
109 if (connectorStatus
.reservation
&& hasReservationExpired(connectorStatus
.reservation
)) {
110 await chargingStation
.removeReservation(
111 connectorStatus
.reservation
,
112 ReservationTerminationReason
.EXPIRED
,
119 export const getNumberOfReservableConnectors
= (
120 connectors
: Map
<number, ConnectorStatus
>,
122 let numberOfReservableConnectors
= 0;
123 for (const [connectorId
, connectorStatus
] of connectors
) {
124 if (connectorId
=== 0) {
127 if (connectorStatus
.status === ConnectorStatusEnum
.Available
) {
128 ++numberOfReservableConnectors
;
131 return numberOfReservableConnectors
;
134 export const getHashId
= (index
: number, stationTemplate
: ChargingStationTemplate
): string => {
135 const chargingStationInfo
= {
136 chargePointModel
: stationTemplate
.chargePointModel
,
137 chargePointVendor
: stationTemplate
.chargePointVendor
,
138 ...(!isUndefined(stationTemplate
.chargeBoxSerialNumberPrefix
) && {
139 chargeBoxSerialNumber
: stationTemplate
.chargeBoxSerialNumberPrefix
,
141 ...(!isUndefined(stationTemplate
.chargePointSerialNumberPrefix
) && {
142 chargePointSerialNumber
: stationTemplate
.chargePointSerialNumberPrefix
,
144 ...(!isUndefined(stationTemplate
.meterSerialNumberPrefix
) && {
145 meterSerialNumber
: stationTemplate
.meterSerialNumberPrefix
,
147 ...(!isUndefined(stationTemplate
.meterType
) && {
148 meterType
: stationTemplate
.meterType
,
151 return createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
152 .update(`${JSON.stringify(chargingStationInfo)}${getChargingStationId(index, stationTemplate)}`)
156 export const checkChargingStation
= (
157 chargingStation
: ChargingStation
,
160 if (chargingStation
.started
=== false && chargingStation
.starting
=== false) {
161 logger
.warn(`${logPrefix} charging station is stopped, cannot proceed`);
167 export const getPhaseRotationValue
= (
169 numberOfPhases
: number,
170 ): string | undefined => {
172 if (connectorId
=== 0 && numberOfPhases
=== 0) {
173 return `${connectorId}.${ConnectorPhaseRotation.RST}`;
174 } else if (connectorId
> 0 && numberOfPhases
=== 0) {
175 return `${connectorId}.${ConnectorPhaseRotation.NotApplicable}`;
177 } else if (connectorId
> 0 && numberOfPhases
=== 1) {
178 return `${connectorId}.${ConnectorPhaseRotation.NotApplicable}`;
179 } else if (connectorId
> 0 && numberOfPhases
=== 3) {
180 return `${connectorId}.${ConnectorPhaseRotation.RST}`;
184 export const getMaxNumberOfEvses
= (evses
: Record
<string, EvseTemplate
>): number => {
188 return Object.keys(evses
).length
;
191 const getMaxNumberOfConnectors
= (connectors
: Record
<string, ConnectorStatus
>): number => {
195 return Object.keys(connectors
).length
;
198 export const getBootConnectorStatus
= (
199 chargingStation
: ChargingStation
,
201 connectorStatus
: ConnectorStatus
,
202 ): ConnectorStatusEnum
=> {
203 let connectorBootStatus
: ConnectorStatusEnum
;
205 !connectorStatus
?.status &&
206 (chargingStation
.isChargingStationAvailable() === false ||
207 chargingStation
.isConnectorAvailable(connectorId
) === false)
209 connectorBootStatus
= ConnectorStatusEnum
.Unavailable
;
210 } else if (!connectorStatus
?.status && connectorStatus
?.bootStatus
) {
211 // Set boot status in template at startup
212 connectorBootStatus
= connectorStatus
?.bootStatus
;
213 } else if (connectorStatus
?.status) {
214 // Set previous status at startup
215 connectorBootStatus
= connectorStatus
?.status;
217 // Set default status
218 connectorBootStatus
= ConnectorStatusEnum
.Available
;
220 return connectorBootStatus
;
223 export const checkTemplate
= (
224 stationTemplate
: ChargingStationTemplate
,
226 templateFile
: string,
228 if (isNullOrUndefined(stationTemplate
)) {
229 const errorMsg
= `Failed to read charging station template file ${templateFile}`;
230 logger
.error(`${logPrefix} ${errorMsg}`);
231 throw new BaseError(errorMsg
);
233 if (isEmptyObject(stationTemplate
)) {
234 const errorMsg
= `Empty charging station information from template file ${templateFile}`;
235 logger
.error(`${logPrefix} ${errorMsg}`);
236 throw new BaseError(errorMsg
);
238 if (isEmptyObject(stationTemplate
.AutomaticTransactionGenerator
!)) {
239 stationTemplate
.AutomaticTransactionGenerator
= Constants
.DEFAULT_ATG_CONFIGURATION
;
241 `${logPrefix} Empty automatic transaction generator configuration from template file ${templateFile}, set to default: %j`,
242 Constants
.DEFAULT_ATG_CONFIGURATION
,
245 if (isNullOrUndefined(stationTemplate
.idTagsFile
) || isEmptyString(stationTemplate
.idTagsFile
)) {
247 `${logPrefix} Missing id tags file in template file ${templateFile}. That can lead to issues with the Automatic Transaction Generator`,
252 export const checkConnectorsConfiguration
= (
253 stationTemplate
: ChargingStationTemplate
,
255 templateFile
: string,
257 configuredMaxConnectors
: number;
258 templateMaxConnectors
: number;
259 templateMaxAvailableConnectors
: number;
261 const configuredMaxConnectors
= getConfiguredMaxNumberOfConnectors(stationTemplate
);
262 checkConfiguredMaxConnectors(configuredMaxConnectors
, logPrefix
, templateFile
);
263 const templateMaxConnectors
= getMaxNumberOfConnectors(stationTemplate
.Connectors
!);
264 checkTemplateMaxConnectors(templateMaxConnectors
, logPrefix
, templateFile
);
265 const templateMaxAvailableConnectors
= stationTemplate
.Connectors
![0]
266 ? templateMaxConnectors
- 1
267 : templateMaxConnectors
;
269 configuredMaxConnectors
> templateMaxAvailableConnectors
&&
270 !stationTemplate
?.randomConnectors
273 `${logPrefix} Number of connectors exceeds the number of connector configurations in template ${templateFile}, forcing random connector configurations affectation`,
275 stationTemplate
.randomConnectors
= true;
277 return { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
};
280 export const checkStationInfoConnectorStatus
= (
282 connectorStatus
: ConnectorStatus
,
284 templateFile
: string,
286 if (!isNullOrUndefined(connectorStatus
?.status)) {
288 `${logPrefix} Charging station information from template ${templateFile} with connector id ${connectorId} status configuration defined, undefine it`,
290 delete connectorStatus
.status;
294 export const buildConnectorsMap
= (
295 connectors
: Record
<string, ConnectorStatus
>,
297 templateFile
: string,
298 ): Map
<number, ConnectorStatus
> => {
299 const connectorsMap
= new Map
<number, ConnectorStatus
>();
300 if (getMaxNumberOfConnectors(connectors
) > 0) {
301 for (const connector
in connectors
) {
302 const connectorStatus
= connectors
[connector
];
303 const connectorId
= convertToInt(connector
);
304 checkStationInfoConnectorStatus(connectorId
, connectorStatus
, logPrefix
, templateFile
);
305 connectorsMap
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
309 `${logPrefix} Charging station information from template ${templateFile} with no connectors, cannot build connectors map`,
312 return connectorsMap
;
315 export const initializeConnectorsMapStatus
= (
316 connectors
: Map
<number, ConnectorStatus
>,
319 for (const connectorId
of connectors
.keys()) {
320 if (connectorId
> 0 && connectors
.get(connectorId
)?.transactionStarted
=== true) {
322 `${logPrefix} Connector id ${connectorId} at initialization has a transaction started with id ${connectors.get(
327 if (connectorId
=== 0) {
328 connectors
.get(connectorId
)!.availability
= AvailabilityType
.Operative
;
329 if (isUndefined(connectors
.get(connectorId
)?.chargingProfiles
)) {
330 connectors
.get(connectorId
)!.chargingProfiles
= [];
334 isNullOrUndefined(connectors
.get(connectorId
)?.transactionStarted
)
336 initializeConnectorStatus(connectors
.get(connectorId
)!);
341 export const resetConnectorStatus
= (connectorStatus
: ConnectorStatus
): void => {
342 connectorStatus
.chargingProfiles
= isNotEmptyArray(connectorStatus
.chargingProfiles
)
343 ? connectorStatus
.chargingProfiles
?.filter(
344 (chargingProfile
) => chargingProfile
.transactionId
!== connectorStatus
?.transactionId
,
347 connectorStatus
.idTagLocalAuthorized
= false;
348 connectorStatus
.idTagAuthorized
= false;
349 connectorStatus
.transactionRemoteStarted
= false;
350 connectorStatus
.transactionStarted
= false;
351 delete connectorStatus
?.transactionStart
;
352 delete connectorStatus
?.transactionId
;
353 delete connectorStatus
?.localAuthorizeIdTag
;
354 delete connectorStatus
?.authorizeIdTag
;
355 delete connectorStatus
?.transactionIdTag
;
356 connectorStatus
.transactionEnergyActiveImportRegisterValue
= 0;
357 delete connectorStatus
?.transactionBeginMeterValue
;
360 export const createBootNotificationRequest
= (
361 stationInfo
: ChargingStationInfo
,
362 bootReason
: BootReasonEnumType
= BootReasonEnumType
.PowerUp
,
363 ): BootNotificationRequest
=> {
364 const ocppVersion
= stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
365 switch (ocppVersion
) {
366 case OCPPVersion
.VERSION_16
:
368 chargePointModel
: stationInfo
.chargePointModel
,
369 chargePointVendor
: stationInfo
.chargePointVendor
,
370 ...(!isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
371 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
373 ...(!isUndefined(stationInfo
.chargePointSerialNumber
) && {
374 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
376 ...(!isUndefined(stationInfo
.firmwareVersion
) && {
377 firmwareVersion
: stationInfo
.firmwareVersion
,
379 ...(!isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
380 ...(!isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
381 ...(!isUndefined(stationInfo
.meterSerialNumber
) && {
382 meterSerialNumber
: stationInfo
.meterSerialNumber
,
384 ...(!isUndefined(stationInfo
.meterType
) && {
385 meterType
: stationInfo
.meterType
,
387 } as OCPP16BootNotificationRequest
;
388 case OCPPVersion
.VERSION_20
:
389 case OCPPVersion
.VERSION_201
:
393 model
: stationInfo
.chargePointModel
,
394 vendorName
: stationInfo
.chargePointVendor
,
395 ...(!isUndefined(stationInfo
.firmwareVersion
) && {
396 firmwareVersion
: stationInfo
.firmwareVersion
,
398 ...(!isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
399 serialNumber
: stationInfo
.chargeBoxSerialNumber
,
401 ...((!isUndefined(stationInfo
.iccid
) || !isUndefined(stationInfo
.imsi
)) && {
403 ...(!isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
404 ...(!isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
408 } as OCPP20BootNotificationRequest
;
412 export const warnTemplateKeysDeprecation
= (
413 stationTemplate
: ChargingStationTemplate
,
415 templateFile
: string,
417 const templateKeys
: { deprecatedKey
: string; key
?: string }[] = [
418 { deprecatedKey
: 'supervisionUrl', key
: 'supervisionUrls' },
419 { deprecatedKey
: 'authorizationFile', key
: 'idTagsFile' },
420 { deprecatedKey
: 'payloadSchemaValidation', key
: 'ocppStrictCompliance' },
421 { deprecatedKey
: 'mustAuthorizeAtRemoteStart', key
: 'remoteAuthorization' },
423 for (const templateKey
of templateKeys
) {
424 warnDeprecatedTemplateKey(
426 templateKey
.deprecatedKey
,
429 !isUndefined(templateKey
.key
) ? `Use '${templateKey.key}' instead` : undefined,
431 convertDeprecatedTemplateKey(stationTemplate
, templateKey
.deprecatedKey
, templateKey
.key
);
435 export const stationTemplateToStationInfo
= (
436 stationTemplate
: ChargingStationTemplate
,
437 ): ChargingStationInfo
=> {
438 stationTemplate
= cloneObject
<ChargingStationTemplate
>(stationTemplate
);
439 delete stationTemplate
.power
;
440 delete stationTemplate
.powerUnit
;
441 delete stationTemplate
.Connectors
;
442 delete stationTemplate
.Evses
;
443 delete stationTemplate
.Configuration
;
444 delete stationTemplate
.AutomaticTransactionGenerator
;
445 delete stationTemplate
.chargeBoxSerialNumberPrefix
;
446 delete stationTemplate
.chargePointSerialNumberPrefix
;
447 delete stationTemplate
.meterSerialNumberPrefix
;
448 return stationTemplate
as ChargingStationInfo
;
451 export const createSerialNumber
= (
452 stationTemplate
: ChargingStationTemplate
,
453 stationInfo
: ChargingStationInfo
,
455 randomSerialNumberUpperCase
?: boolean;
456 randomSerialNumber
?: boolean;
458 randomSerialNumberUpperCase
: true,
459 randomSerialNumber
: true,
462 params
= { ...{ randomSerialNumberUpperCase
: true, randomSerialNumber
: true }, ...params
};
463 const serialNumberSuffix
= params
?.randomSerialNumber
464 ? getRandomSerialNumberSuffix({
465 upperCase
: params
.randomSerialNumberUpperCase
,
468 isNotEmptyString(stationTemplate
?.chargePointSerialNumberPrefix
) &&
469 (stationInfo
.chargePointSerialNumber
= `${stationTemplate.chargePointSerialNumberPrefix}${serialNumberSuffix}`);
470 isNotEmptyString(stationTemplate
?.chargeBoxSerialNumberPrefix
) &&
471 (stationInfo
.chargeBoxSerialNumber
= `${stationTemplate.chargeBoxSerialNumberPrefix}${serialNumberSuffix}`);
472 isNotEmptyString(stationTemplate
?.meterSerialNumberPrefix
) &&
473 (stationInfo
.meterSerialNumber
= `${stationTemplate.meterSerialNumberPrefix}${serialNumberSuffix}`);
476 export const propagateSerialNumber
= (
477 stationTemplate
: ChargingStationTemplate
,
478 stationInfoSrc
: ChargingStationInfo
,
479 stationInfoDst
: ChargingStationInfo
,
481 if (!stationInfoSrc
|| !stationTemplate
) {
483 'Missing charging station template or existing configuration to propagate serial number',
486 stationTemplate
?.chargePointSerialNumberPrefix
&& stationInfoSrc
?.chargePointSerialNumber
487 ? (stationInfoDst
.chargePointSerialNumber
= stationInfoSrc
.chargePointSerialNumber
)
488 : stationInfoDst
?.chargePointSerialNumber
&& delete stationInfoDst
.chargePointSerialNumber
;
489 stationTemplate
?.chargeBoxSerialNumberPrefix
&& stationInfoSrc
?.chargeBoxSerialNumber
490 ? (stationInfoDst
.chargeBoxSerialNumber
= stationInfoSrc
.chargeBoxSerialNumber
)
491 : stationInfoDst
?.chargeBoxSerialNumber
&& delete stationInfoDst
.chargeBoxSerialNumber
;
492 stationTemplate
?.meterSerialNumberPrefix
&& stationInfoSrc
?.meterSerialNumber
493 ? (stationInfoDst
.meterSerialNumber
= stationInfoSrc
.meterSerialNumber
)
494 : stationInfoDst
?.meterSerialNumber
&& delete stationInfoDst
.meterSerialNumber
;
497 export const hasFeatureProfile
= (
498 chargingStation
: ChargingStation
,
499 featureProfile
: SupportedFeatureProfiles
,
500 ): boolean | undefined => {
501 return getConfigurationKey(
503 StandardParametersKey
.SupportedFeatureProfiles
,
504 )?.value
?.includes(featureProfile
);
507 export const getAmperageLimitationUnitDivider
= (stationInfo
: ChargingStationInfo
): number => {
509 switch (stationInfo
.amperageLimitationUnit
) {
510 case AmpereUnits
.DECI_AMPERE
:
513 case AmpereUnits
.CENTI_AMPERE
:
516 case AmpereUnits
.MILLI_AMPERE
:
524 * Gets the connector cloned charging profiles applying a power limitation
525 * and sorted by connector id descending then stack level descending
527 * @param chargingStation -
528 * @param connectorId -
529 * @returns connector charging profiles array
531 export const getConnectorChargingProfiles
= (
532 chargingStation
: ChargingStation
,
535 return cloneObject
<ChargingProfile
[]>(
536 (chargingStation
.getConnectorStatus(connectorId
)?.chargingProfiles
?? [])
537 .sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
539 (chargingStation
.getConnectorStatus(0)?.chargingProfiles
?? []).sort(
540 (a
, b
) => b
.stackLevel
- a
.stackLevel
,
546 export const getChargingStationConnectorChargingProfilesPowerLimit
= (
547 chargingStation
: ChargingStation
,
549 ): number | undefined => {
550 let limit
: number | undefined, chargingProfile
: ChargingProfile
| undefined;
551 // Get charging profiles sorted by connector id then stack level
552 const chargingProfiles
= getConnectorChargingProfiles(chargingStation
, connectorId
);
553 if (isNotEmptyArray(chargingProfiles
)) {
554 const result
= getLimitFromChargingProfiles(
558 chargingStation
.logPrefix(),
560 if (!isNullOrUndefined(result
)) {
561 limit
= result
?.limit
;
562 chargingProfile
= result
?.chargingProfile
;
563 switch (chargingStation
.getCurrentOutType()) {
566 chargingProfile
?.chargingSchedule
?.chargingRateUnit
=== ChargingRateUnitType
.WATT
568 : ACElectricUtils
.powerTotal(
569 chargingStation
.getNumberOfPhases(),
570 chargingStation
.getVoltageOut(),
576 chargingProfile
?.chargingSchedule
?.chargingRateUnit
=== ChargingRateUnitType
.WATT
578 : DCElectricUtils
.power(chargingStation
.getVoltageOut(), limit
!);
580 const connectorMaximumPower
=
581 chargingStation
.getMaximumPower() / chargingStation
.powerDivider
;
582 if (limit
! > connectorMaximumPower
) {
584 `${chargingStation.logPrefix()} ${moduleName}.getChargingStationConnectorChargingProfilesPowerLimit: Charging profile id ${chargingProfile?.chargingProfileId} limit ${limit} is greater than connector id ${connectorId} maximum ${connectorMaximumPower}: %j`,
587 limit
= connectorMaximumPower
;
594 export const getDefaultVoltageOut
= (
595 currentType
: CurrentType
,
597 templateFile
: string,
599 const errorMsg
= `Unknown ${currentType} currentOutType in template file ${templateFile}, cannot define default voltage out`;
600 let defaultVoltageOut
: number;
601 switch (currentType
) {
603 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
606 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
609 logger
.error(`${logPrefix} ${errorMsg}`);
610 throw new BaseError(errorMsg
);
612 return defaultVoltageOut
;
615 export const getIdTagsFile
= (stationInfo
: ChargingStationInfo
): string | undefined => {
617 stationInfo
.idTagsFile
&&
618 join(dirname(fileURLToPath(import.meta
.url
)), 'assets', basename(stationInfo
.idTagsFile
))
622 export const waitChargingStationEvents
= async (
623 emitter
: EventEmitter
,
624 event
: ChargingStationWorkerMessageEvents
,
625 eventsToWait
: number,
626 ): Promise
<number> => {
627 return new Promise
<number>((resolve
) => {
629 if (eventsToWait
=== 0) {
632 emitter
.on(event
, () => {
634 if (events
=== eventsToWait
) {
641 const getConfiguredMaxNumberOfConnectors
= (stationTemplate
: ChargingStationTemplate
): number => {
642 let configuredMaxNumberOfConnectors
= 0;
643 if (isNotEmptyArray(stationTemplate
.numberOfConnectors
) === true) {
644 const numberOfConnectors
= stationTemplate
.numberOfConnectors
as number[];
645 configuredMaxNumberOfConnectors
=
646 numberOfConnectors
[Math.floor(secureRandom() * numberOfConnectors
.length
)];
647 } else if (isUndefined(stationTemplate
.numberOfConnectors
) === false) {
648 configuredMaxNumberOfConnectors
= stationTemplate
.numberOfConnectors
as number;
649 } else if (stationTemplate
.Connectors
&& !stationTemplate
.Evses
) {
650 configuredMaxNumberOfConnectors
= stationTemplate
.Connectors
[0]
651 ? getMaxNumberOfConnectors(stationTemplate
.Connectors
) - 1
652 : getMaxNumberOfConnectors(stationTemplate
.Connectors
);
653 } else if (stationTemplate
.Evses
&& !stationTemplate
.Connectors
) {
654 for (const evse
in stationTemplate
.Evses
) {
658 configuredMaxNumberOfConnectors
+= getMaxNumberOfConnectors(
659 stationTemplate
.Evses
[evse
].Connectors
,
663 return configuredMaxNumberOfConnectors
;
666 const checkConfiguredMaxConnectors
= (
667 configuredMaxConnectors
: number,
669 templateFile
: string,
671 if (configuredMaxConnectors
<= 0) {
673 `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors`,
678 const checkTemplateMaxConnectors
= (
679 templateMaxConnectors
: number,
681 templateFile
: string,
683 if (templateMaxConnectors
=== 0) {
685 `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration`,
687 } else if (templateMaxConnectors
< 0) {
689 `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined`,
694 const initializeConnectorStatus
= (connectorStatus
: ConnectorStatus
): void => {
695 connectorStatus
.availability
= AvailabilityType
.Operative
;
696 connectorStatus
.idTagLocalAuthorized
= false;
697 connectorStatus
.idTagAuthorized
= false;
698 connectorStatus
.transactionRemoteStarted
= false;
699 connectorStatus
.transactionStarted
= false;
700 connectorStatus
.energyActiveImportRegisterValue
= 0;
701 connectorStatus
.transactionEnergyActiveImportRegisterValue
= 0;
702 if (isUndefined(connectorStatus
.chargingProfiles
)) {
703 connectorStatus
.chargingProfiles
= [];
707 const warnDeprecatedTemplateKey
= (
708 template
: ChargingStationTemplate
,
711 templateFile
: string,
714 if (!isUndefined(template
[key
as keyof ChargingStationTemplate
])) {
715 const logMsg
= `Deprecated template key '${key}' usage in file '${templateFile}'${
716 isNotEmptyString(logMsgToAppend) ? `. ${logMsgToAppend}
` : ''
718 logger
.warn(`${logPrefix} ${logMsg}`);
719 console
.warn(chalk
.yellow(`${logMsg}`));
723 const convertDeprecatedTemplateKey
= (
724 template
: ChargingStationTemplate
,
725 deprecatedKey
: string,
728 if (!isUndefined(template
[deprecatedKey
as keyof ChargingStationTemplate
])) {
729 if (!isUndefined(key
)) {
730 (template
as unknown
as Record
<string, unknown
>)[key
!] =
731 template
[deprecatedKey
as keyof ChargingStationTemplate
];
733 delete template
[deprecatedKey
as keyof ChargingStationTemplate
];
737 interface ChargingProfilesLimit
{
739 chargingProfile
: ChargingProfile
;
743 * Charging profiles shall already be sorted by connector id descending then stack level descending
745 * @param chargingStation -
746 * @param connectorId -
747 * @param chargingProfiles -
749 * @returns ChargingProfilesLimit
751 const getLimitFromChargingProfiles
= (
752 chargingStation
: ChargingStation
,
754 chargingProfiles
: ChargingProfile
[],
756 ): ChargingProfilesLimit
| undefined => {
757 const debugLogMsg
= `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Matching charging profile found for power limitation: %j`;
758 const currentDate
= new Date();
759 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
760 for (const chargingProfile
of chargingProfiles
) {
761 const chargingSchedule
= chargingProfile
.chargingSchedule
;
762 if (isNullOrUndefined(chargingSchedule
?.startSchedule
) && connectorStatus
?.transactionStarted
) {
764 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no startSchedule defined. Trying to set it to the connector current transaction start date`,
766 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
767 chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
770 !isNullOrUndefined(chargingSchedule
?.startSchedule
) &&
771 !isDate(chargingSchedule
?.startSchedule
)
774 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} startSchedule property is not a Date instance. Trying to convert it to a Date instance`,
776 chargingSchedule
.startSchedule
= convertToDate(chargingSchedule
?.startSchedule
)!;
779 !isNullOrUndefined(chargingSchedule
?.startSchedule
) &&
780 isNullOrUndefined(chargingSchedule
?.duration
)
783 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no duration defined and will be set to the maximum time allowed`,
785 // OCPP specifies that if duration is not defined, it should be infinite
786 chargingSchedule
.duration
= differenceInSeconds(maxTime
, chargingSchedule
.startSchedule
!);
788 if (!prepareChargingProfileKind(connectorStatus
, chargingProfile
, currentDate
, logPrefix
)) {
791 if (!canProceedChargingProfile(chargingProfile
, currentDate
, logPrefix
)) {
794 // Check if the charging profile is active
796 isWithinInterval(currentDate
, {
797 start
: chargingSchedule
.startSchedule
!,
798 end
: addSeconds(chargingSchedule
.startSchedule
!, chargingSchedule
.duration
!),
801 if (isNotEmptyArray(chargingSchedule
.chargingSchedulePeriod
)) {
802 const chargingSchedulePeriodCompareFn
= (
803 a
: ChargingSchedulePeriod
,
804 b
: ChargingSchedulePeriod
,
805 ) => a
.startPeriod
- b
.startPeriod
;
807 !isArraySorted
<ChargingSchedulePeriod
>(
808 chargingSchedule
.chargingSchedulePeriod
,
809 chargingSchedulePeriodCompareFn
,
813 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} schedule periods are not sorted by start period`,
815 chargingSchedule
.chargingSchedulePeriod
.sort(chargingSchedulePeriodCompareFn
);
817 // Check if the first schedule period startPeriod property is equal to 0
818 if (chargingSchedule
.chargingSchedulePeriod
[0].startPeriod
!== 0) {
820 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} first schedule period start period ${chargingSchedule.chargingSchedulePeriod[0].startPeriod} is not equal to 0`,
824 // Handle only one schedule period
825 if (chargingSchedule
.chargingSchedulePeriod
.length
=== 1) {
826 const result
: ChargingProfilesLimit
= {
827 limit
: chargingSchedule
.chargingSchedulePeriod
[0].limit
,
830 logger
.debug(debugLogMsg
, result
);
833 let previousChargingSchedulePeriod
: ChargingSchedulePeriod
| undefined;
834 // Search for the right schedule period
837 chargingSchedulePeriod
,
838 ] of chargingSchedule
.chargingSchedulePeriod
.entries()) {
839 // Find the right schedule period
842 addSeconds(chargingSchedule
.startSchedule
!, chargingSchedulePeriod
.startPeriod
),
846 // Found the schedule period: previous is the correct one
847 const result
: ChargingProfilesLimit
= {
848 limit
: previousChargingSchedulePeriod
!.limit
,
851 logger
.debug(debugLogMsg
, result
);
854 // Keep a reference to previous one
855 previousChargingSchedulePeriod
= chargingSchedulePeriod
;
856 // Handle the last schedule period within the charging profile duration
858 index
=== chargingSchedule
.chargingSchedulePeriod
.length
- 1 ||
859 (index
< chargingSchedule
.chargingSchedulePeriod
.length
- 1 &&
862 chargingSchedule
.startSchedule
!,
863 chargingSchedule
.chargingSchedulePeriod
[index
+ 1].startPeriod
,
865 chargingSchedule
.startSchedule
!,
866 ) > chargingSchedule
.duration
!)
868 const result
: ChargingProfilesLimit
= {
869 limit
: previousChargingSchedulePeriod
.limit
,
872 logger
.debug(debugLogMsg
, result
);
881 export const prepareChargingProfileKind
= (
882 connectorStatus
: ConnectorStatus
,
883 chargingProfile
: ChargingProfile
,
887 switch (chargingProfile
.chargingProfileKind
) {
888 case ChargingProfileKindType
.RECURRING
:
889 if (!canProceedRecurringChargingProfile(chargingProfile
, logPrefix
)) {
892 prepareRecurringChargingProfile(chargingProfile
, currentDate
, logPrefix
);
894 case ChargingProfileKindType
.RELATIVE
:
895 if (!isNullOrUndefined(chargingProfile
.chargingSchedule
.startSchedule
)) {
897 `${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`,
899 delete chargingProfile
.chargingSchedule
.startSchedule
;
901 if (connectorStatus
?.transactionStarted
) {
902 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
904 // FIXME: Handle relative charging profile duration
910 export const canProceedChargingProfile
= (
911 chargingProfile
: ChargingProfile
,
916 (isValidTime(chargingProfile
.validFrom
) && isBefore(currentDate
, chargingProfile
.validFrom
!)) ||
917 (isValidTime(chargingProfile
.validTo
) && isAfter(currentDate
, chargingProfile
.validTo
!))
920 `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${
921 chargingProfile.chargingProfileId
922 } is not valid for the current date ${currentDate.toISOString()}`,
927 isNullOrUndefined(chargingProfile
.chargingSchedule
.startSchedule
) ||
928 isNullOrUndefined(chargingProfile
.chargingSchedule
.duration
)
931 `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has no startSchedule or duration defined`,
936 !isNullOrUndefined(chargingProfile
.chargingSchedule
.startSchedule
) &&
937 !isValidTime(chargingProfile
.chargingSchedule
.startSchedule
)
940 `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has an invalid startSchedule date defined`,
945 !isNullOrUndefined(chargingProfile
.chargingSchedule
.duration
) &&
946 !Number.isSafeInteger(chargingProfile
.chargingSchedule
.duration
)
949 `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has non integer duration defined`,
956 const canProceedRecurringChargingProfile
= (
957 chargingProfile
: ChargingProfile
,
961 chargingProfile
.chargingProfileKind
=== ChargingProfileKindType
.RECURRING
&&
962 isNullOrUndefined(chargingProfile
.recurrencyKind
)
965 `${logPrefix} ${moduleName}.canProceedRecurringChargingProfile: Recurring charging profile id ${chargingProfile.chargingProfileId} has no recurrencyKind defined`,
969 if (isNullOrUndefined(chargingProfile
.chargingSchedule
.startSchedule
)) {
971 `${logPrefix} ${moduleName}.canProceedRecurringChargingProfile: Recurring charging profile id ${chargingProfile.chargingProfileId} has no startSchedule defined`,
979 * Adjust recurring charging profile startSchedule to the current recurrency time interval if needed
981 * @param chargingProfile -
982 * @param currentDate -
985 const prepareRecurringChargingProfile
= (
986 chargingProfile
: ChargingProfile
,
990 const chargingSchedule
= chargingProfile
.chargingSchedule
;
991 let recurringIntervalTranslated
= false;
992 let recurringInterval
: Interval
;
993 switch (chargingProfile
.recurrencyKind
) {
994 case RecurrencyKindType
.DAILY
:
995 recurringInterval
= {
996 start
: chargingSchedule
.startSchedule
!,
997 end
: addDays(chargingSchedule
.startSchedule
!, 1),
999 checkRecurringChargingProfileDuration(chargingProfile
, recurringInterval
, logPrefix
);
1001 !isWithinInterval(currentDate
, recurringInterval
) &&
1002 isBefore(recurringInterval
.end
, currentDate
)
1004 chargingSchedule
.startSchedule
= addDays(
1005 recurringInterval
.start
,
1006 differenceInDays(currentDate
, recurringInterval
.start
),
1008 recurringInterval
= {
1009 start
: chargingSchedule
.startSchedule
,
1010 end
: addDays(chargingSchedule
.startSchedule
, 1),
1012 recurringIntervalTranslated
= true;
1015 case RecurrencyKindType
.WEEKLY
:
1016 recurringInterval
= {
1017 start
: chargingSchedule
.startSchedule
!,
1018 end
: addWeeks(chargingSchedule
.startSchedule
!, 1),
1020 checkRecurringChargingProfileDuration(chargingProfile
, recurringInterval
, logPrefix
);
1022 !isWithinInterval(currentDate
, recurringInterval
) &&
1023 isBefore(recurringInterval
.end
, currentDate
)
1025 chargingSchedule
.startSchedule
= addWeeks(
1026 recurringInterval
.start
,
1027 differenceInWeeks(currentDate
, recurringInterval
.start
),
1029 recurringInterval
= {
1030 start
: chargingSchedule
.startSchedule
,
1031 end
: addWeeks(chargingSchedule
.startSchedule
, 1),
1033 recurringIntervalTranslated
= true;
1038 `${logPrefix} ${moduleName}.prepareRecurringChargingProfile: Recurring ${chargingProfile.recurrencyKind} charging profile id ${chargingProfile.chargingProfileId} is not supported`,
1041 if (recurringIntervalTranslated
&& !isWithinInterval(currentDate
, recurringInterval
!)) {
1043 `${logPrefix} ${moduleName}.prepareRecurringChargingProfile: Recurring ${
1044 chargingProfile.recurrencyKind
1045 } charging profile id ${chargingProfile.chargingProfileId} recurrency time interval [${toDate(
1046 recurringInterval!.start,
1047 ).toISOString()}, ${toDate(
1048 recurringInterval!.end,
1049 ).toISOString()}] has not been properly translated to current date ${currentDate.toISOString()} `,
1052 return recurringIntervalTranslated
;
1055 const checkRecurringChargingProfileDuration
= (
1056 chargingProfile
: ChargingProfile
,
1060 if (isNullOrUndefined(chargingProfile
.chargingSchedule
.duration
)) {
1062 `${logPrefix} ${moduleName}.checkRecurringChargingProfileDuration: Recurring ${
1063 chargingProfile.chargingProfileKind
1064 } charging profile id ${
1065 chargingProfile.chargingProfileId
1066 } duration is not defined, set it to the recurrency time interval duration ${differenceInSeconds(
1071 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(interval
.end
, interval
.start
);
1073 chargingProfile
.chargingSchedule
.duration
! > differenceInSeconds(interval
.end
, interval
.start
)
1076 `${logPrefix} ${moduleName}.checkRecurringChargingProfileDuration: Recurring ${
1077 chargingProfile.chargingProfileKind
1078 } charging profile id ${chargingProfile.chargingProfileId} duration ${
1079 chargingProfile.chargingSchedule.duration
1080 } is greater than the recurrency time interval duration ${differenceInSeconds(
1085 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(interval
.end
, interval
.start
);
1089 const getRandomSerialNumberSuffix
= (params
?: {
1090 randomBytesLength
?: number;
1091 upperCase
?: boolean;
1093 const randomSerialNumberSuffix
= randomBytes(params
?.randomBytesLength
?? 16).toString('hex');
1094 if (params
?.upperCase
) {
1095 return randomSerialNumberSuffix
.toUpperCase();
1097 return randomSerialNumberSuffix
;