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 { FileType
} from
'../types/FileType';
18 import FileUtils from
'../utils/FileUtils';
19 import { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
20 import { StandardParametersKey
} from
'../types/ocpp/Configuration';
21 import Utils from
'../utils/Utils';
22 import { WebSocketCloseEventStatusString
} from
'../types/WebSocket';
23 import { WorkerProcessType
} from
'../types/Worker';
24 import crypto from
'crypto';
26 import logger from
'../utils/Logger';
27 import moment from
'moment';
28 import path from
'path';
30 export class ChargingStationUtils
{
31 public static getChargingStationId(
33 stationTemplate
: ChargingStationTemplate
35 // In case of multiple instances: add instance index to charging station id
36 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
37 const idSuffix
= stationTemplate
.nameSuffix
?? '';
38 const idStr
= '000000000' + index
.toString();
39 return stationTemplate
?.fixedName
40 ? stationTemplate
.baseName
41 : stationTemplate
.baseName
+
43 instanceIndex
.toString() +
44 idStr
.substring(idStr
.length
- 4) +
48 public static getHashId(index
: number, stationTemplate
: ChargingStationTemplate
): string {
49 const hashBootNotificationRequest
= {
50 chargePointModel
: stationTemplate
.chargePointModel
,
51 chargePointVendor
: stationTemplate
.chargePointVendor
,
52 ...(!Utils
.isUndefined(stationTemplate
.chargeBoxSerialNumberPrefix
) && {
53 chargeBoxSerialNumber
: stationTemplate
.chargeBoxSerialNumberPrefix
,
55 ...(!Utils
.isUndefined(stationTemplate
.chargePointSerialNumberPrefix
) && {
56 chargePointSerialNumber
: stationTemplate
.chargePointSerialNumberPrefix
,
58 ...(!Utils
.isUndefined(stationTemplate
.firmwareVersion
) && {
59 firmwareVersion
: stationTemplate
.firmwareVersion
,
61 ...(!Utils
.isUndefined(stationTemplate
.iccid
) && { iccid
: stationTemplate
.iccid
}),
62 ...(!Utils
.isUndefined(stationTemplate
.imsi
) && { imsi
: stationTemplate
.imsi
}),
63 ...(!Utils
.isUndefined(stationTemplate
.meterSerialNumberPrefix
) && {
64 meterSerialNumber
: stationTemplate
.meterSerialNumberPrefix
,
66 ...(!Utils
.isUndefined(stationTemplate
.meterType
) && {
67 meterType
: stationTemplate
.meterType
,
71 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
73 JSON
.stringify(hashBootNotificationRequest
) +
74 ChargingStationUtils
.getChargingStationId(index
, stationTemplate
)
79 public static getTemplateMaxNumberOfConnectors(stationTemplate
: ChargingStationTemplate
): number {
80 const templateConnectors
= stationTemplate
?.Connectors
;
81 if (!templateConnectors
) {
84 return Object.keys(templateConnectors
).length
;
87 public static checkTemplateMaxConnectors(
88 templateMaxConnectors
: number,
92 if (templateMaxConnectors
=== 0) {
94 `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration`
96 } else if (templateMaxConnectors
< 0) {
98 `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined`
103 public static getConfiguredNumberOfConnectors(
105 stationTemplate
: ChargingStationTemplate
107 let configuredMaxConnectors
: number;
108 if (!Utils
.isEmptyArray(stationTemplate
.numberOfConnectors
)) {
109 const numberOfConnectors
= stationTemplate
.numberOfConnectors
as number[];
110 // Distribute evenly the number of connectors
111 configuredMaxConnectors
= numberOfConnectors
[(index
- 1) % numberOfConnectors
.length
];
112 } else if (!Utils
.isUndefined(stationTemplate
.numberOfConnectors
)) {
113 configuredMaxConnectors
= stationTemplate
.numberOfConnectors
as number;
115 configuredMaxConnectors
= stationTemplate
?.Connectors
[0]
116 ? ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
) - 1
117 : ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
119 return configuredMaxConnectors
;
122 public static checkConfiguredMaxConnectors(
123 configuredMaxConnectors
: number,
124 templateFile
: string,
127 if (configuredMaxConnectors
<= 0) {
129 `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors`
134 public static createBootNotificationRequest(
135 stationInfo
: ChargingStationInfo
136 ): BootNotificationRequest
{
138 chargePointModel
: stationInfo
.chargePointModel
,
139 chargePointVendor
: stationInfo
.chargePointVendor
,
140 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
141 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
143 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
144 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
146 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
147 firmwareVersion
: stationInfo
.firmwareVersion
,
149 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
150 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
151 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
152 meterSerialNumber
: stationInfo
.meterSerialNumber
,
154 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
155 meterType
: stationInfo
.meterType
,
160 public static workerPoolInUse(): boolean {
161 return [WorkerProcessType
.DYNAMIC_POOL
, WorkerProcessType
.STATIC_POOL
].includes(
162 Configuration
.getWorkerProcess()
166 public static workerDynamicPoolInUse(): boolean {
167 return Configuration
.getWorkerProcess() === WorkerProcessType
.DYNAMIC_POOL
;
171 * Convert websocket error code to human readable string message
173 * @param code websocket error code
174 * @returns human readable string message
176 public static getWebSocketCloseEventStatusString(code
: number): string {
177 if (code
>= 0 && code
<= 999) {
179 } else if (code
>= 1016) {
181 return '(For WebSocket standard)';
182 } else if (code
<= 2999) {
183 return '(For WebSocket extensions)';
184 } else if (code
<= 3999) {
185 return '(For libraries and frameworks)';
186 } else if (code
<= 4999) {
187 return '(For applications)';
190 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
191 return WebSocketCloseEventStatusString
[code
] as string;
196 public static warnDeprecatedTemplateKey(
197 template
: ChargingStationTemplate
,
199 templateFile
: string,
203 if (!Utils
.isUndefined(template
[key
])) {
205 `${logPrefix} Deprecated template key '${key}' usage in file '${templateFile}'${
206 logMsgToAppend && '. ' + logMsgToAppend
212 public static convertDeprecatedTemplateKey(
213 template
: ChargingStationTemplate
,
214 deprecatedKey
: string,
217 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
218 template
[key
] = template
[deprecatedKey
] as unknown
;
219 delete template
[deprecatedKey
];
223 public static stationTemplateToStationInfo(
224 stationTemplate
: ChargingStationTemplate
225 ): ChargingStationInfo
{
226 stationTemplate
= Utils
.cloneObject(stationTemplate
);
227 delete stationTemplate
.power
;
228 delete stationTemplate
.powerUnit
;
229 delete stationTemplate
.Configuration
;
230 delete stationTemplate
.AutomaticTransactionGenerator
;
231 delete stationTemplate
.chargeBoxSerialNumberPrefix
;
232 delete stationTemplate
.chargePointSerialNumberPrefix
;
233 delete stationTemplate
.meterSerialNumberPrefix
;
234 return stationTemplate
;
237 public static createStationInfoHash(stationInfo
: ChargingStationInfo
): void {
238 delete stationInfo
.infoHash
;
239 stationInfo
.infoHash
= crypto
240 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
241 .update(JSON
.stringify(stationInfo
))
245 public static createSerialNumber(
246 stationTemplate
: ChargingStationTemplate
,
247 stationInfo
: ChargingStationInfo
= {} as ChargingStationInfo
,
249 randomSerialNumberUpperCase
?: boolean;
250 randomSerialNumber
?: boolean;
252 randomSerialNumberUpperCase
: true,
253 randomSerialNumber
: true,
256 params
= params
?? {};
257 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
258 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
259 const serialNumberSuffix
= params
?.randomSerialNumber
260 ? ChargingStationUtils
.getRandomSerialNumberSuffix({
261 upperCase
: params
.randomSerialNumberUpperCase
,
264 stationInfo
.chargePointSerialNumber
=
265 stationTemplate
?.chargePointSerialNumberPrefix
&&
266 stationTemplate
.chargePointSerialNumberPrefix
+ serialNumberSuffix
;
267 stationInfo
.chargeBoxSerialNumber
=
268 stationTemplate
?.chargeBoxSerialNumberPrefix
&&
269 stationTemplate
.chargeBoxSerialNumberPrefix
+ serialNumberSuffix
;
270 stationInfo
.meterSerialNumber
=
271 stationTemplate
?.meterSerialNumberPrefix
&&
272 stationTemplate
.meterSerialNumberPrefix
+ serialNumberSuffix
;
275 public static propagateSerialNumber(
276 stationTemplate
: ChargingStationTemplate
,
277 stationInfoSrc
: ChargingStationInfo
,
278 stationInfoDst
: ChargingStationInfo
= {} as ChargingStationInfo
280 if (!stationInfoSrc
|| !stationTemplate
) {
282 'Missing charging station template or existing configuration to propagate serial number'
285 stationTemplate
?.chargePointSerialNumberPrefix
&& stationInfoSrc
?.chargePointSerialNumber
286 ? (stationInfoDst
.chargePointSerialNumber
= stationInfoSrc
.chargePointSerialNumber
)
287 : stationInfoDst
?.chargePointSerialNumber
&& delete stationInfoDst
.chargePointSerialNumber
;
288 stationTemplate
?.chargeBoxSerialNumberPrefix
&& stationInfoSrc
?.chargeBoxSerialNumber
289 ? (stationInfoDst
.chargeBoxSerialNumber
= stationInfoSrc
.chargeBoxSerialNumber
)
290 : stationInfoDst
?.chargeBoxSerialNumber
&& delete stationInfoDst
.chargeBoxSerialNumber
;
291 stationTemplate
?.meterSerialNumberPrefix
&& stationInfoSrc
?.meterSerialNumber
292 ? (stationInfoDst
.meterSerialNumber
= stationInfoSrc
.meterSerialNumber
)
293 : stationInfoDst
?.meterSerialNumber
&& delete stationInfoDst
.meterSerialNumber
;
296 public static getAmperageLimitationUnitDivider(stationInfo
: ChargingStationInfo
): number {
298 switch (stationInfo
.amperageLimitationUnit
) {
299 case AmpereUnits
.DECI_AMPERE
:
302 case AmpereUnits
.CENTI_AMPERE
:
305 case AmpereUnits
.MILLI_AMPERE
:
313 * Charging profiles should already be sorted by connectorId and stack level (highest stack level has priority)
315 * @param {ChargingProfile[]} chargingProfiles
316 * @param {string} logPrefix
317 * @returns {{ limit, matchingChargingProfile }}
319 public static getLimitFromChargingProfiles(
320 chargingProfiles
: ChargingProfile
[],
324 matchingChargingProfile
: ChargingProfile
;
326 for (const chargingProfile
of chargingProfiles
) {
328 const currentMoment
= moment();
329 const chargingSchedule
= chargingProfile
.chargingSchedule
;
330 // Check type (recurring) and if it is already active
331 // Adjust the daily recurring schedule to today
333 chargingProfile
.chargingProfileKind
=== ChargingProfileKindType
.RECURRING
&&
334 chargingProfile
.recurrencyKind
=== RecurrencyKindType
.DAILY
&&
335 currentMoment
.isAfter(chargingSchedule
.startSchedule
)
337 const currentDate
= new Date();
338 chargingSchedule
.startSchedule
= new Date(chargingSchedule
.startSchedule
);
339 chargingSchedule
.startSchedule
.setFullYear(
340 currentDate
.getFullYear(),
341 currentDate
.getMonth(),
342 currentDate
.getDate()
344 // Check if the start of the schedule is yesterday
345 if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
346 chargingSchedule
.startSchedule
.setDate(currentDate
.getDate() - 1);
348 } else if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
351 // Check if the charging profile is active
353 moment(chargingSchedule
.startSchedule
)
354 .add(chargingSchedule
.duration
, 's')
355 .isAfter(currentMoment
)
357 let lastButOneSchedule
: ChargingSchedulePeriod
;
358 // Search the right schedule period
359 for (const schedulePeriod
of chargingSchedule
.chargingSchedulePeriod
) {
360 // Handling of only one period
362 chargingSchedule
.chargingSchedulePeriod
.length
=== 1 &&
363 schedulePeriod
.startPeriod
=== 0
366 limit
: schedulePeriod
.limit
,
367 matchingChargingProfile
: chargingProfile
,
370 `${logPrefix} Matching charging profile found for power limitation: %j`,
375 // Find the right schedule period
377 moment(chargingSchedule
.startSchedule
)
378 .add(schedulePeriod
.startPeriod
, 's')
379 .isAfter(currentMoment
)
381 // Found the schedule: last but one is the correct one
383 limit
: lastButOneSchedule
.limit
,
384 matchingChargingProfile
: chargingProfile
,
387 `${logPrefix} Matching charging profile found for power limitation: %j`,
393 lastButOneSchedule
= schedulePeriod
;
394 // Handle the last schedule period
396 schedulePeriod
.startPeriod
===
397 chargingSchedule
.chargingSchedulePeriod
[
398 chargingSchedule
.chargingSchedulePeriod
.length
- 1
402 limit
: lastButOneSchedule
.limit
,
403 matchingChargingProfile
: chargingProfile
,
406 `${logPrefix} Matching charging profile found for power limitation: %j`,
417 public static getDefaultVoltageOut(
418 currentType
: CurrentType
,
419 templateFile
: string,
422 const errMsg
= `${logPrefix} Unknown ${currentType} currentOutType in template file ${templateFile}, cannot define default voltage out`;
423 let defaultVoltageOut
: number;
424 switch (currentType
) {
426 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
429 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
432 logger
.error(errMsg
);
433 throw new Error(errMsg
);
435 return defaultVoltageOut
;
438 public static getSampledValueTemplate(
439 chargingStation
: ChargingStation
,
441 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
442 phase
?: MeterValuePhase
443 ): SampledValueTemplate
| undefined {
444 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
445 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
447 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
452 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
453 !ChargingStationConfigurationUtils
.getConfigurationKey(
455 StandardParametersKey
.MeterValuesSampledData
456 )?.value
.includes(measurand
)
459 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
460 StandardParametersKey.MeterValuesSampledData
465 const sampledValueTemplates
: SampledValueTemplate
[] =
466 chargingStation
.getConnectorStatus(connectorId
).MeterValues
;
469 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
473 !Constants
.SUPPORTED_MEASURANDS
.includes(
474 sampledValueTemplates
[index
]?.measurand
??
475 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
479 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
483 sampledValueTemplates
[index
]?.phase
=== phase
&&
484 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
485 ChargingStationConfigurationUtils
.getConfigurationKey(
487 StandardParametersKey
.MeterValuesSampledData
488 )?.value
.includes(measurand
)
490 return sampledValueTemplates
[index
];
493 !sampledValueTemplates
[index
].phase
&&
494 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
495 ChargingStationConfigurationUtils
.getConfigurationKey(
497 StandardParametersKey
.MeterValuesSampledData
498 )?.value
.includes(measurand
)
500 return sampledValueTemplates
[index
];
502 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
503 (!sampledValueTemplates
[index
].measurand
||
504 sampledValueTemplates
[index
].measurand
=== measurand
)
506 return sampledValueTemplates
[index
];
509 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
510 const errorMsg
= `${chargingStation.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
511 logger
.error(errorMsg
);
512 throw new Error(errorMsg
);
515 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
519 public static getAuthorizedTags(
520 stationInfo
: ChargingStationInfo
,
521 templateFile
: string,
524 let authorizedTags
: string[] = [];
525 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(stationInfo
);
526 if (authorizationFile
) {
528 // Load authorization file
529 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
531 FileUtils
.handleFileException(
533 FileType
.Authorization
,
535 error
as NodeJS
.ErrnoException
539 logger
.info(logPrefix
+ ' No authorization file given in template file ' + templateFile
);
541 return authorizedTags
;
544 public static getAuthorizationFile(stationInfo
: ChargingStationInfo
): string | undefined {
546 stationInfo
.authorizationFile
&&
548 path
.resolve(__dirname
, '../'),
550 path
.basename(stationInfo
.authorizationFile
)
555 private static getRandomSerialNumberSuffix(params
?: {
556 randomBytesLength
?: number;
559 const randomSerialNumberSuffix
= crypto
560 .randomBytes(params
?.randomBytesLength
?? 16)
562 if (params
?.upperCase
) {
563 return randomSerialNumberSuffix
.toUpperCase();
565 return randomSerialNumberSuffix
;