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';
12 type BootNotificationRequest
,
15 ChargingProfileKindType
,
17 type ChargingSchedulePeriod
,
18 type ChargingStationInfo
,
19 type ChargingStationTemplate
,
21 type OCPP16BootNotificationRequest
,
22 type OCPP20BootNotificationRequest
,
35 import { WorkerProcessType
} from
'../worker';
37 const moduleName
= 'ChargingStationUtils';
39 export class ChargingStationUtils
{
40 private constructor() {
41 // This is intentional
44 public static getChargingStationId(
46 stationTemplate
: ChargingStationTemplate
48 // In case of multiple instances: add instance index to charging station id
49 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
50 const idSuffix
= stationTemplate
?.nameSuffix
?? '';
51 const idStr
= `000000000${index.toString()}`;
52 return stationTemplate
?.fixedName
53 ? stationTemplate
.baseName
54 : `${stationTemplate.baseName}-${instanceIndex.toString()}${idStr.substring(
59 public static getHashId(index
: number, stationTemplate
: ChargingStationTemplate
): string {
60 const chargingStationInfo
= {
61 chargePointModel
: stationTemplate
.chargePointModel
,
62 chargePointVendor
: stationTemplate
.chargePointVendor
,
63 ...(!Utils
.isUndefined(stationTemplate
.chargeBoxSerialNumberPrefix
) && {
64 chargeBoxSerialNumber
: stationTemplate
.chargeBoxSerialNumberPrefix
,
66 ...(!Utils
.isUndefined(stationTemplate
.chargePointSerialNumberPrefix
) && {
67 chargePointSerialNumber
: stationTemplate
.chargePointSerialNumberPrefix
,
69 // FIXME?: Should a firmware version change always reference a new configuration file?
70 ...(!Utils
.isUndefined(stationTemplate
.firmwareVersion
) && {
71 firmwareVersion
: stationTemplate
.firmwareVersion
,
73 ...(!Utils
.isUndefined(stationTemplate
.iccid
) && { iccid
: stationTemplate
.iccid
}),
74 ...(!Utils
.isUndefined(stationTemplate
.imsi
) && { imsi
: stationTemplate
.imsi
}),
75 ...(!Utils
.isUndefined(stationTemplate
.meterSerialNumberPrefix
) && {
76 meterSerialNumber
: stationTemplate
.meterSerialNumberPrefix
,
78 ...(!Utils
.isUndefined(stationTemplate
.meterType
) && {
79 meterType
: stationTemplate
.meterType
,
83 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
85 `${JSON.stringify(chargingStationInfo)}${ChargingStationUtils.getChargingStationId(
93 public static checkChargingStation(chargingStation
: ChargingStation
, logPrefix
: string): boolean {
94 if (chargingStation
.started
=== false && chargingStation
.starting
=== false) {
95 logger
.warn(`${logPrefix} charging station is stopped, cannot proceed`);
101 public static getTemplateMaxNumberOfConnectors(stationTemplate
: ChargingStationTemplate
): number {
102 const templateConnectors
= stationTemplate
?.Connectors
;
103 if (!templateConnectors
) {
106 return Object.keys(templateConnectors
).length
;
109 public static checkTemplateMaxConnectors(
110 templateMaxConnectors
: number,
111 templateFile
: string,
114 if (templateMaxConnectors
=== 0) {
116 `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration`
118 } else if (templateMaxConnectors
< 0) {
120 `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined`
125 public static getConfiguredNumberOfConnectors(stationTemplate
: ChargingStationTemplate
): number {
126 let configuredMaxConnectors
: number;
127 if (Utils
.isNotEmptyArray(stationTemplate
.numberOfConnectors
) === true) {
128 const numberOfConnectors
= stationTemplate
.numberOfConnectors
as number[];
129 configuredMaxConnectors
=
130 numberOfConnectors
[Math.floor(Utils
.secureRandom() * numberOfConnectors
.length
)];
131 } else if (Utils
.isUndefined(stationTemplate
.numberOfConnectors
) === false) {
132 configuredMaxConnectors
= stationTemplate
.numberOfConnectors
as number;
134 configuredMaxConnectors
= stationTemplate
?.Connectors
[0]
135 ? ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
) - 1
136 : ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
138 return configuredMaxConnectors
;
141 public static checkConfiguredMaxConnectors(
142 configuredMaxConnectors
: number,
143 templateFile
: string,
146 if (configuredMaxConnectors
<= 0) {
148 `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors`
153 public static createBootNotificationRequest(
154 stationInfo
: ChargingStationInfo
,
155 bootReason
: BootReasonEnumType
= BootReasonEnumType
.PowerUp
156 ): BootNotificationRequest
{
157 const ocppVersion
= stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
158 switch (ocppVersion
) {
159 case OCPPVersion
.VERSION_16
:
161 chargePointModel
: stationInfo
.chargePointModel
,
162 chargePointVendor
: stationInfo
.chargePointVendor
,
163 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
164 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
166 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
167 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
169 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
170 firmwareVersion
: stationInfo
.firmwareVersion
,
172 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
173 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
174 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
175 meterSerialNumber
: stationInfo
.meterSerialNumber
,
177 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
178 meterType
: stationInfo
.meterType
,
180 } as OCPP16BootNotificationRequest
;
181 case OCPPVersion
.VERSION_20
:
182 case OCPPVersion
.VERSION_201
:
186 model
: stationInfo
.chargePointModel
,
187 vendorName
: stationInfo
.chargePointVendor
,
188 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
189 firmwareVersion
: stationInfo
.firmwareVersion
,
191 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
192 serialNumber
: stationInfo
.chargeBoxSerialNumber
,
194 ...((!Utils
.isUndefined(stationInfo
.iccid
) || !Utils
.isUndefined(stationInfo
.imsi
)) && {
196 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
197 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
201 } as OCPP20BootNotificationRequest
;
205 public static workerPoolInUse(): boolean {
206 return [WorkerProcessType
.dynamicPool
, WorkerProcessType
.staticPool
].includes(
207 Configuration
.getWorker().processType
211 public static workerDynamicPoolInUse(): boolean {
212 return Configuration
.getWorker().processType
=== WorkerProcessType
.dynamicPool
;
215 public static warnDeprecatedTemplateKey(
216 template
: ChargingStationTemplate
,
218 templateFile
: string,
222 if (!Utils
.isUndefined(template
[key
])) {
223 const logMsg
= `Deprecated template key '${key}' usage in file '${templateFile}'${
224 Utils.isNotEmptyString(logMsgToAppend) ? `. ${logMsgToAppend}
` : ''
226 logger
.warn(`${logPrefix} ${logMsg}`);
227 console
.warn(chalk
.yellow(`${logMsg}`));
231 public static convertDeprecatedTemplateKey(
232 template
: ChargingStationTemplate
,
233 deprecatedKey
: string,
236 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
237 template
[key
] = template
[deprecatedKey
] as unknown
;
238 delete template
[deprecatedKey
];
242 public static stationTemplateToStationInfo(
243 stationTemplate
: ChargingStationTemplate
244 ): ChargingStationInfo
{
245 stationTemplate
= Utils
.cloneObject(stationTemplate
);
246 delete stationTemplate
.power
;
247 delete stationTemplate
.powerUnit
;
248 delete stationTemplate
.Configuration
;
249 delete stationTemplate
.AutomaticTransactionGenerator
;
250 delete stationTemplate
.chargeBoxSerialNumberPrefix
;
251 delete stationTemplate
.chargePointSerialNumberPrefix
;
252 delete stationTemplate
.meterSerialNumberPrefix
;
253 return stationTemplate
as unknown
as ChargingStationInfo
;
256 public static createStationInfoHash(stationInfo
: ChargingStationInfo
): void {
257 delete stationInfo
.infoHash
;
258 stationInfo
.infoHash
= crypto
259 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
260 .update(JSON
.stringify(stationInfo
))
264 public static createSerialNumber(
265 stationTemplate
: ChargingStationTemplate
,
266 stationInfo
: ChargingStationInfo
,
268 randomSerialNumberUpperCase
?: boolean;
269 randomSerialNumber
?: boolean;
271 randomSerialNumberUpperCase
: true,
272 randomSerialNumber
: true,
275 params
= params
?? {};
276 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
277 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
278 const serialNumberSuffix
= params
?.randomSerialNumber
279 ? ChargingStationUtils
.getRandomSerialNumberSuffix({
280 upperCase
: params
.randomSerialNumberUpperCase
,
283 stationInfo
.chargePointSerialNumber
= Utils
.isNotEmptyString(
284 stationTemplate
?.chargePointSerialNumberPrefix
286 ? `${stationTemplate.chargePointSerialNumberPrefix}${serialNumberSuffix}`
288 stationInfo
.chargeBoxSerialNumber
= Utils
.isNotEmptyString(
289 stationTemplate
?.chargeBoxSerialNumberPrefix
291 ? `${stationTemplate.chargeBoxSerialNumberPrefix}${serialNumberSuffix}`
293 stationInfo
.meterSerialNumber
= Utils
.isNotEmptyString(stationTemplate
?.meterSerialNumberPrefix
)
294 ? `${stationTemplate.meterSerialNumberPrefix}${serialNumberSuffix}`
298 public static propagateSerialNumber(
299 stationTemplate
: ChargingStationTemplate
,
300 stationInfoSrc
: ChargingStationInfo
,
301 stationInfoDst
: ChargingStationInfo
303 if (!stationInfoSrc
|| !stationTemplate
) {
305 'Missing charging station template or existing configuration to propagate serial number'
308 stationTemplate
?.chargePointSerialNumberPrefix
&& stationInfoSrc
?.chargePointSerialNumber
309 ? (stationInfoDst
.chargePointSerialNumber
= stationInfoSrc
.chargePointSerialNumber
)
310 : stationInfoDst
?.chargePointSerialNumber
&& delete stationInfoDst
.chargePointSerialNumber
;
311 stationTemplate
?.chargeBoxSerialNumberPrefix
&& stationInfoSrc
?.chargeBoxSerialNumber
312 ? (stationInfoDst
.chargeBoxSerialNumber
= stationInfoSrc
.chargeBoxSerialNumber
)
313 : stationInfoDst
?.chargeBoxSerialNumber
&& delete stationInfoDst
.chargeBoxSerialNumber
;
314 stationTemplate
?.meterSerialNumberPrefix
&& stationInfoSrc
?.meterSerialNumber
315 ? (stationInfoDst
.meterSerialNumber
= stationInfoSrc
.meterSerialNumber
)
316 : stationInfoDst
?.meterSerialNumber
&& delete stationInfoDst
.meterSerialNumber
;
319 public static getAmperageLimitationUnitDivider(stationInfo
: ChargingStationInfo
): number {
321 switch (stationInfo
.amperageLimitationUnit
) {
322 case AmpereUnits
.DECI_AMPERE
:
325 case AmpereUnits
.CENTI_AMPERE
:
328 case AmpereUnits
.MILLI_AMPERE
:
335 public static getChargingStationConnectorChargingProfilesPowerLimit(
336 chargingStation
: ChargingStation
,
338 ): number | undefined {
339 let limit
: number, matchingChargingProfile
: ChargingProfile
;
340 let chargingProfiles
: ChargingProfile
[] = [];
341 // Get charging profiles for connector and sort by stack level
342 chargingProfiles
= chargingStation
343 .getConnectorStatus(connectorId
)
344 ?.chargingProfiles
?.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
);
345 // Get profiles on connector 0
346 if (chargingStation
.getConnectorStatus(0)?.chargingProfiles
) {
347 chargingProfiles
.push(
349 .getConnectorStatus(0)
350 .chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
353 if (Utils
.isNotEmptyArray(chargingProfiles
)) {
354 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
356 chargingStation
.logPrefix()
358 if (!Utils
.isNullOrUndefined(result
)) {
359 limit
= result
?.limit
;
360 matchingChargingProfile
= result
?.matchingChargingProfile
;
361 switch (chargingStation
.getCurrentOutType()) {
364 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
365 ChargingRateUnitType
.WATT
367 : ACElectricUtils
.powerTotal(
368 chargingStation
.getNumberOfPhases(),
369 chargingStation
.getVoltageOut(),
375 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
376 ChargingRateUnitType
.WATT
378 : DCElectricUtils
.power(chargingStation
.getVoltageOut(), limit
);
380 const connectorMaximumPower
=
381 chargingStation
.getMaximumPower() / chargingStation
.powerDivider
;
382 if (limit
> connectorMaximumPower
) {
384 `${chargingStation.logPrefix()} Charging profile id ${
385 matchingChargingProfile.chargingProfileId
386 } limit ${limit} is greater than connector id ${connectorId} maximum ${connectorMaximumPower}: %j`,
389 limit
= connectorMaximumPower
;
396 public static getDefaultVoltageOut(
397 currentType
: CurrentType
,
398 templateFile
: string,
401 const errMsg
= `Unknown ${currentType} currentOutType in template file ${templateFile}, cannot define default voltage out`;
402 let defaultVoltageOut
: number;
403 switch (currentType
) {
405 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
408 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
411 logger
.error(`${logPrefix} ${errMsg}`);
412 throw new BaseError(errMsg
);
414 return defaultVoltageOut
;
417 public static getIdTagsFile(stationInfo
: ChargingStationInfo
): string | undefined {
419 stationInfo
.idTagsFile
&&
421 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
423 path
.basename(stationInfo
.idTagsFile
)
429 * Charging profiles should already be sorted by connectorId and stack level (highest stack level has priority)
431 * @param chargingProfiles -
435 private static getLimitFromChargingProfiles(
436 chargingProfiles
: ChargingProfile
[],
440 matchingChargingProfile
: ChargingProfile
;
442 const debugLogMsg
= `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Matching charging profile found for power limitation: %j`;
443 for (const chargingProfile
of chargingProfiles
) {
445 const currentMoment
= moment();
446 const chargingSchedule
= chargingProfile
.chargingSchedule
;
447 // Check type (recurring) and if it is already active
448 // Adjust the daily recurring schedule to today
450 chargingProfile
.chargingProfileKind
=== ChargingProfileKindType
.RECURRING
&&
451 chargingProfile
.recurrencyKind
=== RecurrencyKindType
.DAILY
&&
452 currentMoment
.isAfter(chargingSchedule
.startSchedule
)
454 const currentDate
= new Date();
455 chargingSchedule
.startSchedule
= new Date(chargingSchedule
.startSchedule
);
456 chargingSchedule
.startSchedule
.setFullYear(
457 currentDate
.getFullYear(),
458 currentDate
.getMonth(),
459 currentDate
.getDate()
461 // Check if the start of the schedule is yesterday
462 if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
463 chargingSchedule
.startSchedule
.setDate(currentDate
.getDate() - 1);
465 } else if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
468 // Check if the charging profile is active
470 moment(chargingSchedule
.startSchedule
)
471 .add(chargingSchedule
.duration
, 's')
472 .isAfter(currentMoment
)
474 let lastButOneSchedule
: ChargingSchedulePeriod
;
475 // Search the right schedule period
476 for (const schedulePeriod
of chargingSchedule
.chargingSchedulePeriod
) {
477 // Handling of only one period
479 chargingSchedule
.chargingSchedulePeriod
.length
=== 1 &&
480 schedulePeriod
.startPeriod
=== 0
483 limit
: schedulePeriod
.limit
,
484 matchingChargingProfile
: chargingProfile
,
486 logger
.debug(debugLogMsg
, result
);
489 // Find the right schedule period
491 moment(chargingSchedule
.startSchedule
)
492 .add(schedulePeriod
.startPeriod
, 's')
493 .isAfter(currentMoment
)
495 // Found the schedule: last but one is the correct one
497 limit
: lastButOneSchedule
.limit
,
498 matchingChargingProfile
: chargingProfile
,
500 logger
.debug(debugLogMsg
, result
);
504 lastButOneSchedule
= schedulePeriod
;
505 // Handle the last schedule period
507 schedulePeriod
.startPeriod
===
508 chargingSchedule
.chargingSchedulePeriod
[
509 chargingSchedule
.chargingSchedulePeriod
.length
- 1
513 limit
: lastButOneSchedule
.limit
,
514 matchingChargingProfile
: chargingProfile
,
516 logger
.debug(debugLogMsg
, result
);
525 private static getRandomSerialNumberSuffix(params
?: {
526 randomBytesLength
?: number;
529 const randomSerialNumberSuffix
= crypto
530 .randomBytes(params
?.randomBytesLength
?? 16)
532 if (params
?.upperCase
) {
533 return randomSerialNumberSuffix
.toUpperCase();
535 return randomSerialNumberSuffix
;