1 import { ChargingProfile
, ChargingSchedulePeriod
} from
'../types/ocpp/ChargingProfile';
2 import { ChargingProfileKindType
, RecurrencyKindType
} from
'../types/ocpp/1.6/ChargingProfile';
3 import ChargingStationTemplate
, {
7 } from
'../types/ChargingStationTemplate';
8 import { MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
10 import BaseError from
'../exception/BaseError';
11 import { BootNotificationRequest
} from
'../types/ocpp/Requests';
12 import ChargingStation from
'./ChargingStation';
13 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
14 import ChargingStationInfo from
'../types/ChargingStationInfo';
15 import Configuration from
'../utils/Configuration';
16 import Constants from
'../utils/Constants';
17 import { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
18 import { StandardParametersKey
} from
'../types/ocpp/Configuration';
19 import Utils from
'../utils/Utils';
20 import { WebSocketCloseEventStatusString
} from
'../types/WebSocket';
21 import { WorkerProcessType
} from
'../types/Worker';
22 import crypto from
'crypto';
23 import { fileURLToPath
} from
'url';
24 import logger from
'../utils/Logger';
25 import moment from
'moment';
26 import path from
'path';
28 export class ChargingStationUtils
{
29 public static getChargingStationId(
31 stationTemplate
: ChargingStationTemplate
33 // In case of multiple instances: add instance index to charging station id
34 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
35 const idSuffix
= stationTemplate
.nameSuffix
?? '';
36 const idStr
= '000000000' + index
.toString();
37 return stationTemplate
?.fixedName
38 ? stationTemplate
.baseName
39 : stationTemplate
.baseName
+
41 instanceIndex
.toString() +
42 idStr
.substring(idStr
.length
- 4) +
46 public static getHashId(index
: number, stationTemplate
: ChargingStationTemplate
): string {
47 const hashBootNotificationRequest
= {
48 chargePointModel
: stationTemplate
.chargePointModel
,
49 chargePointVendor
: stationTemplate
.chargePointVendor
,
50 ...(!Utils
.isUndefined(stationTemplate
.chargeBoxSerialNumberPrefix
) && {
51 chargeBoxSerialNumber
: stationTemplate
.chargeBoxSerialNumberPrefix
,
53 ...(!Utils
.isUndefined(stationTemplate
.chargePointSerialNumberPrefix
) && {
54 chargePointSerialNumber
: stationTemplate
.chargePointSerialNumberPrefix
,
56 ...(!Utils
.isUndefined(stationTemplate
.firmwareVersion
) && {
57 firmwareVersion
: stationTemplate
.firmwareVersion
,
59 ...(!Utils
.isUndefined(stationTemplate
.iccid
) && { iccid
: stationTemplate
.iccid
}),
60 ...(!Utils
.isUndefined(stationTemplate
.imsi
) && { imsi
: stationTemplate
.imsi
}),
61 ...(!Utils
.isUndefined(stationTemplate
.meterSerialNumberPrefix
) && {
62 meterSerialNumber
: stationTemplate
.meterSerialNumberPrefix
,
64 ...(!Utils
.isUndefined(stationTemplate
.meterType
) && {
65 meterType
: stationTemplate
.meterType
,
69 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
71 JSON
.stringify(hashBootNotificationRequest
) +
72 ChargingStationUtils
.getChargingStationId(index
, stationTemplate
)
77 public static getTemplateMaxNumberOfConnectors(stationTemplate
: ChargingStationTemplate
): number {
78 const templateConnectors
= stationTemplate
?.Connectors
;
79 if (!templateConnectors
) {
82 return Object.keys(templateConnectors
).length
;
85 public static checkTemplateMaxConnectors(
86 templateMaxConnectors
: number,
90 if (templateMaxConnectors
=== 0) {
92 `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration`
94 } else if (templateMaxConnectors
< 0) {
96 `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined`
101 public static getConfiguredNumberOfConnectors(
103 stationTemplate
: ChargingStationTemplate
105 let configuredMaxConnectors
: number;
106 if (!Utils
.isEmptyArray(stationTemplate
.numberOfConnectors
)) {
107 const numberOfConnectors
= stationTemplate
.numberOfConnectors
as number[];
108 // Distribute evenly the number of connectors
109 configuredMaxConnectors
= numberOfConnectors
[(index
- 1) % numberOfConnectors
.length
];
110 } else if (!Utils
.isUndefined(stationTemplate
.numberOfConnectors
)) {
111 configuredMaxConnectors
= stationTemplate
.numberOfConnectors
as number;
113 configuredMaxConnectors
= stationTemplate
?.Connectors
[0]
114 ? ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
) - 1
115 : ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
117 return configuredMaxConnectors
;
120 public static checkConfiguredMaxConnectors(
121 configuredMaxConnectors
: number,
122 templateFile
: string,
125 if (configuredMaxConnectors
<= 0) {
127 `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors`
132 public static createBootNotificationRequest(
133 stationInfo
: ChargingStationInfo
134 ): BootNotificationRequest
{
136 chargePointModel
: stationInfo
.chargePointModel
,
137 chargePointVendor
: stationInfo
.chargePointVendor
,
138 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
139 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
141 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
142 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
144 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
145 firmwareVersion
: stationInfo
.firmwareVersion
,
147 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
148 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
149 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
150 meterSerialNumber
: stationInfo
.meterSerialNumber
,
152 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
153 meterType
: stationInfo
.meterType
,
158 public static workerPoolInUse(): boolean {
159 return [WorkerProcessType
.DYNAMIC_POOL
, WorkerProcessType
.STATIC_POOL
].includes(
160 Configuration
.getWorkerProcess()
164 public static workerDynamicPoolInUse(): boolean {
165 return Configuration
.getWorkerProcess() === WorkerProcessType
.DYNAMIC_POOL
;
169 * Convert websocket error code to human readable string message
171 * @param code websocket error code
172 * @returns human readable string message
174 public static getWebSocketCloseEventStatusString(code
: number): string {
175 if (code
>= 0 && code
<= 999) {
177 } else if (code
>= 1016) {
179 return '(For WebSocket standard)';
180 } else if (code
<= 2999) {
181 return '(For WebSocket extensions)';
182 } else if (code
<= 3999) {
183 return '(For libraries and frameworks)';
184 } else if (code
<= 4999) {
185 return '(For applications)';
188 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
189 return WebSocketCloseEventStatusString
[code
] as string;
194 public static warnDeprecatedTemplateKey(
195 template
: ChargingStationTemplate
,
197 templateFile
: string,
201 if (!Utils
.isUndefined(template
[key
])) {
203 `${logPrefix} Deprecated template key '${key}' usage in file '${templateFile}'${
204 logMsgToAppend && '. ' + logMsgToAppend
210 public static convertDeprecatedTemplateKey(
211 template
: ChargingStationTemplate
,
212 deprecatedKey
: string,
215 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
216 template
[key
] = template
[deprecatedKey
] as unknown
;
217 delete template
[deprecatedKey
];
221 public static stationTemplateToStationInfo(
222 stationTemplate
: ChargingStationTemplate
223 ): ChargingStationInfo
{
224 stationTemplate
= Utils
.cloneObject(stationTemplate
);
225 delete stationTemplate
.power
;
226 delete stationTemplate
.powerUnit
;
227 delete stationTemplate
.Configuration
;
228 delete stationTemplate
.AutomaticTransactionGenerator
;
229 delete stationTemplate
.chargeBoxSerialNumberPrefix
;
230 delete stationTemplate
.chargePointSerialNumberPrefix
;
231 delete stationTemplate
.meterSerialNumberPrefix
;
232 return stationTemplate
;
235 public static createStationInfoHash(stationInfo
: ChargingStationInfo
): void {
236 delete stationInfo
.infoHash
;
237 stationInfo
.infoHash
= crypto
238 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
239 .update(JSON
.stringify(stationInfo
))
243 public static createSerialNumber(
244 stationTemplate
: ChargingStationTemplate
,
245 stationInfo
: ChargingStationInfo
= {} as ChargingStationInfo
,
247 randomSerialNumberUpperCase
?: boolean;
248 randomSerialNumber
?: boolean;
250 randomSerialNumberUpperCase
: true,
251 randomSerialNumber
: true,
254 params
= params
?? {};
255 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
256 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
257 const serialNumberSuffix
= params
?.randomSerialNumber
258 ? ChargingStationUtils
.getRandomSerialNumberSuffix({
259 upperCase
: params
.randomSerialNumberUpperCase
,
262 stationInfo
.chargePointSerialNumber
=
263 stationTemplate
?.chargePointSerialNumberPrefix
&&
264 stationTemplate
.chargePointSerialNumberPrefix
+ serialNumberSuffix
;
265 stationInfo
.chargeBoxSerialNumber
=
266 stationTemplate
?.chargeBoxSerialNumberPrefix
&&
267 stationTemplate
.chargeBoxSerialNumberPrefix
+ serialNumberSuffix
;
268 stationInfo
.meterSerialNumber
=
269 stationTemplate
?.meterSerialNumberPrefix
&&
270 stationTemplate
.meterSerialNumberPrefix
+ serialNumberSuffix
;
273 public static propagateSerialNumber(
274 stationTemplate
: ChargingStationTemplate
,
275 stationInfoSrc
: ChargingStationInfo
,
276 stationInfoDst
: ChargingStationInfo
= {} as ChargingStationInfo
278 if (!stationInfoSrc
|| !stationTemplate
) {
280 'Missing charging station template or existing configuration to propagate serial number'
283 stationTemplate
?.chargePointSerialNumberPrefix
&& stationInfoSrc
?.chargePointSerialNumber
284 ? (stationInfoDst
.chargePointSerialNumber
= stationInfoSrc
.chargePointSerialNumber
)
285 : stationInfoDst
?.chargePointSerialNumber
&& delete stationInfoDst
.chargePointSerialNumber
;
286 stationTemplate
?.chargeBoxSerialNumberPrefix
&& stationInfoSrc
?.chargeBoxSerialNumber
287 ? (stationInfoDst
.chargeBoxSerialNumber
= stationInfoSrc
.chargeBoxSerialNumber
)
288 : stationInfoDst
?.chargeBoxSerialNumber
&& delete stationInfoDst
.chargeBoxSerialNumber
;
289 stationTemplate
?.meterSerialNumberPrefix
&& stationInfoSrc
?.meterSerialNumber
290 ? (stationInfoDst
.meterSerialNumber
= stationInfoSrc
.meterSerialNumber
)
291 : stationInfoDst
?.meterSerialNumber
&& delete stationInfoDst
.meterSerialNumber
;
294 public static getAmperageLimitationUnitDivider(stationInfo
: ChargingStationInfo
): number {
296 switch (stationInfo
.amperageLimitationUnit
) {
297 case AmpereUnits
.DECI_AMPERE
:
300 case AmpereUnits
.CENTI_AMPERE
:
303 case AmpereUnits
.MILLI_AMPERE
:
311 * Charging profiles should already be sorted by connectorId and stack level (highest stack level has priority)
313 * @param {ChargingProfile[]} chargingProfiles
314 * @param {string} logPrefix
315 * @returns {{ limit, matchingChargingProfile }}
317 public static getLimitFromChargingProfiles(
318 chargingProfiles
: ChargingProfile
[],
322 matchingChargingProfile
: ChargingProfile
;
324 for (const chargingProfile
of chargingProfiles
) {
326 const currentMoment
= moment();
327 const chargingSchedule
= chargingProfile
.chargingSchedule
;
328 // Check type (recurring) and if it is already active
329 // Adjust the daily recurring schedule to today
331 chargingProfile
.chargingProfileKind
=== ChargingProfileKindType
.RECURRING
&&
332 chargingProfile
.recurrencyKind
=== RecurrencyKindType
.DAILY
&&
333 currentMoment
.isAfter(chargingSchedule
.startSchedule
)
335 const currentDate
= new Date();
336 chargingSchedule
.startSchedule
= new Date(chargingSchedule
.startSchedule
);
337 chargingSchedule
.startSchedule
.setFullYear(
338 currentDate
.getFullYear(),
339 currentDate
.getMonth(),
340 currentDate
.getDate()
342 // Check if the start of the schedule is yesterday
343 if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
344 chargingSchedule
.startSchedule
.setDate(currentDate
.getDate() - 1);
346 } else if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
349 // Check if the charging profile is active
351 moment(chargingSchedule
.startSchedule
)
352 .add(chargingSchedule
.duration
, 's')
353 .isAfter(currentMoment
)
355 let lastButOneSchedule
: ChargingSchedulePeriod
;
356 // Search the right schedule period
357 for (const schedulePeriod
of chargingSchedule
.chargingSchedulePeriod
) {
358 // Handling of only one period
360 chargingSchedule
.chargingSchedulePeriod
.length
=== 1 &&
361 schedulePeriod
.startPeriod
=== 0
364 limit
: schedulePeriod
.limit
,
365 matchingChargingProfile
: chargingProfile
,
368 `${logPrefix} Matching charging profile found for power limitation: %j`,
373 // Find the right schedule period
375 moment(chargingSchedule
.startSchedule
)
376 .add(schedulePeriod
.startPeriod
, 's')
377 .isAfter(currentMoment
)
379 // Found the schedule: last but one is the correct one
381 limit
: lastButOneSchedule
.limit
,
382 matchingChargingProfile
: chargingProfile
,
385 `${logPrefix} Matching charging profile found for power limitation: %j`,
391 lastButOneSchedule
= schedulePeriod
;
392 // Handle the last schedule period
394 schedulePeriod
.startPeriod
===
395 chargingSchedule
.chargingSchedulePeriod
[
396 chargingSchedule
.chargingSchedulePeriod
.length
- 1
400 limit
: lastButOneSchedule
.limit
,
401 matchingChargingProfile
: chargingProfile
,
404 `${logPrefix} Matching charging profile found for power limitation: %j`,
415 public static getDefaultVoltageOut(
416 currentType
: CurrentType
,
417 templateFile
: string,
420 const errMsg
= `${logPrefix} Unknown ${currentType} currentOutType in template file ${templateFile}, cannot define default voltage out`;
421 let defaultVoltageOut
: number;
422 switch (currentType
) {
424 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
427 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
430 logger
.error(errMsg
);
431 throw new Error(errMsg
);
433 return defaultVoltageOut
;
436 public static getSampledValueTemplate(
437 chargingStation
: ChargingStation
,
439 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
440 phase
?: MeterValuePhase
441 ): SampledValueTemplate
| undefined {
442 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
443 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
445 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
450 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
451 !ChargingStationConfigurationUtils
.getConfigurationKey(
453 StandardParametersKey
.MeterValuesSampledData
454 )?.value
.includes(measurand
)
457 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
458 StandardParametersKey.MeterValuesSampledData
463 const sampledValueTemplates
: SampledValueTemplate
[] =
464 chargingStation
.getConnectorStatus(connectorId
).MeterValues
;
467 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
471 !Constants
.SUPPORTED_MEASURANDS
.includes(
472 sampledValueTemplates
[index
]?.measurand
??
473 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
477 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
481 sampledValueTemplates
[index
]?.phase
=== phase
&&
482 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
483 ChargingStationConfigurationUtils
.getConfigurationKey(
485 StandardParametersKey
.MeterValuesSampledData
486 )?.value
.includes(measurand
)
488 return sampledValueTemplates
[index
];
491 !sampledValueTemplates
[index
].phase
&&
492 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
493 ChargingStationConfigurationUtils
.getConfigurationKey(
495 StandardParametersKey
.MeterValuesSampledData
496 )?.value
.includes(measurand
)
498 return sampledValueTemplates
[index
];
500 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
501 (!sampledValueTemplates
[index
].measurand
||
502 sampledValueTemplates
[index
].measurand
=== measurand
)
504 return sampledValueTemplates
[index
];
507 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
508 const errorMsg
= `${chargingStation.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
509 logger
.error(errorMsg
);
510 throw new Error(errorMsg
);
513 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
517 public static getAuthorizationFile(stationInfo
: ChargingStationInfo
): string | undefined {
519 stationInfo
.authorizationFile
&&
521 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
523 path
.basename(stationInfo
.authorizationFile
)
528 private static getRandomSerialNumberSuffix(params
?: {
529 randomBytesLength
?: number;
532 const randomSerialNumberSuffix
= crypto
533 .randomBytes(params
?.randomBytesLength
?? 16)
535 if (params
?.upperCase
) {
536 return randomSerialNumberSuffix
.toUpperCase();
538 return randomSerialNumberSuffix
;