fix: warn abount unsupported charging profiles structure
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationUtils.ts
... / ...
CommitLineData
1import { createHash, randomBytes } from 'node:crypto';
2import type { EventEmitter } from 'node:events';
3import { basename, dirname, join } from 'node:path';
4import { fileURLToPath } from 'node:url';
5
6import chalk from 'chalk';
7import {
8 addDays,
9 addSeconds,
10 addWeeks,
11 differenceInDays,
12 differenceInSeconds,
13 differenceInWeeks,
14 isAfter,
15 isBefore,
16 isWithinInterval,
17 toDate,
18} from 'date-fns';
19
20import type { ChargingStation } from './ChargingStation';
21import { BaseError } from '../exception';
22import {
23 AmpereUnits,
24 AvailabilityType,
25 type BootNotificationRequest,
26 BootReasonEnumType,
27 type ChargingProfile,
28 ChargingProfileKindType,
29 ChargingRateUnitType,
30 type ChargingSchedulePeriod,
31 type ChargingStationInfo,
32 type ChargingStationTemplate,
33 ChargingStationWorkerMessageEvents,
34 ConnectorPhaseRotation,
35 type ConnectorStatus,
36 ConnectorStatusEnum,
37 CurrentType,
38 type EvseTemplate,
39 type OCPP16BootNotificationRequest,
40 type OCPP20BootNotificationRequest,
41 OCPPVersion,
42 RecurrencyKindType,
43 Voltage,
44} from '../types';
45import {
46 ACElectricUtils,
47 Constants,
48 DCElectricUtils,
49 cloneObject,
50 convertToDate,
51 convertToInt,
52 isArraySorted,
53 isEmptyObject,
54 isEmptyString,
55 isNotEmptyArray,
56 isNotEmptyString,
57 isNullOrUndefined,
58 isUndefined,
59 isValidDate,
60 logger,
61 secureRandom,
62} from '../utils';
63
64const moduleName = 'ChargingStationUtils';
65
66export const getChargingStationId = (
67 index: number,
68 stationTemplate: ChargingStationTemplate,
69): string => {
70 // In case of multiple instances: add instance index to charging station id
71 const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
72 const idSuffix = stationTemplate?.nameSuffix ?? '';
73 const idStr = `000000000${index.toString()}`;
74 return stationTemplate?.fixedName
75 ? stationTemplate.baseName
76 : `${stationTemplate.baseName}-${instanceIndex.toString()}${idStr.substring(
77 idStr.length - 4,
78 )}${idSuffix}`;
79};
80
81export const countReservableConnectors = (connectors: Map<number, ConnectorStatus>) => {
82 let reservableConnectors = 0;
83 for (const [connectorId, connectorStatus] of connectors) {
84 if (connectorId === 0) {
85 continue;
86 }
87 if (connectorStatus.status === ConnectorStatusEnum.Available) {
88 ++reservableConnectors;
89 }
90 }
91 return reservableConnectors;
92};
93
94export const getHashId = (index: number, stationTemplate: ChargingStationTemplate): string => {
95 const chargingStationInfo = {
96 chargePointModel: stationTemplate.chargePointModel,
97 chargePointVendor: stationTemplate.chargePointVendor,
98 ...(!isUndefined(stationTemplate.chargeBoxSerialNumberPrefix) && {
99 chargeBoxSerialNumber: stationTemplate.chargeBoxSerialNumberPrefix,
100 }),
101 ...(!isUndefined(stationTemplate.chargePointSerialNumberPrefix) && {
102 chargePointSerialNumber: stationTemplate.chargePointSerialNumberPrefix,
103 }),
104 ...(!isUndefined(stationTemplate.meterSerialNumberPrefix) && {
105 meterSerialNumber: stationTemplate.meterSerialNumberPrefix,
106 }),
107 ...(!isUndefined(stationTemplate.meterType) && {
108 meterType: stationTemplate.meterType,
109 }),
110 };
111 return createHash(Constants.DEFAULT_HASH_ALGORITHM)
112 .update(`${JSON.stringify(chargingStationInfo)}${getChargingStationId(index, stationTemplate)}`)
113 .digest('hex');
114};
115
116export const checkChargingStation = (
117 chargingStation: ChargingStation,
118 logPrefix: string,
119): boolean => {
120 if (chargingStation.started === false && chargingStation.starting === false) {
121 logger.warn(`${logPrefix} charging station is stopped, cannot proceed`);
122 return false;
123 }
124 return true;
125};
126
127export const getPhaseRotationValue = (
128 connectorId: number,
129 numberOfPhases: number,
130): string | undefined => {
131 // AC/DC
132 if (connectorId === 0 && numberOfPhases === 0) {
133 return `${connectorId}.${ConnectorPhaseRotation.RST}`;
134 } else if (connectorId > 0 && numberOfPhases === 0) {
135 return `${connectorId}.${ConnectorPhaseRotation.NotApplicable}`;
136 // AC
137 } else if (connectorId > 0 && numberOfPhases === 1) {
138 return `${connectorId}.${ConnectorPhaseRotation.NotApplicable}`;
139 } else if (connectorId > 0 && numberOfPhases === 3) {
140 return `${connectorId}.${ConnectorPhaseRotation.RST}`;
141 }
142};
143
144export const getMaxNumberOfEvses = (evses: Record<string, EvseTemplate>): number => {
145 if (!evses) {
146 return -1;
147 }
148 return Object.keys(evses).length;
149};
150
151const getMaxNumberOfConnectors = (connectors: Record<string, ConnectorStatus>): number => {
152 if (!connectors) {
153 return -1;
154 }
155 return Object.keys(connectors).length;
156};
157
158export const getBootConnectorStatus = (
159 chargingStation: ChargingStation,
160 connectorId: number,
161 connectorStatus: ConnectorStatus,
162): ConnectorStatusEnum => {
163 let connectorBootStatus: ConnectorStatusEnum;
164 if (
165 !connectorStatus?.status &&
166 (chargingStation.isChargingStationAvailable() === false ||
167 chargingStation.isConnectorAvailable(connectorId) === false)
168 ) {
169 connectorBootStatus = ConnectorStatusEnum.Unavailable;
170 } else if (!connectorStatus?.status && connectorStatus?.bootStatus) {
171 // Set boot status in template at startup
172 connectorBootStatus = connectorStatus?.bootStatus;
173 } else if (connectorStatus?.status) {
174 // Set previous status at startup
175 connectorBootStatus = connectorStatus?.status;
176 } else {
177 // Set default status
178 connectorBootStatus = ConnectorStatusEnum.Available;
179 }
180 return connectorBootStatus;
181};
182
183export const checkTemplate = (
184 stationTemplate: ChargingStationTemplate,
185 logPrefix: string,
186 templateFile: string,
187): void => {
188 if (isNullOrUndefined(stationTemplate)) {
189 const errorMsg = `Failed to read charging station template file ${templateFile}`;
190 logger.error(`${logPrefix} ${errorMsg}`);
191 throw new BaseError(errorMsg);
192 }
193 if (isEmptyObject(stationTemplate)) {
194 const errorMsg = `Empty charging station information from template file ${templateFile}`;
195 logger.error(`${logPrefix} ${errorMsg}`);
196 throw new BaseError(errorMsg);
197 }
198 if (isEmptyObject(stationTemplate.AutomaticTransactionGenerator!)) {
199 stationTemplate.AutomaticTransactionGenerator = Constants.DEFAULT_ATG_CONFIGURATION;
200 logger.warn(
201 `${logPrefix} Empty automatic transaction generator configuration from template file ${templateFile}, set to default: %j`,
202 Constants.DEFAULT_ATG_CONFIGURATION,
203 );
204 }
205 if (isNullOrUndefined(stationTemplate.idTagsFile) || isEmptyString(stationTemplate.idTagsFile)) {
206 logger.warn(
207 `${logPrefix} Missing id tags file in template file ${templateFile}. That can lead to issues with the Automatic Transaction Generator`,
208 );
209 }
210};
211
212export const checkConnectorsConfiguration = (
213 stationTemplate: ChargingStationTemplate,
214 logPrefix: string,
215 templateFile: string,
216): {
217 configuredMaxConnectors: number;
218 templateMaxConnectors: number;
219 templateMaxAvailableConnectors: number;
220} => {
221 const configuredMaxConnectors = getConfiguredNumberOfConnectors(stationTemplate);
222 checkConfiguredMaxConnectors(configuredMaxConnectors, logPrefix, templateFile);
223 const templateMaxConnectors = getMaxNumberOfConnectors(stationTemplate.Connectors!);
224 checkTemplateMaxConnectors(templateMaxConnectors, logPrefix, templateFile);
225 const templateMaxAvailableConnectors = stationTemplate.Connectors![0]
226 ? templateMaxConnectors - 1
227 : templateMaxConnectors;
228 if (
229 configuredMaxConnectors > templateMaxAvailableConnectors &&
230 !stationTemplate?.randomConnectors
231 ) {
232 logger.warn(
233 `${logPrefix} Number of connectors exceeds the number of connector configurations in template ${templateFile}, forcing random connector configurations affectation`,
234 );
235 stationTemplate.randomConnectors = true;
236 }
237 return { configuredMaxConnectors, templateMaxConnectors, templateMaxAvailableConnectors };
238};
239
240export const checkStationInfoConnectorStatus = (
241 connectorId: number,
242 connectorStatus: ConnectorStatus,
243 logPrefix: string,
244 templateFile: string,
245): void => {
246 if (!isNullOrUndefined(connectorStatus?.status)) {
247 logger.warn(
248 `${logPrefix} Charging station information from template ${templateFile} with connector id ${connectorId} status configuration defined, undefine it`,
249 );
250 delete connectorStatus.status;
251 }
252};
253
254export const buildConnectorsMap = (
255 connectors: Record<string, ConnectorStatus>,
256 logPrefix: string,
257 templateFile: string,
258): Map<number, ConnectorStatus> => {
259 const connectorsMap = new Map<number, ConnectorStatus>();
260 if (getMaxNumberOfConnectors(connectors) > 0) {
261 for (const connector in connectors) {
262 const connectorStatus = connectors[connector];
263 const connectorId = convertToInt(connector);
264 checkStationInfoConnectorStatus(connectorId, connectorStatus, logPrefix, templateFile);
265 connectorsMap.set(connectorId, cloneObject<ConnectorStatus>(connectorStatus));
266 }
267 } else {
268 logger.warn(
269 `${logPrefix} Charging station information from template ${templateFile} with no connectors, cannot build connectors map`,
270 );
271 }
272 return connectorsMap;
273};
274
275export const initializeConnectorsMapStatus = (
276 connectors: Map<number, ConnectorStatus>,
277 logPrefix: string,
278): void => {
279 for (const connectorId of connectors.keys()) {
280 if (connectorId > 0 && connectors.get(connectorId)?.transactionStarted === true) {
281 logger.warn(
282 `${logPrefix} Connector id ${connectorId} at initialization has a transaction started with id ${connectors.get(
283 connectorId,
284 )?.transactionId}`,
285 );
286 }
287 if (connectorId === 0) {
288 connectors.get(connectorId)!.availability = AvailabilityType.Operative;
289 if (isUndefined(connectors.get(connectorId)?.chargingProfiles)) {
290 connectors.get(connectorId)!.chargingProfiles = [];
291 }
292 } else if (
293 connectorId > 0 &&
294 isNullOrUndefined(connectors.get(connectorId)?.transactionStarted)
295 ) {
296 initializeConnectorStatus(connectors.get(connectorId)!);
297 }
298 }
299};
300
301export const resetConnectorStatus = (connectorStatus: ConnectorStatus): void => {
302 connectorStatus.idTagLocalAuthorized = false;
303 connectorStatus.idTagAuthorized = false;
304 connectorStatus.transactionRemoteStarted = false;
305 connectorStatus.transactionStarted = false;
306 delete connectorStatus?.transactionStart;
307 delete connectorStatus?.transactionId;
308 delete connectorStatus?.localAuthorizeIdTag;
309 delete connectorStatus?.authorizeIdTag;
310 delete connectorStatus?.transactionIdTag;
311 connectorStatus.transactionEnergyActiveImportRegisterValue = 0;
312 delete connectorStatus?.transactionBeginMeterValue;
313};
314
315export const createBootNotificationRequest = (
316 stationInfo: ChargingStationInfo,
317 bootReason: BootReasonEnumType = BootReasonEnumType.PowerUp,
318): BootNotificationRequest => {
319 const ocppVersion = stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
320 switch (ocppVersion) {
321 case OCPPVersion.VERSION_16:
322 return {
323 chargePointModel: stationInfo.chargePointModel,
324 chargePointVendor: stationInfo.chargePointVendor,
325 ...(!isUndefined(stationInfo.chargeBoxSerialNumber) && {
326 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumber,
327 }),
328 ...(!isUndefined(stationInfo.chargePointSerialNumber) && {
329 chargePointSerialNumber: stationInfo.chargePointSerialNumber,
330 }),
331 ...(!isUndefined(stationInfo.firmwareVersion) && {
332 firmwareVersion: stationInfo.firmwareVersion,
333 }),
334 ...(!isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
335 ...(!isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
336 ...(!isUndefined(stationInfo.meterSerialNumber) && {
337 meterSerialNumber: stationInfo.meterSerialNumber,
338 }),
339 ...(!isUndefined(stationInfo.meterType) && {
340 meterType: stationInfo.meterType,
341 }),
342 } as OCPP16BootNotificationRequest;
343 case OCPPVersion.VERSION_20:
344 case OCPPVersion.VERSION_201:
345 return {
346 reason: bootReason,
347 chargingStation: {
348 model: stationInfo.chargePointModel,
349 vendorName: stationInfo.chargePointVendor,
350 ...(!isUndefined(stationInfo.firmwareVersion) && {
351 firmwareVersion: stationInfo.firmwareVersion,
352 }),
353 ...(!isUndefined(stationInfo.chargeBoxSerialNumber) && {
354 serialNumber: stationInfo.chargeBoxSerialNumber,
355 }),
356 ...((!isUndefined(stationInfo.iccid) || !isUndefined(stationInfo.imsi)) && {
357 modem: {
358 ...(!isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
359 ...(!isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
360 },
361 }),
362 },
363 } as OCPP20BootNotificationRequest;
364 }
365};
366
367export const warnTemplateKeysDeprecation = (
368 stationTemplate: ChargingStationTemplate,
369 logPrefix: string,
370 templateFile: string,
371) => {
372 const templateKeys: { deprecatedKey: string; key?: string }[] = [
373 { deprecatedKey: 'supervisionUrl', key: 'supervisionUrls' },
374 { deprecatedKey: 'authorizationFile', key: 'idTagsFile' },
375 { deprecatedKey: 'payloadSchemaValidation', key: 'ocppStrictCompliance' },
376 ];
377 for (const templateKey of templateKeys) {
378 warnDeprecatedTemplateKey(
379 stationTemplate,
380 templateKey.deprecatedKey,
381 logPrefix,
382 templateFile,
383 !isUndefined(templateKey.key) ? `Use '${templateKey.key}' instead` : undefined,
384 );
385 convertDeprecatedTemplateKey(stationTemplate, templateKey.deprecatedKey, templateKey.key);
386 }
387};
388
389export const stationTemplateToStationInfo = (
390 stationTemplate: ChargingStationTemplate,
391): ChargingStationInfo => {
392 stationTemplate = cloneObject<ChargingStationTemplate>(stationTemplate);
393 delete stationTemplate.power;
394 delete stationTemplate.powerUnit;
395 delete stationTemplate.Connectors;
396 delete stationTemplate.Evses;
397 delete stationTemplate.Configuration;
398 delete stationTemplate.AutomaticTransactionGenerator;
399 delete stationTemplate.chargeBoxSerialNumberPrefix;
400 delete stationTemplate.chargePointSerialNumberPrefix;
401 delete stationTemplate.meterSerialNumberPrefix;
402 return stationTemplate as unknown as ChargingStationInfo;
403};
404
405export const createSerialNumber = (
406 stationTemplate: ChargingStationTemplate,
407 stationInfo: ChargingStationInfo,
408 params: {
409 randomSerialNumberUpperCase?: boolean;
410 randomSerialNumber?: boolean;
411 } = {
412 randomSerialNumberUpperCase: true,
413 randomSerialNumber: true,
414 },
415): void => {
416 params = { ...{ randomSerialNumberUpperCase: true, randomSerialNumber: true }, ...params };
417 const serialNumberSuffix = params?.randomSerialNumber
418 ? getRandomSerialNumberSuffix({
419 upperCase: params.randomSerialNumberUpperCase,
420 })
421 : '';
422 isNotEmptyString(stationTemplate?.chargePointSerialNumberPrefix) &&
423 (stationInfo.chargePointSerialNumber = `${stationTemplate.chargePointSerialNumberPrefix}${serialNumberSuffix}`);
424 isNotEmptyString(stationTemplate?.chargeBoxSerialNumberPrefix) &&
425 (stationInfo.chargeBoxSerialNumber = `${stationTemplate.chargeBoxSerialNumberPrefix}${serialNumberSuffix}`);
426 isNotEmptyString(stationTemplate?.meterSerialNumberPrefix) &&
427 (stationInfo.meterSerialNumber = `${stationTemplate.meterSerialNumberPrefix}${serialNumberSuffix}`);
428};
429
430export const propagateSerialNumber = (
431 stationTemplate: ChargingStationTemplate,
432 stationInfoSrc: ChargingStationInfo,
433 stationInfoDst: ChargingStationInfo,
434) => {
435 if (!stationInfoSrc || !stationTemplate) {
436 throw new BaseError(
437 'Missing charging station template or existing configuration to propagate serial number',
438 );
439 }
440 stationTemplate?.chargePointSerialNumberPrefix && stationInfoSrc?.chargePointSerialNumber
441 ? (stationInfoDst.chargePointSerialNumber = stationInfoSrc.chargePointSerialNumber)
442 : stationInfoDst?.chargePointSerialNumber && delete stationInfoDst.chargePointSerialNumber;
443 stationTemplate?.chargeBoxSerialNumberPrefix && stationInfoSrc?.chargeBoxSerialNumber
444 ? (stationInfoDst.chargeBoxSerialNumber = stationInfoSrc.chargeBoxSerialNumber)
445 : stationInfoDst?.chargeBoxSerialNumber && delete stationInfoDst.chargeBoxSerialNumber;
446 stationTemplate?.meterSerialNumberPrefix && stationInfoSrc?.meterSerialNumber
447 ? (stationInfoDst.meterSerialNumber = stationInfoSrc.meterSerialNumber)
448 : stationInfoDst?.meterSerialNumber && delete stationInfoDst.meterSerialNumber;
449};
450
451export const getAmperageLimitationUnitDivider = (stationInfo: ChargingStationInfo): number => {
452 let unitDivider = 1;
453 switch (stationInfo.amperageLimitationUnit) {
454 case AmpereUnits.DECI_AMPERE:
455 unitDivider = 10;
456 break;
457 case AmpereUnits.CENTI_AMPERE:
458 unitDivider = 100;
459 break;
460 case AmpereUnits.MILLI_AMPERE:
461 unitDivider = 1000;
462 break;
463 }
464 return unitDivider;
465};
466
467export const getChargingStationConnectorChargingProfilesPowerLimit = (
468 chargingStation: ChargingStation,
469 connectorId: number,
470): number | undefined => {
471 let limit: number | undefined, matchingChargingProfile: ChargingProfile | undefined;
472 // Get charging profiles for connector id and sort by stack level
473 const chargingProfiles =
474 cloneObject<ChargingProfile[]>(
475 chargingStation.getConnectorStatus(connectorId)!.chargingProfiles!,
476 )?.sort((a, b) => b.stackLevel - a.stackLevel) ?? [];
477 // Get charging profiles on connector 0 and sort by stack level
478 if (isNotEmptyArray(chargingStation.getConnectorStatus(0)?.chargingProfiles)) {
479 chargingProfiles.push(
480 ...cloneObject<ChargingProfile[]>(
481 chargingStation.getConnectorStatus(0)!.chargingProfiles!,
482 ).sort((a, b) => b.stackLevel - a.stackLevel),
483 );
484 }
485 if (isNotEmptyArray(chargingProfiles)) {
486 const result = getLimitFromChargingProfiles(
487 chargingStation,
488 connectorId,
489 chargingProfiles,
490 chargingStation.logPrefix(),
491 );
492 if (!isNullOrUndefined(result)) {
493 limit = result?.limit;
494 matchingChargingProfile = result?.matchingChargingProfile;
495 switch (chargingStation.getCurrentOutType()) {
496 case CurrentType.AC:
497 limit =
498 matchingChargingProfile?.chargingSchedule?.chargingRateUnit ===
499 ChargingRateUnitType.WATT
500 ? limit
501 : ACElectricUtils.powerTotal(
502 chargingStation.getNumberOfPhases(),
503 chargingStation.getVoltageOut(),
504 limit!,
505 );
506 break;
507 case CurrentType.DC:
508 limit =
509 matchingChargingProfile?.chargingSchedule?.chargingRateUnit ===
510 ChargingRateUnitType.WATT
511 ? limit
512 : DCElectricUtils.power(chargingStation.getVoltageOut(), limit!);
513 }
514 const connectorMaximumPower =
515 chargingStation.getMaximumPower() / chargingStation.powerDivider;
516 if (limit! > connectorMaximumPower) {
517 logger.error(
518 `${chargingStation.logPrefix()} ${moduleName}.getChargingStationConnectorChargingProfilesPowerLimit: Charging profile id ${matchingChargingProfile?.chargingProfileId} limit ${limit} is greater than connector id ${connectorId} maximum ${connectorMaximumPower}: %j`,
519 result,
520 );
521 limit = connectorMaximumPower;
522 }
523 }
524 }
525 return limit;
526};
527
528export const getDefaultVoltageOut = (
529 currentType: CurrentType,
530 logPrefix: string,
531 templateFile: string,
532): Voltage => {
533 const errorMsg = `Unknown ${currentType} currentOutType in template file ${templateFile}, cannot define default voltage out`;
534 let defaultVoltageOut: number;
535 switch (currentType) {
536 case CurrentType.AC:
537 defaultVoltageOut = Voltage.VOLTAGE_230;
538 break;
539 case CurrentType.DC:
540 defaultVoltageOut = Voltage.VOLTAGE_400;
541 break;
542 default:
543 logger.error(`${logPrefix} ${errorMsg}`);
544 throw new BaseError(errorMsg);
545 }
546 return defaultVoltageOut;
547};
548
549export const getIdTagsFile = (stationInfo: ChargingStationInfo): string | undefined => {
550 return (
551 stationInfo.idTagsFile &&
552 join(dirname(fileURLToPath(import.meta.url)), 'assets', basename(stationInfo.idTagsFile))
553 );
554};
555
556export const waitChargingStationEvents = async (
557 emitter: EventEmitter,
558 event: ChargingStationWorkerMessageEvents,
559 eventsToWait: number,
560): Promise<number> => {
561 return new Promise<number>((resolve) => {
562 let events = 0;
563 if (eventsToWait === 0) {
564 resolve(events);
565 }
566 emitter.on(event, () => {
567 ++events;
568 if (events === eventsToWait) {
569 resolve(events);
570 }
571 });
572 });
573};
574
575const getConfiguredNumberOfConnectors = (stationTemplate: ChargingStationTemplate): number => {
576 let configuredMaxConnectors = 0;
577 if (isNotEmptyArray(stationTemplate.numberOfConnectors) === true) {
578 const numberOfConnectors = stationTemplate.numberOfConnectors as number[];
579 configuredMaxConnectors =
580 numberOfConnectors[Math.floor(secureRandom() * numberOfConnectors.length)];
581 } else if (isUndefined(stationTemplate.numberOfConnectors) === false) {
582 configuredMaxConnectors = stationTemplate.numberOfConnectors as number;
583 } else if (stationTemplate.Connectors && !stationTemplate.Evses) {
584 configuredMaxConnectors = stationTemplate.Connectors[0]
585 ? getMaxNumberOfConnectors(stationTemplate.Connectors) - 1
586 : getMaxNumberOfConnectors(stationTemplate.Connectors);
587 } else if (stationTemplate.Evses && !stationTemplate.Connectors) {
588 for (const evse in stationTemplate.Evses) {
589 if (evse === '0') {
590 continue;
591 }
592 configuredMaxConnectors += getMaxNumberOfConnectors(stationTemplate.Evses[evse].Connectors);
593 }
594 }
595 return configuredMaxConnectors;
596};
597
598const checkConfiguredMaxConnectors = (
599 configuredMaxConnectors: number,
600 logPrefix: string,
601 templateFile: string,
602): void => {
603 if (configuredMaxConnectors <= 0) {
604 logger.warn(
605 `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors`,
606 );
607 }
608};
609
610const checkTemplateMaxConnectors = (
611 templateMaxConnectors: number,
612 logPrefix: string,
613 templateFile: string,
614): void => {
615 if (templateMaxConnectors === 0) {
616 logger.warn(
617 `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration`,
618 );
619 } else if (templateMaxConnectors < 0) {
620 logger.error(
621 `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined`,
622 );
623 }
624};
625
626const initializeConnectorStatus = (connectorStatus: ConnectorStatus): void => {
627 connectorStatus.availability = AvailabilityType.Operative;
628 connectorStatus.idTagLocalAuthorized = false;
629 connectorStatus.idTagAuthorized = false;
630 connectorStatus.transactionRemoteStarted = false;
631 connectorStatus.transactionStarted = false;
632 connectorStatus.energyActiveImportRegisterValue = 0;
633 connectorStatus.transactionEnergyActiveImportRegisterValue = 0;
634 if (isUndefined(connectorStatus.chargingProfiles)) {
635 connectorStatus.chargingProfiles = [];
636 }
637};
638
639const warnDeprecatedTemplateKey = (
640 template: ChargingStationTemplate,
641 key: string,
642 logPrefix: string,
643 templateFile: string,
644 logMsgToAppend = '',
645): void => {
646 if (!isUndefined(template[key as keyof ChargingStationTemplate])) {
647 const logMsg = `Deprecated template key '${key}' usage in file '${templateFile}'${
648 isNotEmptyString(logMsgToAppend) ? `. ${logMsgToAppend}` : ''
649 }`;
650 logger.warn(`${logPrefix} ${logMsg}`);
651 console.warn(chalk.yellow(`${logMsg}`));
652 }
653};
654
655const convertDeprecatedTemplateKey = (
656 template: ChargingStationTemplate,
657 deprecatedKey: string,
658 key?: string,
659): void => {
660 if (!isUndefined(template[deprecatedKey as keyof ChargingStationTemplate])) {
661 if (!isUndefined(key)) {
662 (template as unknown as Record<string, unknown>)[key!] =
663 template[deprecatedKey as keyof ChargingStationTemplate];
664 }
665 delete template[deprecatedKey as keyof ChargingStationTemplate];
666 }
667};
668
669interface ChargingProfilesLimit {
670 limit: number;
671 matchingChargingProfile: ChargingProfile;
672}
673
674/**
675 * Charging profiles should already be sorted by connector id and stack level (highest stack level has priority)
676 *
677 * @param chargingProfiles -
678 * @param logPrefix -
679 * @returns ChargingProfilesLimit
680 */
681const getLimitFromChargingProfiles = (
682 chargingStation: ChargingStation,
683 connectorId: number,
684 chargingProfiles: ChargingProfile[],
685 logPrefix: string,
686): ChargingProfilesLimit | undefined => {
687 const debugLogMsg = `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Matching charging profile found for power limitation: %j`;
688 const currentDate = new Date();
689 const connectorStatus = chargingStation.getConnectorStatus(connectorId);
690 for (const chargingProfile of chargingProfiles) {
691 if (
692 (isValidDate(chargingProfile.validFrom) &&
693 isBefore(currentDate, chargingProfile.validFrom!)) ||
694 (isValidDate(chargingProfile.validTo) && isAfter(currentDate, chargingProfile.validTo!))
695 ) {
696 logger.debug(
697 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${
698 chargingProfile.chargingProfileId
699 } is not valid for the current date ${currentDate.toISOString()}`,
700 );
701 continue;
702 }
703 const chargingSchedule = chargingProfile.chargingSchedule;
704 if (connectorStatus?.transactionStarted && !chargingSchedule?.startSchedule) {
705 logger.debug(
706 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not defined in charging profile id ${chargingProfile.chargingProfileId}. Trying to set it to the connector transaction start date`,
707 );
708 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
709 chargingSchedule.startSchedule = connectorStatus?.transactionStart;
710 }
711 if (!(chargingSchedule?.startSchedule instanceof Date)) {
712 logger.warn(
713 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not a Date object in charging profile id ${chargingProfile.chargingProfileId}. Trying to convert it to a Date object`,
714 );
715 chargingSchedule.startSchedule = convertToDate(chargingSchedule?.startSchedule)!;
716 }
717 if (
718 chargingProfile.chargingProfileKind === ChargingProfileKindType.RECURRING &&
719 isNullOrUndefined(chargingProfile.recurrencyKind)
720 ) {
721 logger.error(
722 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Recurring charging profile id ${chargingProfile.chargingProfileId} has no recurrencyKind defined`,
723 );
724 continue;
725 }
726 if (chargingProfile.chargingProfileKind === ChargingProfileKindType.RECURRING) {
727 prepareRecurringChargingProfile(chargingProfile, currentDate, logPrefix);
728 } else if (
729 chargingProfile.chargingProfileKind === ChargingProfileKindType.RELATIVE &&
730 connectorStatus?.transactionStarted
731 ) {
732 chargingSchedule.startSchedule = connectorStatus?.transactionStart;
733 }
734 if (isNullOrUndefined(chargingSchedule?.duration)) {
735 logger.error(
736 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no duration defined, not yet supported`,
737 );
738 continue;
739 }
740 // Check if the charging profile is active
741 if (
742 isValidDate(chargingSchedule?.startSchedule) &&
743 isWithinInterval(currentDate, {
744 start: chargingSchedule.startSchedule!,
745 end: addSeconds(chargingSchedule.startSchedule!, chargingSchedule.duration!),
746 })
747 ) {
748 if (isNotEmptyArray(chargingSchedule.chargingSchedulePeriod)) {
749 const chargingSchedulePeriodCompareFn = (
750 a: ChargingSchedulePeriod,
751 b: ChargingSchedulePeriod,
752 ) => a.startPeriod - b.startPeriod;
753 if (
754 isArraySorted<ChargingSchedulePeriod>(
755 chargingSchedule.chargingSchedulePeriod,
756 chargingSchedulePeriodCompareFn,
757 ) === false
758 ) {
759 logger.warn(
760 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} schedule periods are not sorted by start period`,
761 );
762 chargingSchedule.chargingSchedulePeriod.sort(chargingSchedulePeriodCompareFn);
763 }
764 // Check if the first schedule period start period is equal to 0
765 if (chargingSchedule.chargingSchedulePeriod[0].startPeriod !== 0) {
766 logger.error(
767 `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} first schedule period start period ${chargingSchedule.chargingSchedulePeriod[0].startPeriod} is not equal to 0`,
768 );
769 continue;
770 }
771 // Handle only one schedule period
772 if (chargingSchedule.chargingSchedulePeriod.length === 1) {
773 const result: ChargingProfilesLimit = {
774 limit: chargingSchedule.chargingSchedulePeriod[0].limit,
775 matchingChargingProfile: chargingProfile,
776 };
777 logger.debug(debugLogMsg, result);
778 return result;
779 }
780 let lastButOneSchedule: ChargingSchedulePeriod | undefined;
781 // Search for the right schedule period
782 for (const [index, schedulePeriod] of chargingSchedule.chargingSchedulePeriod.entries()) {
783 // Find the right schedule period
784 if (
785 isAfter(
786 addSeconds(chargingSchedule.startSchedule!, schedulePeriod.startPeriod),
787 currentDate,
788 )
789 ) {
790 // Found the schedule period: last but one is the correct one
791 const result: ChargingProfilesLimit = {
792 limit: lastButOneSchedule!.limit,
793 matchingChargingProfile: chargingProfile,
794 };
795 logger.debug(debugLogMsg, result);
796 return result;
797 }
798 // Keep it
799 lastButOneSchedule = schedulePeriod;
800 // Handle the last schedule period within the charging profile duration
801 if (
802 index === chargingSchedule.chargingSchedulePeriod.length - 1 ||
803 (index < chargingSchedule.chargingSchedulePeriod.length - 1 &&
804 chargingSchedule.duration! >
805 differenceInSeconds(
806 addSeconds(
807 chargingSchedule.startSchedule!,
808 chargingSchedule.chargingSchedulePeriod[index + 1].startPeriod,
809 ),
810 chargingSchedule.startSchedule!,
811 ))
812 ) {
813 const result: ChargingProfilesLimit = {
814 limit: lastButOneSchedule.limit,
815 matchingChargingProfile: chargingProfile,
816 };
817 logger.debug(debugLogMsg, result);
818 return result;
819 }
820 }
821 }
822 }
823 }
824};
825
826/**
827 * Adjust recurring charging profile startSchedule to the current recurrency time interval if needed
828 *
829 * @param chargingProfile -
830 * @param currentDate -
831 * @param logPrefix -
832 */
833const prepareRecurringChargingProfile = (
834 chargingProfile: ChargingProfile,
835 currentDate: Date,
836 logPrefix: string,
837) => {
838 const chargingSchedule = chargingProfile.chargingSchedule;
839 let recurringInterval: Interval;
840 switch (chargingProfile.recurrencyKind) {
841 case RecurrencyKindType.DAILY:
842 recurringInterval = {
843 start: chargingSchedule.startSchedule!,
844 end: addDays(chargingSchedule.startSchedule!, 1),
845 };
846 checkRecurringChargingProfileDuration(chargingProfile, recurringInterval, logPrefix);
847 if (
848 !isWithinInterval(currentDate, recurringInterval) &&
849 isBefore(recurringInterval.end, currentDate)
850 ) {
851 chargingSchedule.startSchedule = addDays(
852 recurringInterval.start,
853 differenceInDays(currentDate, recurringInterval.start),
854 );
855 recurringInterval = {
856 start: chargingSchedule.startSchedule,
857 end: addDays(chargingSchedule.startSchedule, 1),
858 };
859 }
860 break;
861 case RecurrencyKindType.WEEKLY:
862 recurringInterval = {
863 start: chargingSchedule.startSchedule!,
864 end: addWeeks(chargingSchedule.startSchedule!, 1),
865 };
866 checkRecurringChargingProfileDuration(chargingProfile, recurringInterval, logPrefix);
867 if (
868 !isWithinInterval(currentDate, recurringInterval) &&
869 isBefore(recurringInterval.end, currentDate)
870 ) {
871 chargingSchedule.startSchedule = addWeeks(
872 recurringInterval.start,
873 differenceInWeeks(currentDate, recurringInterval.start),
874 );
875 recurringInterval = {
876 start: chargingSchedule.startSchedule,
877 end: addWeeks(chargingSchedule.startSchedule, 1),
878 };
879 }
880 break;
881 }
882 if (!isWithinInterval(currentDate, recurringInterval!)) {
883 logger.error(
884 `${logPrefix} ${moduleName}.prepareRecurringChargingProfile: Recurring ${
885 chargingProfile.recurrencyKind
886 } charging profile id ${chargingProfile.chargingProfileId} recurrency time interval [${toDate(
887 recurringInterval!.start,
888 ).toISOString()}, ${toDate(
889 recurringInterval!.end,
890 ).toISOString()}] is not properly translated to current date ${currentDate.toISOString()} `,
891 );
892 }
893};
894
895const checkRecurringChargingProfileDuration = (
896 chargingProfile: ChargingProfile,
897 interval: Interval,
898 logPrefix: string,
899) => {
900 if (isNullOrUndefined(chargingProfile.chargingSchedule.duration)) {
901 logger.warn(
902 `${logPrefix} ${moduleName}.checkRecurringChargingProfileDuration: Recurring ${
903 chargingProfile.chargingProfileKind
904 } charging profile id ${
905 chargingProfile.chargingProfileId
906 } duration is not defined, set it to the recurrency time interval duration ${differenceInSeconds(
907 interval.end,
908 interval.start,
909 )}`,
910 );
911 chargingProfile.chargingSchedule.duration = differenceInSeconds(interval.end, interval.start);
912 } else if (
913 chargingProfile.chargingSchedule.duration! > differenceInSeconds(interval.end, interval.start)
914 ) {
915 logger.warn(
916 `${logPrefix} ${moduleName}.checkRecurringChargingProfileDuration: Recurring ${
917 chargingProfile.chargingProfileKind
918 } charging profile id ${chargingProfile.chargingProfileId} duration ${
919 chargingProfile.chargingSchedule.duration
920 } is greater than the recurrency time interval duration ${differenceInSeconds(
921 interval.end,
922 interval.start,
923 )}`,
924 );
925 chargingProfile.chargingSchedule.duration = differenceInSeconds(interval.end, interval.start);
926 }
927};
928
929const getRandomSerialNumberSuffix = (params?: {
930 randomBytesLength?: number;
931 upperCase?: boolean;
932}): string => {
933 const randomSerialNumberSuffix = randomBytes(params?.randomBytesLength ?? 16).toString('hex');
934 if (params?.upperCase) {
935 return randomSerialNumberSuffix.toUpperCase();
936 }
937 return randomSerialNumberSuffix;
938};