1 import crypto from
'node:crypto';
2 import path from
'node:path';
3 import { fileURLToPath
} from
'node:url';
5 import chalk from
'chalk';
6 import moment from
'moment';
8 import type { ChargingStation
} from
'./internal';
9 import { BaseError
} from
'../exception';
13 type BootNotificationRequest
,
16 ChargingProfileKindType
,
18 type ChargingSchedulePeriod
,
19 type ChargingStationInfo
,
20 type ChargingStationTemplate
,
24 type OCPP16BootNotificationRequest
,
25 type OCPP20BootNotificationRequest
,
38 import { WorkerProcessType
} from
'../worker';
40 const moduleName
= 'ChargingStationUtils';
42 export class ChargingStationUtils
{
43 private constructor() {
44 // This is intentional
47 public static getChargingStationId(
49 stationTemplate
: ChargingStationTemplate
51 // In case of multiple instances: add instance index to charging station id
52 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
53 const idSuffix
= stationTemplate
?.nameSuffix
?? '';
54 const idStr
= `000000000${index.toString()}`;
55 return stationTemplate
?.fixedName
56 ? stationTemplate
.baseName
57 : `${stationTemplate.baseName}-${instanceIndex.toString()}${idStr.substring(
62 public static getHashId(index
: number, stationTemplate
: ChargingStationTemplate
): string {
63 const chargingStationInfo
= {
64 chargePointModel
: stationTemplate
.chargePointModel
,
65 chargePointVendor
: stationTemplate
.chargePointVendor
,
66 ...(!Utils
.isUndefined(stationTemplate
.chargeBoxSerialNumberPrefix
) && {
67 chargeBoxSerialNumber
: stationTemplate
.chargeBoxSerialNumberPrefix
,
69 ...(!Utils
.isUndefined(stationTemplate
.chargePointSerialNumberPrefix
) && {
70 chargePointSerialNumber
: stationTemplate
.chargePointSerialNumberPrefix
,
72 ...(!Utils
.isUndefined(stationTemplate
.meterSerialNumberPrefix
) && {
73 meterSerialNumber
: stationTemplate
.meterSerialNumberPrefix
,
75 ...(!Utils
.isUndefined(stationTemplate
.meterType
) && {
76 meterType
: stationTemplate
.meterType
,
80 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
82 `${JSON.stringify(chargingStationInfo)}${ChargingStationUtils.getChargingStationId(
90 public static checkChargingStation(chargingStation
: ChargingStation
, logPrefix
: string): boolean {
91 if (chargingStation
.started
=== false && chargingStation
.starting
=== false) {
92 logger
.warn(`${logPrefix} charging station is stopped, cannot proceed`);
98 public static getMaxNumberOfEvses(evses
: Record
<string, EvseTemplate
>): number {
102 return Object.keys(evses
).length
;
105 public static getMaxNumberOfConnectors(connectors
: Record
<string, ConnectorStatus
>): number {
109 return Object.keys(connectors
).length
;
112 public static checkTemplateMaxConnectors(
113 templateMaxConnectors
: number,
114 templateFile
: string,
117 if (templateMaxConnectors
=== 0) {
119 `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration`
121 } else if (templateMaxConnectors
< 0) {
123 `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined`
128 public static getConfiguredNumberOfConnectors(stationInfo
: ChargingStationInfo
): number {
129 let configuredMaxConnectors
: number;
130 if (Utils
.isNotEmptyArray(stationInfo
.numberOfConnectors
) === true) {
131 const numberOfConnectors
= stationInfo
.numberOfConnectors
as number[];
132 configuredMaxConnectors
=
133 numberOfConnectors
[Math.floor(Utils
.secureRandom() * numberOfConnectors
.length
)];
134 } else if (Utils
.isUndefined(stationInfo
.numberOfConnectors
) === false) {
135 configuredMaxConnectors
= stationInfo
.numberOfConnectors
as number;
136 } else if (stationInfo
.Connectors
&& !stationInfo
.Evses
) {
137 configuredMaxConnectors
= stationInfo
?.Connectors
[0]
138 ? ChargingStationUtils
.getMaxNumberOfConnectors(stationInfo
.Connectors
) - 1
139 : ChargingStationUtils
.getMaxNumberOfConnectors(stationInfo
.Connectors
);
140 } else if (stationInfo
.Evses
&& !stationInfo
.Connectors
) {
141 configuredMaxConnectors
= 0;
142 for (const evse
in stationInfo
.Evses
) {
146 configuredMaxConnectors
+= ChargingStationUtils
.getMaxNumberOfConnectors(
147 stationInfo
.Evses
[evse
].Connectors
151 return configuredMaxConnectors
;
154 public static checkConfiguredMaxConnectors(
155 configuredMaxConnectors
: number,
156 templateFile
: string,
159 if (configuredMaxConnectors
<= 0) {
161 `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors`
166 public static checkStationInfoConnectorStatus(
168 connectorStatus
: ConnectorStatus
,
172 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
174 `${logPrefix} Charging station information from template ${templateFile} with connector ${connectorId} status configuration defined, undefine it`
176 delete connectorStatus
.status;
180 public static buildConnectorsMap(
181 connectors
: Record
<string, ConnectorStatus
>,
184 ): Map
<number, ConnectorStatus
> {
185 const connectorsMap
= new Map
<number, ConnectorStatus
>();
186 if (ChargingStationUtils
.getMaxNumberOfConnectors(connectors
) > 0) {
187 for (const connector
in connectors
) {
188 const connectorStatus
= connectors
[connector
];
189 const connectorId
= Utils
.convertToInt(connector
);
190 ChargingStationUtils
.checkStationInfoConnectorStatus(
196 connectorsMap
.set(connectorId
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
200 `${logPrefix} Charging station information from template ${templateFile} with no connectors, cannot build connectors map`
203 return connectorsMap
;
206 public static initializeConnectorsMapStatus(
207 connectors
: Map
<number, ConnectorStatus
>,
210 for (const connectorId
of connectors
.keys()) {
211 if (connectorId
> 0 && connectors
.get(connectorId
)?.transactionStarted
=== true) {
213 `${logPrefix} Connector ${connectorId} at initialization has a transaction started: ${
214 connectors.get(connectorId)?.transactionId
218 if (connectorId
=== 0) {
219 connectors
.get(connectorId
).availability
= AvailabilityType
.Operative
;
220 if (Utils
.isUndefined(connectors
.get(connectorId
)?.chargingProfiles
)) {
221 connectors
.get(connectorId
).chargingProfiles
= [];
225 Utils
.isNullOrUndefined(connectors
.get(connectorId
)?.transactionStarted
)
227 ChargingStationUtils
.initializeConnectorStatus(connectors
.get(connectorId
));
232 public static resetConnectorStatus(connectorStatus
: ConnectorStatus
): void {
233 connectorStatus
.idTagLocalAuthorized
= false;
234 connectorStatus
.idTagAuthorized
= false;
235 connectorStatus
.transactionRemoteStarted
= false;
236 connectorStatus
.transactionStarted
= false;
237 delete connectorStatus
?.localAuthorizeIdTag
;
238 delete connectorStatus
?.authorizeIdTag
;
239 delete connectorStatus
?.transactionId
;
240 delete connectorStatus
?.transactionIdTag
;
241 connectorStatus
.transactionEnergyActiveImportRegisterValue
= 0;
242 delete connectorStatus
?.transactionBeginMeterValue
;
245 public static createBootNotificationRequest(
246 stationInfo
: ChargingStationInfo
,
247 bootReason
: BootReasonEnumType
= BootReasonEnumType
.PowerUp
248 ): BootNotificationRequest
{
249 const ocppVersion
= stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
250 switch (ocppVersion
) {
251 case OCPPVersion
.VERSION_16
:
253 chargePointModel
: stationInfo
.chargePointModel
,
254 chargePointVendor
: stationInfo
.chargePointVendor
,
255 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
256 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
258 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
259 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
261 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
262 firmwareVersion
: stationInfo
.firmwareVersion
,
264 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
265 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
266 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
267 meterSerialNumber
: stationInfo
.meterSerialNumber
,
269 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
270 meterType
: stationInfo
.meterType
,
272 } as OCPP16BootNotificationRequest
;
273 case OCPPVersion
.VERSION_20
:
274 case OCPPVersion
.VERSION_201
:
278 model
: stationInfo
.chargePointModel
,
279 vendorName
: stationInfo
.chargePointVendor
,
280 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
281 firmwareVersion
: stationInfo
.firmwareVersion
,
283 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
284 serialNumber
: stationInfo
.chargeBoxSerialNumber
,
286 ...((!Utils
.isUndefined(stationInfo
.iccid
) || !Utils
.isUndefined(stationInfo
.imsi
)) && {
288 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
289 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
293 } as OCPP20BootNotificationRequest
;
297 public static workerPoolInUse(): boolean {
298 return [WorkerProcessType
.dynamicPool
, WorkerProcessType
.staticPool
].includes(
299 Configuration
.getWorker().processType
303 public static workerDynamicPoolInUse(): boolean {
304 return Configuration
.getWorker().processType
=== WorkerProcessType
.dynamicPool
;
307 public static warnTemplateKeysDeprecation(
308 templateFile
: string,
309 stationTemplate
: ChargingStationTemplate
,
312 const templateKeys
: { key
: string; deprecatedKey
: string }[] = [
313 { key
: 'supervisionUrls', deprecatedKey
: 'supervisionUrl' },
314 { key
: 'idTagsFile', deprecatedKey
: 'authorizationFile' },
316 for (const templateKey
of templateKeys
) {
317 ChargingStationUtils
.warnDeprecatedTemplateKey(
319 templateKey
.deprecatedKey
,
322 `Use '${templateKey.key}' instead`
324 ChargingStationUtils
.convertDeprecatedTemplateKey(
326 templateKey
.deprecatedKey
,
332 public static stationTemplateToStationInfo(
333 stationTemplate
: ChargingStationTemplate
334 ): ChargingStationInfo
{
335 stationTemplate
= Utils
.cloneObject(stationTemplate
);
336 delete stationTemplate
.power
;
337 delete stationTemplate
.powerUnit
;
338 delete stationTemplate
.Configuration
;
339 delete stationTemplate
.AutomaticTransactionGenerator
;
340 delete stationTemplate
.chargeBoxSerialNumberPrefix
;
341 delete stationTemplate
.chargePointSerialNumberPrefix
;
342 delete stationTemplate
.meterSerialNumberPrefix
;
343 return stationTemplate
as unknown
as ChargingStationInfo
;
346 public static createStationInfoHash(stationInfo
: ChargingStationInfo
): void {
347 delete stationInfo
.infoHash
;
348 stationInfo
.infoHash
= crypto
349 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
350 .update(JSON
.stringify(stationInfo
))
354 public static createSerialNumber(
355 stationTemplate
: ChargingStationTemplate
,
356 stationInfo
: ChargingStationInfo
,
358 randomSerialNumberUpperCase
?: boolean;
359 randomSerialNumber
?: boolean;
361 randomSerialNumberUpperCase
: true,
362 randomSerialNumber
: true,
365 params
= params
?? {};
366 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
367 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
368 const serialNumberSuffix
= params
?.randomSerialNumber
369 ? ChargingStationUtils
.getRandomSerialNumberSuffix({
370 upperCase
: params
.randomSerialNumberUpperCase
,
373 stationInfo
.chargePointSerialNumber
= Utils
.isNotEmptyString(
374 stationTemplate
?.chargePointSerialNumberPrefix
376 ? `${stationTemplate.chargePointSerialNumberPrefix}${serialNumberSuffix}`
378 stationInfo
.chargeBoxSerialNumber
= Utils
.isNotEmptyString(
379 stationTemplate
?.chargeBoxSerialNumberPrefix
381 ? `${stationTemplate.chargeBoxSerialNumberPrefix}${serialNumberSuffix}`
383 stationInfo
.meterSerialNumber
= Utils
.isNotEmptyString(stationTemplate
?.meterSerialNumberPrefix
)
384 ? `${stationTemplate.meterSerialNumberPrefix}${serialNumberSuffix}`
388 public static propagateSerialNumber(
389 stationTemplate
: ChargingStationTemplate
,
390 stationInfoSrc
: ChargingStationInfo
,
391 stationInfoDst
: ChargingStationInfo
393 if (!stationInfoSrc
|| !stationTemplate
) {
395 'Missing charging station template or existing configuration to propagate serial number'
398 stationTemplate
?.chargePointSerialNumberPrefix
&& stationInfoSrc
?.chargePointSerialNumber
399 ? (stationInfoDst
.chargePointSerialNumber
= stationInfoSrc
.chargePointSerialNumber
)
400 : stationInfoDst
?.chargePointSerialNumber
&& delete stationInfoDst
.chargePointSerialNumber
;
401 stationTemplate
?.chargeBoxSerialNumberPrefix
&& stationInfoSrc
?.chargeBoxSerialNumber
402 ? (stationInfoDst
.chargeBoxSerialNumber
= stationInfoSrc
.chargeBoxSerialNumber
)
403 : stationInfoDst
?.chargeBoxSerialNumber
&& delete stationInfoDst
.chargeBoxSerialNumber
;
404 stationTemplate
?.meterSerialNumberPrefix
&& stationInfoSrc
?.meterSerialNumber
405 ? (stationInfoDst
.meterSerialNumber
= stationInfoSrc
.meterSerialNumber
)
406 : stationInfoDst
?.meterSerialNumber
&& delete stationInfoDst
.meterSerialNumber
;
409 public static getAmperageLimitationUnitDivider(stationInfo
: ChargingStationInfo
): number {
411 switch (stationInfo
.amperageLimitationUnit
) {
412 case AmpereUnits
.DECI_AMPERE
:
415 case AmpereUnits
.CENTI_AMPERE
:
418 case AmpereUnits
.MILLI_AMPERE
:
425 public static getChargingStationConnectorChargingProfilesPowerLimit(
426 chargingStation
: ChargingStation
,
428 ): number | undefined {
429 let limit
: number, matchingChargingProfile
: ChargingProfile
;
430 // Get charging profiles for connector and sort by stack level
431 const chargingProfiles
=
432 Utils
.cloneObject(chargingStation
.getConnectorStatus(connectorId
)?.chargingProfiles
)?.sort(
433 (a
, b
) => b
.stackLevel
- a
.stackLevel
435 // Get profiles on connector 0
436 if (chargingStation
.getConnectorStatus(0)?.chargingProfiles
) {
437 chargingProfiles
.push(
438 ...Utils
.cloneObject(chargingStation
.getConnectorStatus(0).chargingProfiles
).sort(
439 (a
, b
) => b
.stackLevel
- a
.stackLevel
443 if (Utils
.isNotEmptyArray(chargingProfiles
)) {
444 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
446 chargingStation
.logPrefix()
448 if (!Utils
.isNullOrUndefined(result
)) {
449 limit
= result
?.limit
;
450 matchingChargingProfile
= result
?.matchingChargingProfile
;
451 switch (chargingStation
.getCurrentOutType()) {
454 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
455 ChargingRateUnitType
.WATT
457 : ACElectricUtils
.powerTotal(
458 chargingStation
.getNumberOfPhases(),
459 chargingStation
.getVoltageOut(),
465 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
466 ChargingRateUnitType
.WATT
468 : DCElectricUtils
.power(chargingStation
.getVoltageOut(), limit
);
470 const connectorMaximumPower
=
471 chargingStation
.getMaximumPower() / chargingStation
.powerDivider
;
472 if (limit
> connectorMaximumPower
) {
474 `${chargingStation.logPrefix()} Charging profile id ${
475 matchingChargingProfile.chargingProfileId
476 } limit ${limit} is greater than connector id ${connectorId} maximum ${connectorMaximumPower}: %j`,
479 limit
= connectorMaximumPower
;
486 public static getDefaultVoltageOut(
487 currentType
: CurrentType
,
488 templateFile
: string,
491 const errMsg
= `Unknown ${currentType} currentOutType in template file ${templateFile}, cannot define default voltage out`;
492 let defaultVoltageOut
: number;
493 switch (currentType
) {
495 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
498 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
501 logger
.error(`${logPrefix} ${errMsg}`);
502 throw new BaseError(errMsg
);
504 return defaultVoltageOut
;
507 public static getIdTagsFile(stationInfo
: ChargingStationInfo
): string | undefined {
509 stationInfo
.idTagsFile
&&
511 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
513 path
.basename(stationInfo
.idTagsFile
)
518 private static initializeConnectorStatus(connectorStatus
: ConnectorStatus
): void {
519 connectorStatus
.availability
= AvailabilityType
.Operative
;
520 connectorStatus
.idTagLocalAuthorized
= false;
521 connectorStatus
.idTagAuthorized
= false;
522 connectorStatus
.transactionRemoteStarted
= false;
523 connectorStatus
.transactionStarted
= false;
524 connectorStatus
.energyActiveImportRegisterValue
= 0;
525 connectorStatus
.transactionEnergyActiveImportRegisterValue
= 0;
526 if (Utils
.isUndefined(connectorStatus
.chargingProfiles
)) {
527 connectorStatus
.chargingProfiles
= [];
531 private static warnDeprecatedTemplateKey(
532 template
: ChargingStationTemplate
,
534 templateFile
: string,
538 if (!Utils
.isUndefined(template
[key
])) {
539 const logMsg
= `Deprecated template key '${key}' usage in file '${templateFile}'${
540 Utils.isNotEmptyString(logMsgToAppend) ? `. ${logMsgToAppend}
` : ''
542 logger
.warn(`${logPrefix} ${logMsg}`);
543 console
.warn(chalk
.yellow(`${logMsg}`));
547 private static convertDeprecatedTemplateKey(
548 template
: ChargingStationTemplate
,
549 deprecatedKey
: string,
552 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
553 template
[key
] = template
[deprecatedKey
] as unknown
;
554 delete template
[deprecatedKey
];
559 * Charging profiles should already be sorted by connectorId and stack level (highest stack level has priority)
561 * @param chargingProfiles -
565 private static getLimitFromChargingProfiles(
566 chargingProfiles
: ChargingProfile
[],
570 matchingChargingProfile
: ChargingProfile
;
572 const debugLogMsg
= `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Matching charging profile found for power limitation: %j`;
573 const currentMoment
= moment();
574 const currentDate
= new Date();
575 for (const chargingProfile
of chargingProfiles
) {
577 const chargingSchedule
= chargingProfile
.chargingSchedule
;
578 if (!chargingSchedule
?.startSchedule
) {
580 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not defined in charging profile id ${chargingProfile.chargingProfileId}`
583 // Check type (recurring) and if it is already active
584 // Adjust the daily recurring schedule to today
586 chargingProfile
.chargingProfileKind
=== ChargingProfileKindType
.RECURRING
&&
587 chargingProfile
.recurrencyKind
=== RecurrencyKindType
.DAILY
&&
588 currentMoment
.isAfter(chargingSchedule
.startSchedule
)
590 if (!(chargingSchedule
?.startSchedule
instanceof Date)) {
592 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not a Date object in charging profile id ${chargingProfile.chargingProfileId}. Trying to convert it to a Date object`
594 chargingSchedule
.startSchedule
= new Date(chargingSchedule
.startSchedule
);
596 chargingSchedule
.startSchedule
.setFullYear(
597 currentDate
.getFullYear(),
598 currentDate
.getMonth(),
599 currentDate
.getDate()
601 // Check if the start of the schedule is yesterday
602 if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
603 chargingSchedule
.startSchedule
.setDate(currentDate
.getDate() - 1);
605 } else if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
608 // Check if the charging profile is active
610 moment(chargingSchedule
.startSchedule
)
611 .add(chargingSchedule
.duration
, 's')
612 .isAfter(currentMoment
)
614 let lastButOneSchedule
: ChargingSchedulePeriod
;
615 // Search the right schedule period
616 for (const schedulePeriod
of chargingSchedule
.chargingSchedulePeriod
) {
617 // Handling of only one period
619 chargingSchedule
.chargingSchedulePeriod
.length
=== 1 &&
620 schedulePeriod
.startPeriod
=== 0
623 limit
: schedulePeriod
.limit
,
624 matchingChargingProfile
: chargingProfile
,
626 logger
.debug(debugLogMsg
, result
);
629 // Find the right schedule period
631 moment(chargingSchedule
.startSchedule
)
632 .add(schedulePeriod
.startPeriod
, 's')
633 .isAfter(currentMoment
)
635 // Found the schedule: last but one is the correct one
637 limit
: lastButOneSchedule
.limit
,
638 matchingChargingProfile
: chargingProfile
,
640 logger
.debug(debugLogMsg
, result
);
644 lastButOneSchedule
= schedulePeriod
;
645 // Handle the last schedule period
647 schedulePeriod
.startPeriod
===
648 chargingSchedule
.chargingSchedulePeriod
[
649 chargingSchedule
.chargingSchedulePeriod
.length
- 1
653 limit
: lastButOneSchedule
.limit
,
654 matchingChargingProfile
: chargingProfile
,
656 logger
.debug(debugLogMsg
, result
);
665 private static getRandomSerialNumberSuffix(params
?: {
666 randomBytesLength
?: number;
669 const randomSerialNumberSuffix
= crypto
670 .randomBytes(params
?.randomBytesLength
?? 16)
672 if (params
?.upperCase
) {
673 return randomSerialNumberSuffix
.toUpperCase();
675 return randomSerialNumberSuffix
;