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';
25 import { fileURLToPath
} from
'url';
27 import logger from
'../utils/Logger';
28 import moment from
'moment';
29 import path from
'path';
31 export class ChargingStationUtils
{
32 public static getChargingStationId(
34 stationTemplate
: ChargingStationTemplate
36 // In case of multiple instances: add instance index to charging station id
37 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
38 const idSuffix
= stationTemplate
.nameSuffix
?? '';
39 const idStr
= '000000000' + index
.toString();
40 return stationTemplate
?.fixedName
41 ? stationTemplate
.baseName
42 : stationTemplate
.baseName
+
44 instanceIndex
.toString() +
45 idStr
.substring(idStr
.length
- 4) +
49 public static getHashId(index
: number, stationTemplate
: ChargingStationTemplate
): string {
50 const hashBootNotificationRequest
= {
51 chargePointModel
: stationTemplate
.chargePointModel
,
52 chargePointVendor
: stationTemplate
.chargePointVendor
,
53 ...(!Utils
.isUndefined(stationTemplate
.chargeBoxSerialNumberPrefix
) && {
54 chargeBoxSerialNumber
: stationTemplate
.chargeBoxSerialNumberPrefix
,
56 ...(!Utils
.isUndefined(stationTemplate
.chargePointSerialNumberPrefix
) && {
57 chargePointSerialNumber
: stationTemplate
.chargePointSerialNumberPrefix
,
59 ...(!Utils
.isUndefined(stationTemplate
.firmwareVersion
) && {
60 firmwareVersion
: stationTemplate
.firmwareVersion
,
62 ...(!Utils
.isUndefined(stationTemplate
.iccid
) && { iccid
: stationTemplate
.iccid
}),
63 ...(!Utils
.isUndefined(stationTemplate
.imsi
) && { imsi
: stationTemplate
.imsi
}),
64 ...(!Utils
.isUndefined(stationTemplate
.meterSerialNumberPrefix
) && {
65 meterSerialNumber
: stationTemplate
.meterSerialNumberPrefix
,
67 ...(!Utils
.isUndefined(stationTemplate
.meterType
) && {
68 meterType
: stationTemplate
.meterType
,
72 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
74 JSON
.stringify(hashBootNotificationRequest
) +
75 ChargingStationUtils
.getChargingStationId(index
, stationTemplate
)
80 public static getTemplateMaxNumberOfConnectors(stationTemplate
: ChargingStationTemplate
): number {
81 const templateConnectors
= stationTemplate
?.Connectors
;
82 if (!templateConnectors
) {
85 return Object.keys(templateConnectors
).length
;
88 public static checkTemplateMaxConnectors(
89 templateMaxConnectors
: number,
93 if (templateMaxConnectors
=== 0) {
95 `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration`
97 } else if (templateMaxConnectors
< 0) {
99 `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined`
104 public static getConfiguredNumberOfConnectors(
106 stationTemplate
: ChargingStationTemplate
108 let configuredMaxConnectors
: number;
109 if (!Utils
.isEmptyArray(stationTemplate
.numberOfConnectors
)) {
110 const numberOfConnectors
= stationTemplate
.numberOfConnectors
as number[];
111 // Distribute evenly the number of connectors
112 configuredMaxConnectors
= numberOfConnectors
[(index
- 1) % numberOfConnectors
.length
];
113 } else if (!Utils
.isUndefined(stationTemplate
.numberOfConnectors
)) {
114 configuredMaxConnectors
= stationTemplate
.numberOfConnectors
as number;
116 configuredMaxConnectors
= stationTemplate
?.Connectors
[0]
117 ? ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
) - 1
118 : ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
120 return configuredMaxConnectors
;
123 public static checkConfiguredMaxConnectors(
124 configuredMaxConnectors
: number,
125 templateFile
: string,
128 if (configuredMaxConnectors
<= 0) {
130 `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors`
135 public static createBootNotificationRequest(
136 stationInfo
: ChargingStationInfo
137 ): BootNotificationRequest
{
139 chargePointModel
: stationInfo
.chargePointModel
,
140 chargePointVendor
: stationInfo
.chargePointVendor
,
141 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
142 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
144 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
145 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
147 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
148 firmwareVersion
: stationInfo
.firmwareVersion
,
150 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
151 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
152 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
153 meterSerialNumber
: stationInfo
.meterSerialNumber
,
155 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
156 meterType
: stationInfo
.meterType
,
161 public static workerPoolInUse(): boolean {
162 return [WorkerProcessType
.DYNAMIC_POOL
, WorkerProcessType
.STATIC_POOL
].includes(
163 Configuration
.getWorkerProcess()
167 public static workerDynamicPoolInUse(): boolean {
168 return Configuration
.getWorkerProcess() === WorkerProcessType
.DYNAMIC_POOL
;
172 * Convert websocket error code to human readable string message
174 * @param code websocket error code
175 * @returns human readable string message
177 public static getWebSocketCloseEventStatusString(code
: number): string {
178 if (code
>= 0 && code
<= 999) {
180 } else if (code
>= 1016) {
182 return '(For WebSocket standard)';
183 } else if (code
<= 2999) {
184 return '(For WebSocket extensions)';
185 } else if (code
<= 3999) {
186 return '(For libraries and frameworks)';
187 } else if (code
<= 4999) {
188 return '(For applications)';
191 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
192 return WebSocketCloseEventStatusString
[code
] as string;
197 public static warnDeprecatedTemplateKey(
198 template
: ChargingStationTemplate
,
200 templateFile
: string,
204 if (!Utils
.isUndefined(template
[key
])) {
206 `${logPrefix} Deprecated template key '${key}' usage in file '${templateFile}'${
207 logMsgToAppend && '. ' + logMsgToAppend
213 public static convertDeprecatedTemplateKey(
214 template
: ChargingStationTemplate
,
215 deprecatedKey
: string,
218 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
219 template
[key
] = template
[deprecatedKey
] as unknown
;
220 delete template
[deprecatedKey
];
224 public static stationTemplateToStationInfo(
225 stationTemplate
: ChargingStationTemplate
226 ): ChargingStationInfo
{
227 stationTemplate
= Utils
.cloneObject(stationTemplate
);
228 delete stationTemplate
.power
;
229 delete stationTemplate
.powerUnit
;
230 delete stationTemplate
.Configuration
;
231 delete stationTemplate
.AutomaticTransactionGenerator
;
232 delete stationTemplate
.chargeBoxSerialNumberPrefix
;
233 delete stationTemplate
.chargePointSerialNumberPrefix
;
234 delete stationTemplate
.meterSerialNumberPrefix
;
235 return stationTemplate
;
238 public static createStationInfoHash(stationInfo
: ChargingStationInfo
): void {
239 delete stationInfo
.infoHash
;
240 stationInfo
.infoHash
= crypto
241 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
242 .update(JSON
.stringify(stationInfo
))
246 public static createSerialNumber(
247 stationTemplate
: ChargingStationTemplate
,
248 stationInfo
: ChargingStationInfo
= {} as ChargingStationInfo
,
250 randomSerialNumberUpperCase
?: boolean;
251 randomSerialNumber
?: boolean;
253 randomSerialNumberUpperCase
: true,
254 randomSerialNumber
: true,
257 params
= params
?? {};
258 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
259 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
260 const serialNumberSuffix
= params
?.randomSerialNumber
261 ? ChargingStationUtils
.getRandomSerialNumberSuffix({
262 upperCase
: params
.randomSerialNumberUpperCase
,
265 stationInfo
.chargePointSerialNumber
=
266 stationTemplate
?.chargePointSerialNumberPrefix
&&
267 stationTemplate
.chargePointSerialNumberPrefix
+ serialNumberSuffix
;
268 stationInfo
.chargeBoxSerialNumber
=
269 stationTemplate
?.chargeBoxSerialNumberPrefix
&&
270 stationTemplate
.chargeBoxSerialNumberPrefix
+ serialNumberSuffix
;
271 stationInfo
.meterSerialNumber
=
272 stationTemplate
?.meterSerialNumberPrefix
&&
273 stationTemplate
.meterSerialNumberPrefix
+ serialNumberSuffix
;
276 public static propagateSerialNumber(
277 stationTemplate
: ChargingStationTemplate
,
278 stationInfoSrc
: ChargingStationInfo
,
279 stationInfoDst
: ChargingStationInfo
= {} as ChargingStationInfo
281 if (!stationInfoSrc
|| !stationTemplate
) {
283 'Missing charging station template or existing configuration to propagate serial number'
286 stationTemplate
?.chargePointSerialNumberPrefix
&& stationInfoSrc
?.chargePointSerialNumber
287 ? (stationInfoDst
.chargePointSerialNumber
= stationInfoSrc
.chargePointSerialNumber
)
288 : stationInfoDst
?.chargePointSerialNumber
&& delete stationInfoDst
.chargePointSerialNumber
;
289 stationTemplate
?.chargeBoxSerialNumberPrefix
&& stationInfoSrc
?.chargeBoxSerialNumber
290 ? (stationInfoDst
.chargeBoxSerialNumber
= stationInfoSrc
.chargeBoxSerialNumber
)
291 : stationInfoDst
?.chargeBoxSerialNumber
&& delete stationInfoDst
.chargeBoxSerialNumber
;
292 stationTemplate
?.meterSerialNumberPrefix
&& stationInfoSrc
?.meterSerialNumber
293 ? (stationInfoDst
.meterSerialNumber
= stationInfoSrc
.meterSerialNumber
)
294 : stationInfoDst
?.meterSerialNumber
&& delete stationInfoDst
.meterSerialNumber
;
297 public static getAmperageLimitationUnitDivider(stationInfo
: ChargingStationInfo
): number {
299 switch (stationInfo
.amperageLimitationUnit
) {
300 case AmpereUnits
.DECI_AMPERE
:
303 case AmpereUnits
.CENTI_AMPERE
:
306 case AmpereUnits
.MILLI_AMPERE
:
314 * Charging profiles should already be sorted by connectorId and stack level (highest stack level has priority)
316 * @param {ChargingProfile[]} chargingProfiles
317 * @param {string} logPrefix
318 * @returns {{ limit, matchingChargingProfile }}
320 public static getLimitFromChargingProfiles(
321 chargingProfiles
: ChargingProfile
[],
325 matchingChargingProfile
: ChargingProfile
;
327 for (const chargingProfile
of chargingProfiles
) {
329 const currentMoment
= moment();
330 const chargingSchedule
= chargingProfile
.chargingSchedule
;
331 // Check type (recurring) and if it is already active
332 // Adjust the daily recurring schedule to today
334 chargingProfile
.chargingProfileKind
=== ChargingProfileKindType
.RECURRING
&&
335 chargingProfile
.recurrencyKind
=== RecurrencyKindType
.DAILY
&&
336 currentMoment
.isAfter(chargingSchedule
.startSchedule
)
338 const currentDate
= new Date();
339 chargingSchedule
.startSchedule
= new Date(chargingSchedule
.startSchedule
);
340 chargingSchedule
.startSchedule
.setFullYear(
341 currentDate
.getFullYear(),
342 currentDate
.getMonth(),
343 currentDate
.getDate()
345 // Check if the start of the schedule is yesterday
346 if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
347 chargingSchedule
.startSchedule
.setDate(currentDate
.getDate() - 1);
349 } else if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
352 // Check if the charging profile is active
354 moment(chargingSchedule
.startSchedule
)
355 .add(chargingSchedule
.duration
, 's')
356 .isAfter(currentMoment
)
358 let lastButOneSchedule
: ChargingSchedulePeriod
;
359 // Search the right schedule period
360 for (const schedulePeriod
of chargingSchedule
.chargingSchedulePeriod
) {
361 // Handling of only one period
363 chargingSchedule
.chargingSchedulePeriod
.length
=== 1 &&
364 schedulePeriod
.startPeriod
=== 0
367 limit
: schedulePeriod
.limit
,
368 matchingChargingProfile
: chargingProfile
,
371 `${logPrefix} Matching charging profile found for power limitation: %j`,
376 // Find the right schedule period
378 moment(chargingSchedule
.startSchedule
)
379 .add(schedulePeriod
.startPeriod
, 's')
380 .isAfter(currentMoment
)
382 // Found the schedule: last but one is the correct one
384 limit
: lastButOneSchedule
.limit
,
385 matchingChargingProfile
: chargingProfile
,
388 `${logPrefix} Matching charging profile found for power limitation: %j`,
394 lastButOneSchedule
= schedulePeriod
;
395 // Handle the last schedule period
397 schedulePeriod
.startPeriod
===
398 chargingSchedule
.chargingSchedulePeriod
[
399 chargingSchedule
.chargingSchedulePeriod
.length
- 1
403 limit
: lastButOneSchedule
.limit
,
404 matchingChargingProfile
: chargingProfile
,
407 `${logPrefix} Matching charging profile found for power limitation: %j`,
418 public static getDefaultVoltageOut(
419 currentType
: CurrentType
,
420 templateFile
: string,
423 const errMsg
= `${logPrefix} Unknown ${currentType} currentOutType in template file ${templateFile}, cannot define default voltage out`;
424 let defaultVoltageOut
: number;
425 switch (currentType
) {
427 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
430 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
433 logger
.error(errMsg
);
434 throw new Error(errMsg
);
436 return defaultVoltageOut
;
439 public static getSampledValueTemplate(
440 chargingStation
: ChargingStation
,
442 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
443 phase
?: MeterValuePhase
444 ): SampledValueTemplate
| undefined {
445 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
446 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
448 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
453 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
454 !ChargingStationConfigurationUtils
.getConfigurationKey(
456 StandardParametersKey
.MeterValuesSampledData
457 )?.value
.includes(measurand
)
460 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
461 StandardParametersKey.MeterValuesSampledData
466 const sampledValueTemplates
: SampledValueTemplate
[] =
467 chargingStation
.getConnectorStatus(connectorId
).MeterValues
;
470 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
474 !Constants
.SUPPORTED_MEASURANDS
.includes(
475 sampledValueTemplates
[index
]?.measurand
??
476 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
480 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
484 sampledValueTemplates
[index
]?.phase
=== phase
&&
485 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
486 ChargingStationConfigurationUtils
.getConfigurationKey(
488 StandardParametersKey
.MeterValuesSampledData
489 )?.value
.includes(measurand
)
491 return sampledValueTemplates
[index
];
494 !sampledValueTemplates
[index
].phase
&&
495 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
496 ChargingStationConfigurationUtils
.getConfigurationKey(
498 StandardParametersKey
.MeterValuesSampledData
499 )?.value
.includes(measurand
)
501 return sampledValueTemplates
[index
];
503 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
504 (!sampledValueTemplates
[index
].measurand
||
505 sampledValueTemplates
[index
].measurand
=== measurand
)
507 return sampledValueTemplates
[index
];
510 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
511 const errorMsg
= `${chargingStation.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
512 logger
.error(errorMsg
);
513 throw new Error(errorMsg
);
516 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
520 public static getAuthorizedTags(
521 stationInfo
: ChargingStationInfo
,
522 templateFile
: string,
525 let authorizedTags
: string[] = [];
526 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(stationInfo
);
527 if (authorizationFile
) {
529 // Load authorization file
530 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
532 FileUtils
.handleFileException(
534 FileType
.Authorization
,
536 error
as NodeJS
.ErrnoException
540 logger
.info(logPrefix
+ ' No authorization file given in template file ' + templateFile
);
542 return authorizedTags
;
545 public static getAuthorizationFile(stationInfo
: ChargingStationInfo
): string | undefined {
547 stationInfo
.authorizationFile
&&
549 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
551 path
.basename(stationInfo
.authorizationFile
)
556 private static getRandomSerialNumberSuffix(params
?: {
557 randomBytesLength
?: number;
560 const randomSerialNumberSuffix
= crypto
561 .randomBytes(params
?.randomBytesLength
?? 16)
563 if (params
?.upperCase
) {
564 return randomSerialNumberSuffix
.toUpperCase();
566 return randomSerialNumberSuffix
;