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';
21 import type { ChargingStation
} from
'./ChargingStation';
22 import { BaseError
} from
'../exception';
26 type BootNotificationRequest
,
29 ChargingProfileKindType
,
31 type ChargingSchedulePeriod
,
32 type ChargingStationInfo
,
33 type ChargingStationTemplate
,
34 ChargingStationWorkerMessageEvents
,
35 ConnectorPhaseRotation
,
40 type OCPP16BootNotificationRequest
,
41 type OCPP20BootNotificationRequest
,
63 const moduleName
= 'ChargingStationUtils';
65 export const getChargingStationId
= (
67 stationTemplate
: ChargingStationTemplate
,
69 // In case of multiple instances: add instance index to charging station id
70 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
71 const idSuffix
= stationTemplate
?.nameSuffix
?? '';
72 const idStr
= `000000000${index.toString()}`;
73 return stationTemplate
?.fixedName
74 ? stationTemplate
.baseName
75 : `${stationTemplate.baseName}-${instanceIndex.toString()}${idStr.substring(
80 export const countReservableConnectors
= (connectors
: Map
<number, ConnectorStatus
>) => {
81 let reservableConnectors
= 0;
82 for (const [connectorId
, connectorStatus
] of connectors
) {
83 if (connectorId
=== 0) {
86 if (connectorStatus
.status === ConnectorStatusEnum
.Available
) {
87 ++reservableConnectors
;
90 return reservableConnectors
;
93 export const getHashId
= (index
: number, stationTemplate
: ChargingStationTemplate
): string => {
94 const chargingStationInfo
= {
95 chargePointModel
: stationTemplate
.chargePointModel
,
96 chargePointVendor
: stationTemplate
.chargePointVendor
,
97 ...(!isUndefined(stationTemplate
.chargeBoxSerialNumberPrefix
) && {
98 chargeBoxSerialNumber
: stationTemplate
.chargeBoxSerialNumberPrefix
,
100 ...(!isUndefined(stationTemplate
.chargePointSerialNumberPrefix
) && {
101 chargePointSerialNumber
: stationTemplate
.chargePointSerialNumberPrefix
,
103 ...(!isUndefined(stationTemplate
.meterSerialNumberPrefix
) && {
104 meterSerialNumber
: stationTemplate
.meterSerialNumberPrefix
,
106 ...(!isUndefined(stationTemplate
.meterType
) && {
107 meterType
: stationTemplate
.meterType
,
110 return createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
111 .update(`${JSON.stringify(chargingStationInfo)}${getChargingStationId(index, stationTemplate)}`)
115 export const checkChargingStation
= (
116 chargingStation
: ChargingStation
,
119 if (chargingStation
.started
=== false && chargingStation
.starting
=== false) {
120 logger
.warn(`${logPrefix} charging station is stopped, cannot proceed`);
126 export const getPhaseRotationValue
= (
128 numberOfPhases
: number,
129 ): string | undefined => {
131 if (connectorId
=== 0 && numberOfPhases
=== 0) {
132 return `${connectorId}.${ConnectorPhaseRotation.RST}`;
133 } else if (connectorId
> 0 && numberOfPhases
=== 0) {
134 return `${connectorId}.${ConnectorPhaseRotation.NotApplicable}`;
136 } else if (connectorId
> 0 && numberOfPhases
=== 1) {
137 return `${connectorId}.${ConnectorPhaseRotation.NotApplicable}`;
138 } else if (connectorId
> 0 && numberOfPhases
=== 3) {
139 return `${connectorId}.${ConnectorPhaseRotation.RST}`;
143 export const getMaxNumberOfEvses
= (evses
: Record
<string, EvseTemplate
>): number => {
147 return Object.keys(evses
).length
;
150 const getMaxNumberOfConnectors
= (connectors
: Record
<string, ConnectorStatus
>): number => {
154 return Object.keys(connectors
).length
;
157 export const getBootConnectorStatus
= (
158 chargingStation
: ChargingStation
,
160 connectorStatus
: ConnectorStatus
,
161 ): ConnectorStatusEnum
=> {
162 let connectorBootStatus
: ConnectorStatusEnum
;
164 !connectorStatus
?.status &&
165 (chargingStation
.isChargingStationAvailable() === false ||
166 chargingStation
.isConnectorAvailable(connectorId
) === false)
168 connectorBootStatus
= ConnectorStatusEnum
.Unavailable
;
169 } else if (!connectorStatus
?.status && connectorStatus
?.bootStatus
) {
170 // Set boot status in template at startup
171 connectorBootStatus
= connectorStatus
?.bootStatus
;
172 } else if (connectorStatus
?.status) {
173 // Set previous status at startup
174 connectorBootStatus
= connectorStatus
?.status;
176 // Set default status
177 connectorBootStatus
= ConnectorStatusEnum
.Available
;
179 return connectorBootStatus
;
182 export const checkTemplate
= (
183 stationTemplate
: ChargingStationTemplate
,
185 templateFile
: string,
187 if (isNullOrUndefined(stationTemplate
)) {
188 const errorMsg
= `Failed to read charging station template file ${templateFile}`;
189 logger
.error(`${logPrefix} ${errorMsg}`);
190 throw new BaseError(errorMsg
);
192 if (isEmptyObject(stationTemplate
)) {
193 const errorMsg
= `Empty charging station information from template file ${templateFile}`;
194 logger
.error(`${logPrefix} ${errorMsg}`);
195 throw new BaseError(errorMsg
);
197 if (isEmptyObject(stationTemplate
.AutomaticTransactionGenerator
!)) {
198 stationTemplate
.AutomaticTransactionGenerator
= Constants
.DEFAULT_ATG_CONFIGURATION
;
200 `${logPrefix} Empty automatic transaction generator configuration from template file ${templateFile}, set to default: %j`,
201 Constants
.DEFAULT_ATG_CONFIGURATION
,
204 if (isNullOrUndefined(stationTemplate
.idTagsFile
) || isEmptyString(stationTemplate
.idTagsFile
)) {
206 `${logPrefix} Missing id tags file in template file ${templateFile}. That can lead to issues with the Automatic Transaction Generator`,
211 export const checkConnectorsConfiguration
= (
212 stationTemplate
: ChargingStationTemplate
,
214 templateFile
: string,
216 configuredMaxConnectors
: number;
217 templateMaxConnectors
: number;
218 templateMaxAvailableConnectors
: number;
220 const configuredMaxConnectors
= getConfiguredNumberOfConnectors(stationTemplate
);
221 checkConfiguredMaxConnectors(configuredMaxConnectors
, logPrefix
, templateFile
);
222 const templateMaxConnectors
= getMaxNumberOfConnectors(stationTemplate
.Connectors
!);
223 checkTemplateMaxConnectors(templateMaxConnectors
, logPrefix
, templateFile
);
224 const templateMaxAvailableConnectors
= stationTemplate
.Connectors
![0]
225 ? templateMaxConnectors
- 1
226 : templateMaxConnectors
;
228 configuredMaxConnectors
> templateMaxAvailableConnectors
&&
229 !stationTemplate
?.randomConnectors
232 `${logPrefix} Number of connectors exceeds the number of connector configurations in template ${templateFile}, forcing random connector configurations affectation`,
234 stationTemplate
.randomConnectors
= true;
236 return { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
};
239 export const checkStationInfoConnectorStatus
= (
241 connectorStatus
: ConnectorStatus
,
243 templateFile
: string,
245 if (!isNullOrUndefined(connectorStatus
?.status)) {
247 `${logPrefix} Charging station information from template ${templateFile} with connector id ${connectorId} status configuration defined, undefine it`,
249 delete connectorStatus
.status;
253 export const buildConnectorsMap
= (
254 connectors
: Record
<string, ConnectorStatus
>,
256 templateFile
: string,
257 ): Map
<number, ConnectorStatus
> => {
258 const connectorsMap
= new Map
<number, ConnectorStatus
>();
259 if (getMaxNumberOfConnectors(connectors
) > 0) {
260 for (const connector
in connectors
) {
261 const connectorStatus
= connectors
[connector
];
262 const connectorId
= convertToInt(connector
);
263 checkStationInfoConnectorStatus(connectorId
, connectorStatus
, logPrefix
, templateFile
);
264 connectorsMap
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
268 `${logPrefix} Charging station information from template ${templateFile} with no connectors, cannot build connectors map`,
271 return connectorsMap
;
274 export const initializeConnectorsMapStatus
= (
275 connectors
: Map
<number, ConnectorStatus
>,
278 for (const connectorId
of connectors
.keys()) {
279 if (connectorId
> 0 && connectors
.get(connectorId
)?.transactionStarted
=== true) {
281 `${logPrefix} Connector id ${connectorId} at initialization has a transaction started with id ${connectors.get(
286 if (connectorId
=== 0) {
287 connectors
.get(connectorId
)!.availability
= AvailabilityType
.Operative
;
288 if (isUndefined(connectors
.get(connectorId
)?.chargingProfiles
)) {
289 connectors
.get(connectorId
)!.chargingProfiles
= [];
293 isNullOrUndefined(connectors
.get(connectorId
)?.transactionStarted
)
295 initializeConnectorStatus(connectors
.get(connectorId
)!);
300 export const resetConnectorStatus
= (connectorStatus
: ConnectorStatus
): void => {
301 connectorStatus
.idTagLocalAuthorized
= false;
302 connectorStatus
.idTagAuthorized
= false;
303 connectorStatus
.transactionRemoteStarted
= false;
304 connectorStatus
.transactionStarted
= false;
305 delete connectorStatus
?.localAuthorizeIdTag
;
306 delete connectorStatus
?.authorizeIdTag
;
307 delete connectorStatus
?.transactionId
;
308 delete connectorStatus
?.transactionIdTag
;
309 connectorStatus
.transactionEnergyActiveImportRegisterValue
= 0;
310 delete connectorStatus
?.transactionBeginMeterValue
;
313 export const createBootNotificationRequest
= (
314 stationInfo
: ChargingStationInfo
,
315 bootReason
: BootReasonEnumType
= BootReasonEnumType
.PowerUp
,
316 ): BootNotificationRequest
=> {
317 const ocppVersion
= stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
318 switch (ocppVersion
) {
319 case OCPPVersion
.VERSION_16
:
321 chargePointModel
: stationInfo
.chargePointModel
,
322 chargePointVendor
: stationInfo
.chargePointVendor
,
323 ...(!isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
324 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
326 ...(!isUndefined(stationInfo
.chargePointSerialNumber
) && {
327 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
329 ...(!isUndefined(stationInfo
.firmwareVersion
) && {
330 firmwareVersion
: stationInfo
.firmwareVersion
,
332 ...(!isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
333 ...(!isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
334 ...(!isUndefined(stationInfo
.meterSerialNumber
) && {
335 meterSerialNumber
: stationInfo
.meterSerialNumber
,
337 ...(!isUndefined(stationInfo
.meterType
) && {
338 meterType
: stationInfo
.meterType
,
340 } as OCPP16BootNotificationRequest
;
341 case OCPPVersion
.VERSION_20
:
342 case OCPPVersion
.VERSION_201
:
346 model
: stationInfo
.chargePointModel
,
347 vendorName
: stationInfo
.chargePointVendor
,
348 ...(!isUndefined(stationInfo
.firmwareVersion
) && {
349 firmwareVersion
: stationInfo
.firmwareVersion
,
351 ...(!isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
352 serialNumber
: stationInfo
.chargeBoxSerialNumber
,
354 ...((!isUndefined(stationInfo
.iccid
) || !isUndefined(stationInfo
.imsi
)) && {
356 ...(!isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
357 ...(!isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
361 } as OCPP20BootNotificationRequest
;
365 export const warnTemplateKeysDeprecation
= (
366 stationTemplate
: ChargingStationTemplate
,
368 templateFile
: string,
370 const templateKeys
: { deprecatedKey
: string; key
?: string }[] = [
371 { deprecatedKey
: 'supervisionUrl', key
: 'supervisionUrls' },
372 { deprecatedKey
: 'authorizationFile', key
: 'idTagsFile' },
373 { deprecatedKey
: 'payloadSchemaValidation', key
: 'ocppStrictCompliance' },
375 for (const templateKey
of templateKeys
) {
376 warnDeprecatedTemplateKey(
378 templateKey
.deprecatedKey
,
381 !isUndefined(templateKey
.key
) ? `Use '${templateKey.key}' instead` : undefined,
383 convertDeprecatedTemplateKey(stationTemplate
, templateKey
.deprecatedKey
, templateKey
.key
);
387 export const stationTemplateToStationInfo
= (
388 stationTemplate
: ChargingStationTemplate
,
389 ): ChargingStationInfo
=> {
390 stationTemplate
= cloneObject
<ChargingStationTemplate
>(stationTemplate
);
391 delete stationTemplate
.power
;
392 delete stationTemplate
.powerUnit
;
393 delete stationTemplate
.Connectors
;
394 delete stationTemplate
.Evses
;
395 delete stationTemplate
.Configuration
;
396 delete stationTemplate
.AutomaticTransactionGenerator
;
397 delete stationTemplate
.chargeBoxSerialNumberPrefix
;
398 delete stationTemplate
.chargePointSerialNumberPrefix
;
399 delete stationTemplate
.meterSerialNumberPrefix
;
400 return stationTemplate
as unknown
as ChargingStationInfo
;
403 export const createSerialNumber
= (
404 stationTemplate
: ChargingStationTemplate
,
405 stationInfo
: ChargingStationInfo
,
407 randomSerialNumberUpperCase
?: boolean;
408 randomSerialNumber
?: boolean;
410 randomSerialNumberUpperCase
: true,
411 randomSerialNumber
: true,
414 params
= { ...{ randomSerialNumberUpperCase
: true, randomSerialNumber
: true }, ...params
};
415 const serialNumberSuffix
= params
?.randomSerialNumber
416 ? getRandomSerialNumberSuffix({
417 upperCase
: params
.randomSerialNumberUpperCase
,
420 isNotEmptyString(stationTemplate
?.chargePointSerialNumberPrefix
) &&
421 (stationInfo
.chargePointSerialNumber
= `${stationTemplate.chargePointSerialNumberPrefix}${serialNumberSuffix}`);
422 isNotEmptyString(stationTemplate
?.chargeBoxSerialNumberPrefix
) &&
423 (stationInfo
.chargeBoxSerialNumber
= `${stationTemplate.chargeBoxSerialNumberPrefix}${serialNumberSuffix}`);
424 isNotEmptyString(stationTemplate
?.meterSerialNumberPrefix
) &&
425 (stationInfo
.meterSerialNumber
= `${stationTemplate.meterSerialNumberPrefix}${serialNumberSuffix}`);
428 export const propagateSerialNumber
= (
429 stationTemplate
: ChargingStationTemplate
,
430 stationInfoSrc
: ChargingStationInfo
,
431 stationInfoDst
: ChargingStationInfo
,
433 if (!stationInfoSrc
|| !stationTemplate
) {
435 'Missing charging station template or existing configuration to propagate serial number',
438 stationTemplate
?.chargePointSerialNumberPrefix
&& stationInfoSrc
?.chargePointSerialNumber
439 ? (stationInfoDst
.chargePointSerialNumber
= stationInfoSrc
.chargePointSerialNumber
)
440 : stationInfoDst
?.chargePointSerialNumber
&& delete stationInfoDst
.chargePointSerialNumber
;
441 stationTemplate
?.chargeBoxSerialNumberPrefix
&& stationInfoSrc
?.chargeBoxSerialNumber
442 ? (stationInfoDst
.chargeBoxSerialNumber
= stationInfoSrc
.chargeBoxSerialNumber
)
443 : stationInfoDst
?.chargeBoxSerialNumber
&& delete stationInfoDst
.chargeBoxSerialNumber
;
444 stationTemplate
?.meterSerialNumberPrefix
&& stationInfoSrc
?.meterSerialNumber
445 ? (stationInfoDst
.meterSerialNumber
= stationInfoSrc
.meterSerialNumber
)
446 : stationInfoDst
?.meterSerialNumber
&& delete stationInfoDst
.meterSerialNumber
;
449 export const getAmperageLimitationUnitDivider
= (stationInfo
: ChargingStationInfo
): number => {
451 switch (stationInfo
.amperageLimitationUnit
) {
452 case AmpereUnits
.DECI_AMPERE
:
455 case AmpereUnits
.CENTI_AMPERE
:
458 case AmpereUnits
.MILLI_AMPERE
:
465 export const getChargingStationConnectorChargingProfilesPowerLimit
= (
466 chargingStation
: ChargingStation
,
468 ): number | undefined => {
469 let limit
: number | undefined, matchingChargingProfile
: ChargingProfile
| undefined;
470 // Get charging profiles for connector and sort by stack level
471 const chargingProfiles
=
472 cloneObject
<ChargingProfile
[]>(
473 chargingStation
.getConnectorStatus(connectorId
)!.chargingProfiles
!,
474 )?.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
) ?? [];
475 // Get profiles on connector 0
476 if (chargingStation
.getConnectorStatus(0)?.chargingProfiles
) {
477 chargingProfiles
.push(
478 ...cloneObject
<ChargingProfile
[]>(
479 chargingStation
.getConnectorStatus(0)!.chargingProfiles
!,
480 ).sort((a
, b
) => b
.stackLevel
- a
.stackLevel
),
483 if (isNotEmptyArray(chargingProfiles
)) {
484 const result
= getLimitFromChargingProfiles(chargingProfiles
, chargingStation
.logPrefix());
485 if (!isNullOrUndefined(result
)) {
486 limit
= result
?.limit
;
487 matchingChargingProfile
= result
?.matchingChargingProfile
;
488 switch (chargingStation
.getCurrentOutType()) {
491 matchingChargingProfile
?.chargingSchedule
?.chargingRateUnit
===
492 ChargingRateUnitType
.WATT
494 : ACElectricUtils
.powerTotal(
495 chargingStation
.getNumberOfPhases(),
496 chargingStation
.getVoltageOut(),
502 matchingChargingProfile
?.chargingSchedule
?.chargingRateUnit
===
503 ChargingRateUnitType
.WATT
505 : DCElectricUtils
.power(chargingStation
.getVoltageOut(), limit
!);
507 const connectorMaximumPower
=
508 chargingStation
.getMaximumPower() / chargingStation
.powerDivider
;
509 if (limit
! > connectorMaximumPower
) {
511 `${chargingStation.logPrefix()} Charging profile id ${matchingChargingProfile?.chargingProfileId} limit ${limit} is greater than connector id ${connectorId} maximum ${connectorMaximumPower}: %j`,
514 limit
= connectorMaximumPower
;
521 export const getDefaultVoltageOut
= (
522 currentType
: CurrentType
,
524 templateFile
: string,
526 const errorMsg
= `Unknown ${currentType} currentOutType in template file ${templateFile}, cannot define default voltage out`;
527 let defaultVoltageOut
: number;
528 switch (currentType
) {
530 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
533 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
536 logger
.error(`${logPrefix} ${errorMsg}`);
537 throw new BaseError(errorMsg
);
539 return defaultVoltageOut
;
542 export const getIdTagsFile
= (stationInfo
: ChargingStationInfo
): string | undefined => {
544 stationInfo
.idTagsFile
&&
545 join(dirname(fileURLToPath(import.meta
.url
)), 'assets', basename(stationInfo
.idTagsFile
))
549 export const waitChargingStationEvents
= async (
550 emitter
: EventEmitter
,
551 event
: ChargingStationWorkerMessageEvents
,
552 eventsToWait
: number,
553 ): Promise
<number> => {
554 return new Promise
<number>((resolve
) => {
556 if (eventsToWait
=== 0) {
559 emitter
.on(event
, () => {
561 if (events
=== eventsToWait
) {
568 const getConfiguredNumberOfConnectors
= (stationTemplate
: ChargingStationTemplate
): number => {
569 let configuredMaxConnectors
= 0;
570 if (isNotEmptyArray(stationTemplate
.numberOfConnectors
) === true) {
571 const numberOfConnectors
= stationTemplate
.numberOfConnectors
as number[];
572 configuredMaxConnectors
=
573 numberOfConnectors
[Math.floor(secureRandom() * numberOfConnectors
.length
)];
574 } else if (isUndefined(stationTemplate
.numberOfConnectors
) === false) {
575 configuredMaxConnectors
= stationTemplate
.numberOfConnectors
as number;
576 } else if (stationTemplate
.Connectors
&& !stationTemplate
.Evses
) {
577 configuredMaxConnectors
= stationTemplate
.Connectors
[0]
578 ? getMaxNumberOfConnectors(stationTemplate
.Connectors
) - 1
579 : getMaxNumberOfConnectors(stationTemplate
.Connectors
);
580 } else if (stationTemplate
.Evses
&& !stationTemplate
.Connectors
) {
581 for (const evse
in stationTemplate
.Evses
) {
585 configuredMaxConnectors
+= getMaxNumberOfConnectors(stationTemplate
.Evses
[evse
].Connectors
);
588 return configuredMaxConnectors
;
591 const checkConfiguredMaxConnectors
= (
592 configuredMaxConnectors
: number,
594 templateFile
: string,
596 if (configuredMaxConnectors
<= 0) {
598 `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors`,
603 const checkTemplateMaxConnectors
= (
604 templateMaxConnectors
: number,
606 templateFile
: string,
608 if (templateMaxConnectors
=== 0) {
610 `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration`,
612 } else if (templateMaxConnectors
< 0) {
614 `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined`,
619 const initializeConnectorStatus
= (connectorStatus
: ConnectorStatus
): void => {
620 connectorStatus
.availability
= AvailabilityType
.Operative
;
621 connectorStatus
.idTagLocalAuthorized
= false;
622 connectorStatus
.idTagAuthorized
= false;
623 connectorStatus
.transactionRemoteStarted
= false;
624 connectorStatus
.transactionStarted
= false;
625 connectorStatus
.energyActiveImportRegisterValue
= 0;
626 connectorStatus
.transactionEnergyActiveImportRegisterValue
= 0;
627 if (isUndefined(connectorStatus
.chargingProfiles
)) {
628 connectorStatus
.chargingProfiles
= [];
632 const warnDeprecatedTemplateKey
= (
633 template
: ChargingStationTemplate
,
636 templateFile
: string,
639 if (!isUndefined(template
[key
as keyof ChargingStationTemplate
])) {
640 const logMsg
= `Deprecated template key '${key}' usage in file '${templateFile}'${
641 isNotEmptyString(logMsgToAppend) ? `. ${logMsgToAppend}
` : ''
643 logger
.warn(`${logPrefix} ${logMsg}`);
644 console
.warn(chalk
.yellow(`${logMsg}`));
648 const convertDeprecatedTemplateKey
= (
649 template
: ChargingStationTemplate
,
650 deprecatedKey
: string,
653 if (!isUndefined(template
[deprecatedKey
as keyof ChargingStationTemplate
])) {
654 if (!isUndefined(key
)) {
655 (template
as unknown
as Record
<string, unknown
>)[key
!] =
656 template
[deprecatedKey
as keyof ChargingStationTemplate
];
658 delete template
[deprecatedKey
as keyof ChargingStationTemplate
];
663 * Charging profiles should already be sorted by connector id and stack level (highest stack level has priority)
665 * @param chargingProfiles -
669 const getLimitFromChargingProfiles
= (
670 chargingProfiles
: ChargingProfile
[],
675 matchingChargingProfile
: ChargingProfile
;
678 const debugLogMsg
= `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Matching charging profile found for power limitation: %j`;
679 const currentDate
= new Date();
680 for (const chargingProfile
of chargingProfiles
) {
682 const chargingSchedule
= chargingProfile
.chargingSchedule
;
683 if (!chargingSchedule
?.startSchedule
) {
685 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not defined in charging profile id ${chargingProfile.chargingProfileId}`,
688 if (!(chargingSchedule
?.startSchedule
instanceof Date)) {
690 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not a Date object in charging profile id ${chargingProfile.chargingProfileId}. Trying to convert it to a Date object`,
692 chargingSchedule
.startSchedule
= convertToDate(chargingSchedule
.startSchedule
)!;
694 // Adjust recurring schedule
695 if (chargingProfile
.chargingProfileKind
=== ChargingProfileKindType
.RECURRING
) {
696 switch (chargingProfile
.recurrencyKind
) {
697 case RecurrencyKindType
.DAILY
:
698 if (isYesterday(chargingSchedule
.startSchedule
)) {
699 addDays(chargingSchedule
.startSchedule
, 1);
700 } else if (isTomorrow(chargingSchedule
.startSchedule
)) {
701 subDays(chargingSchedule
.startSchedule
, 1);
704 case RecurrencyKindType
.WEEKLY
:
705 if (isBefore(chargingSchedule
.startSchedule
, startOfWeek(currentDate
))) {
706 addWeeks(chargingSchedule
.startSchedule
, 1);
707 } else if (isAfter(chargingSchedule
.startSchedule
, endOfWeek(currentDate
))) {
708 subWeeks(chargingSchedule
.startSchedule
, 1);
713 // Check if the charging profile is active
715 isAfter(addSeconds(chargingSchedule
.startSchedule
, chargingSchedule
.duration
!), currentDate
)
717 let lastButOneSchedule
: ChargingSchedulePeriod
| undefined;
718 // Search the right schedule period
719 for (const schedulePeriod
of chargingSchedule
.chargingSchedulePeriod
) {
720 // Handling of only one period
722 chargingSchedule
.chargingSchedulePeriod
.length
=== 1 &&
723 schedulePeriod
.startPeriod
=== 0
726 limit
: schedulePeriod
.limit
,
727 matchingChargingProfile
: chargingProfile
,
729 logger
.debug(debugLogMsg
, result
);
732 // Find the right schedule period
735 addSeconds(chargingSchedule
.startSchedule
, schedulePeriod
.startPeriod
),
739 // Found the schedule: last but one is the correct one
741 limit
: lastButOneSchedule
!.limit
,
742 matchingChargingProfile
: chargingProfile
,
744 logger
.debug(debugLogMsg
, result
);
748 lastButOneSchedule
= schedulePeriod
;
749 // Handle the last schedule period
751 schedulePeriod
.startPeriod
===
752 chargingSchedule
.chargingSchedulePeriod
[
753 chargingSchedule
.chargingSchedulePeriod
.length
- 1
757 limit
: lastButOneSchedule
.limit
,
758 matchingChargingProfile
: chargingProfile
,
760 logger
.debug(debugLogMsg
, result
);
768 const getRandomSerialNumberSuffix
= (params
?: {
769 randomBytesLength
?: number;
772 const randomSerialNumberSuffix
= randomBytes(params
?.randomBytesLength
?? 16).toString('hex');
773 if (params
?.upperCase
) {
774 return randomSerialNumberSuffix
.toUpperCase();
776 return randomSerialNumberSuffix
;