9eee346630083ee75dc623af9b16c6ff14704d0f
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationUtils.ts
1 import { ChargingProfile, ChargingSchedulePeriod } from '../types/ocpp/ChargingProfile';
2 import { ChargingProfileKindType, RecurrencyKindType } from '../types/ocpp/1.6/ChargingProfile';
3 import ChargingStationTemplate, {
4 AmpereUnits,
5 CurrentType,
6 Voltage,
7 } from '../types/ChargingStationTemplate';
8 import { MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
9
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 fs from 'fs';
26 import logger from '../utils/Logger';
27 import moment from 'moment';
28 import path from 'path';
29
30 export class ChargingStationUtils {
31 public static getChargingStationId(
32 index: number,
33 stationTemplate: ChargingStationTemplate
34 ): string {
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 +
42 '-' +
43 instanceIndex.toString() +
44 idStr.substring(idStr.length - 4) +
45 idSuffix;
46 }
47
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,
54 }),
55 ...(!Utils.isUndefined(stationTemplate.chargePointSerialNumberPrefix) && {
56 chargePointSerialNumber: stationTemplate.chargePointSerialNumberPrefix,
57 }),
58 ...(!Utils.isUndefined(stationTemplate.firmwareVersion) && {
59 firmwareVersion: stationTemplate.firmwareVersion,
60 }),
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,
65 }),
66 ...(!Utils.isUndefined(stationTemplate.meterType) && {
67 meterType: stationTemplate.meterType,
68 }),
69 };
70 return crypto
71 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
72 .update(
73 JSON.stringify(hashBootNotificationRequest) +
74 ChargingStationUtils.getChargingStationId(index, stationTemplate)
75 )
76 .digest('hex');
77 }
78
79 public static getTemplateMaxNumberOfConnectors(stationTemplate: ChargingStationTemplate): number {
80 const templateConnectors = stationTemplate?.Connectors;
81 if (!templateConnectors) {
82 return -1;
83 }
84 return Object.keys(templateConnectors).length;
85 }
86
87 public static checkTemplateMaxConnectors(
88 templateMaxConnectors: number,
89 templateFile: string,
90 logPrefix: string
91 ): void {
92 if (templateMaxConnectors === 0) {
93 logger.warn(
94 `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration`
95 );
96 } else if (templateMaxConnectors < 0) {
97 logger.error(
98 `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined`
99 );
100 }
101 }
102
103 public static getConfiguredNumberOfConnectors(
104 index: number,
105 stationTemplate: ChargingStationTemplate
106 ): number {
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;
114 } else {
115 configuredMaxConnectors = stationTemplate?.Connectors[0]
116 ? ChargingStationUtils.getTemplateMaxNumberOfConnectors(stationTemplate) - 1
117 : ChargingStationUtils.getTemplateMaxNumberOfConnectors(stationTemplate);
118 }
119 return configuredMaxConnectors;
120 }
121
122 public static checkConfiguredMaxConnectors(
123 configuredMaxConnectors: number,
124 templateFile: string,
125 logPrefix: string
126 ): void {
127 if (configuredMaxConnectors <= 0) {
128 logger.warn(
129 `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors`
130 );
131 }
132 }
133
134 public static createBootNotificationRequest(
135 stationInfo: ChargingStationInfo
136 ): BootNotificationRequest {
137 return {
138 chargePointModel: stationInfo.chargePointModel,
139 chargePointVendor: stationInfo.chargePointVendor,
140 ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumber) && {
141 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumber,
142 }),
143 ...(!Utils.isUndefined(stationInfo.chargePointSerialNumber) && {
144 chargePointSerialNumber: stationInfo.chargePointSerialNumber,
145 }),
146 ...(!Utils.isUndefined(stationInfo.firmwareVersion) && {
147 firmwareVersion: stationInfo.firmwareVersion,
148 }),
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,
153 }),
154 ...(!Utils.isUndefined(stationInfo.meterType) && {
155 meterType: stationInfo.meterType,
156 }),
157 };
158 }
159
160 public static workerPoolInUse(): boolean {
161 return [WorkerProcessType.DYNAMIC_POOL, WorkerProcessType.STATIC_POOL].includes(
162 Configuration.getWorkerProcess()
163 );
164 }
165
166 public static workerDynamicPoolInUse(): boolean {
167 return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL;
168 }
169
170 /**
171 * Convert websocket error code to human readable string message
172 *
173 * @param code websocket error code
174 * @returns human readable string message
175 */
176 public static getWebSocketCloseEventStatusString(code: number): string {
177 if (code >= 0 && code <= 999) {
178 return '(Unused)';
179 } else if (code >= 1016) {
180 if (code <= 1999) {
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)';
188 }
189 }
190 if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) {
191 return WebSocketCloseEventStatusString[code] as string;
192 }
193 return '(Unknown)';
194 }
195
196 public static warnDeprecatedTemplateKey(
197 template: ChargingStationTemplate,
198 key: string,
199 templateFile: string,
200 logPrefix: string,
201 logMsgToAppend = ''
202 ): void {
203 if (!Utils.isUndefined(template[key])) {
204 logger.warn(
205 `${logPrefix} Deprecated template key '${key}' usage in file '${templateFile}'${
206 logMsgToAppend && '. ' + logMsgToAppend
207 }`
208 );
209 }
210 }
211
212 public static convertDeprecatedTemplateKey(
213 template: ChargingStationTemplate,
214 deprecatedKey: string,
215 key: string
216 ): void {
217 if (!Utils.isUndefined(template[deprecatedKey])) {
218 template[key] = template[deprecatedKey] as unknown;
219 delete template[deprecatedKey];
220 }
221 }
222
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;
235 }
236
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))
242 .digest('hex');
243 }
244
245 public static createSerialNumber(
246 stationTemplate: ChargingStationTemplate,
247 stationInfo: ChargingStationInfo = {} as ChargingStationInfo,
248 params: {
249 randomSerialNumberUpperCase?: boolean;
250 randomSerialNumber?: boolean;
251 } = {
252 randomSerialNumberUpperCase: true,
253 randomSerialNumber: true,
254 }
255 ): void {
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,
262 })
263 : '';
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;
273 }
274
275 public static propagateSerialNumber(
276 stationTemplate: ChargingStationTemplate,
277 stationInfoSrc: ChargingStationInfo,
278 stationInfoDst: ChargingStationInfo = {} as ChargingStationInfo
279 ) {
280 if (!stationInfoSrc || !stationTemplate) {
281 throw new BaseError(
282 'Missing charging station template or existing configuration to propagate serial number'
283 );
284 }
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;
294 }
295
296 public static getAmperageLimitationUnitDivider(stationInfo: ChargingStationInfo): number {
297 let unitDivider = 1;
298 switch (stationInfo.amperageLimitationUnit) {
299 case AmpereUnits.DECI_AMPERE:
300 unitDivider = 10;
301 break;
302 case AmpereUnits.CENTI_AMPERE:
303 unitDivider = 100;
304 break;
305 case AmpereUnits.MILLI_AMPERE:
306 unitDivider = 1000;
307 break;
308 }
309 return unitDivider;
310 }
311
312 /**
313 * Charging profiles should already be sorted by connectorId and stack level (highest stack level has priority)
314 *
315 * @param {ChargingProfile[]} chargingProfiles
316 * @param {string} logPrefix
317 * @returns {{ limit, matchingChargingProfile }}
318 */
319 public static getLimitFromChargingProfiles(
320 chargingProfiles: ChargingProfile[],
321 logPrefix: string
322 ): {
323 limit: number;
324 matchingChargingProfile: ChargingProfile;
325 } | null {
326 for (const chargingProfile of chargingProfiles) {
327 // Set helpers
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
332 if (
333 chargingProfile.chargingProfileKind === ChargingProfileKindType.RECURRING &&
334 chargingProfile.recurrencyKind === RecurrencyKindType.DAILY &&
335 currentMoment.isAfter(chargingSchedule.startSchedule)
336 ) {
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()
343 );
344 // Check if the start of the schedule is yesterday
345 if (moment(chargingSchedule.startSchedule).isAfter(currentMoment)) {
346 chargingSchedule.startSchedule.setDate(currentDate.getDate() - 1);
347 }
348 } else if (moment(chargingSchedule.startSchedule).isAfter(currentMoment)) {
349 return null;
350 }
351 // Check if the charging profile is active
352 if (
353 moment(chargingSchedule.startSchedule)
354 .add(chargingSchedule.duration, 's')
355 .isAfter(currentMoment)
356 ) {
357 let lastButOneSchedule: ChargingSchedulePeriod;
358 // Search the right schedule period
359 for (const schedulePeriod of chargingSchedule.chargingSchedulePeriod) {
360 // Handling of only one period
361 if (
362 chargingSchedule.chargingSchedulePeriod.length === 1 &&
363 schedulePeriod.startPeriod === 0
364 ) {
365 const result = {
366 limit: schedulePeriod.limit,
367 matchingChargingProfile: chargingProfile,
368 };
369 logger.debug(
370 `${logPrefix} Matching charging profile found for power limitation: %j`,
371 result
372 );
373 return result;
374 }
375 // Find the right schedule period
376 if (
377 moment(chargingSchedule.startSchedule)
378 .add(schedulePeriod.startPeriod, 's')
379 .isAfter(currentMoment)
380 ) {
381 // Found the schedule: last but one is the correct one
382 const result = {
383 limit: lastButOneSchedule.limit,
384 matchingChargingProfile: chargingProfile,
385 };
386 logger.debug(
387 `${logPrefix} Matching charging profile found for power limitation: %j`,
388 result
389 );
390 return result;
391 }
392 // Keep it
393 lastButOneSchedule = schedulePeriod;
394 // Handle the last schedule period
395 if (
396 schedulePeriod.startPeriod ===
397 chargingSchedule.chargingSchedulePeriod[
398 chargingSchedule.chargingSchedulePeriod.length - 1
399 ].startPeriod
400 ) {
401 const result = {
402 limit: lastButOneSchedule.limit,
403 matchingChargingProfile: chargingProfile,
404 };
405 logger.debug(
406 `${logPrefix} Matching charging profile found for power limitation: %j`,
407 result
408 );
409 return result;
410 }
411 }
412 }
413 }
414 return null;
415 }
416
417 public static getDefaultVoltageOut(
418 currentType: CurrentType,
419 templateFile: string,
420 logPrefix: string
421 ): Voltage {
422 const errMsg = `${logPrefix} Unknown ${currentType} currentOutType in template file ${templateFile}, cannot define default voltage out`;
423 let defaultVoltageOut: number;
424 switch (currentType) {
425 case CurrentType.AC:
426 defaultVoltageOut = Voltage.VOLTAGE_230;
427 break;
428 case CurrentType.DC:
429 defaultVoltageOut = Voltage.VOLTAGE_400;
430 break;
431 default:
432 logger.error(errMsg);
433 throw new Error(errMsg);
434 }
435 return defaultVoltageOut;
436 }
437
438 public static getSampledValueTemplate(
439 chargingStation: ChargingStation,
440 connectorId: number,
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)) {
446 logger.warn(
447 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
448 );
449 return;
450 }
451 if (
452 measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
453 !ChargingStationConfigurationUtils.getConfigurationKey(
454 chargingStation,
455 StandardParametersKey.MeterValuesSampledData
456 )?.value.includes(measurand)
457 ) {
458 logger.debug(
459 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
460 StandardParametersKey.MeterValuesSampledData
461 }' OCPP parameter`
462 );
463 return;
464 }
465 const sampledValueTemplates: SampledValueTemplate[] =
466 chargingStation.getConnectorStatus(connectorId).MeterValues;
467 for (
468 let index = 0;
469 !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length;
470 index++
471 ) {
472 if (
473 !Constants.SUPPORTED_MEASURANDS.includes(
474 sampledValueTemplates[index]?.measurand ??
475 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
476 )
477 ) {
478 logger.warn(
479 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
480 );
481 } else if (
482 phase &&
483 sampledValueTemplates[index]?.phase === phase &&
484 sampledValueTemplates[index]?.measurand === measurand &&
485 ChargingStationConfigurationUtils.getConfigurationKey(
486 chargingStation,
487 StandardParametersKey.MeterValuesSampledData
488 )?.value.includes(measurand)
489 ) {
490 return sampledValueTemplates[index];
491 } else if (
492 !phase &&
493 !sampledValueTemplates[index].phase &&
494 sampledValueTemplates[index]?.measurand === measurand &&
495 ChargingStationConfigurationUtils.getConfigurationKey(
496 chargingStation,
497 StandardParametersKey.MeterValuesSampledData
498 )?.value.includes(measurand)
499 ) {
500 return sampledValueTemplates[index];
501 } else if (
502 measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
503 (!sampledValueTemplates[index].measurand ||
504 sampledValueTemplates[index].measurand === measurand)
505 ) {
506 return sampledValueTemplates[index];
507 }
508 }
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);
513 }
514 logger.debug(
515 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
516 );
517 }
518
519 public static getAuthorizedTags(
520 stationInfo: ChargingStationInfo,
521 templateFile: string,
522 logPrefix: string
523 ): string[] {
524 let authorizedTags: string[] = [];
525 const authorizationFile = ChargingStationUtils.getAuthorizationFile(stationInfo);
526 if (authorizationFile) {
527 try {
528 // Load authorization file
529 authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[];
530 } catch (error) {
531 FileUtils.handleFileException(
532 logPrefix,
533 FileType.Authorization,
534 authorizationFile,
535 error as NodeJS.ErrnoException
536 );
537 }
538 } else {
539 logger.info(logPrefix + ' No authorization file given in template file ' + templateFile);
540 }
541 return authorizedTags;
542 }
543
544 public static getAuthorizationFile(stationInfo: ChargingStationInfo): string | undefined {
545 return (
546 stationInfo.authorizationFile &&
547 path.join(
548 path.resolve(__dirname, '../'),
549 'assets',
550 path.basename(stationInfo.authorizationFile)
551 )
552 );
553 }
554
555 private static getRandomSerialNumberSuffix(params?: {
556 randomBytesLength?: number;
557 upperCase?: boolean;
558 }): string {
559 const randomSerialNumberSuffix = crypto
560 .randomBytes(params?.randomBytesLength ?? 16)
561 .toString('hex');
562 if (params?.upperCase) {
563 return randomSerialNumberSuffix.toUpperCase();
564 }
565 return randomSerialNumberSuffix;
566 }
567 }