Small variable namespace cleanups
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { ACElectricUtils, DCElectricUtils } from '../utils/ElectricUtils';
4 import {
5 AvailabilityType,
6 BootNotificationRequest,
7 CachedRequest,
8 IncomingRequest,
9 IncomingRequestCommand,
10 RequestCommand,
11 } from '../types/ocpp/Requests';
12 import {
13 BootNotificationResponse,
14 HeartbeatResponse,
15 MeterValuesResponse,
16 RegistrationStatus,
17 StatusNotificationResponse,
18 } from '../types/ocpp/Responses';
19 import ChargingStationConfiguration, { Section } from '../types/ChargingStationConfiguration';
20 import ChargingStationOcppConfiguration, {
21 ConfigurationKey,
22 } from '../types/ChargingStationOcppConfiguration';
23 import ChargingStationTemplate, {
24 AmpereUnits,
25 CurrentType,
26 PowerUnits,
27 Voltage,
28 WsOptions,
29 } from '../types/ChargingStationTemplate';
30 import {
31 ConnectorPhaseRotation,
32 StandardParametersKey,
33 SupportedFeatureProfiles,
34 VendorDefaultParametersKey,
35 } from '../types/ocpp/Configuration';
36 import { MeterValue, MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
37 import { StopTransactionReason, StopTransactionResponse } from '../types/ocpp/Transaction';
38 import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
39 import WebSocket, { Data, OPEN, RawData } from 'ws';
40
41 import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
42 import { ChargePointErrorCode } from '../types/ocpp/ChargePointErrorCode';
43 import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
44 import { ChargingProfile } from '../types/ocpp/ChargingProfile';
45 import ChargingStationInfo from '../types/ChargingStationInfo';
46 import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
47 import Configuration from '../utils/Configuration';
48 import { ConnectorStatus } from '../types/ConnectorStatus';
49 import Constants from '../utils/Constants';
50 import { ErrorType } from '../types/ocpp/ErrorType';
51 import { FileType } from '../types/FileType';
52 import FileUtils from '../utils/FileUtils';
53 import { JsonType } from '../types/JsonType';
54 import { MessageType } from '../types/ocpp/MessageType';
55 import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
56 import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
57 import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
58 import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils';
59 import OCPPError from '../exception/OCPPError';
60 import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
61 import OCPPRequestService from './ocpp/OCPPRequestService';
62 import { OCPPVersion } from '../types/ocpp/OCPPVersion';
63 import PerformanceStatistics from '../performance/PerformanceStatistics';
64 import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates';
65 import { SupervisionUrlDistribution } from '../types/ConfigurationData';
66 import { URL } from 'url';
67 import Utils from '../utils/Utils';
68 import crypto from 'crypto';
69 import fs from 'fs';
70 import logger from '../utils/Logger';
71 import { parentPort } from 'worker_threads';
72 import path from 'path';
73
74 export default class ChargingStation {
75 public hashId!: string;
76 public readonly templateFile: string;
77 public authorizedTags: string[];
78 public stationInfo!: ChargingStationInfo;
79 public readonly connectors: Map<number, ConnectorStatus>;
80 public ocppConfiguration!: ChargingStationOcppConfiguration;
81 public wsConnection!: WebSocket;
82 public readonly requests: Map<string, CachedRequest>;
83 public performanceStatistics!: PerformanceStatistics;
84 public heartbeatSetInterval!: NodeJS.Timeout;
85 public ocppRequestService!: OCPPRequestService;
86 public bootNotificationResponse!: BootNotificationResponse | null;
87 private readonly index: number;
88 private configurationFile!: string;
89 private bootNotificationRequest!: BootNotificationRequest;
90 private connectorsConfigurationHash!: string;
91 private ocppIncomingRequestService!: OCPPIncomingRequestService;
92 private readonly messageBuffer: Set<string>;
93 private wsConfiguredConnectionUrl!: URL;
94 private wsConnectionRestarted: boolean;
95 private stopped: boolean;
96 private autoReconnectRetryCount: number;
97 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
98 private webSocketPingSetInterval!: NodeJS.Timeout;
99
100 constructor(index: number, templateFile: string) {
101 this.index = index;
102 this.templateFile = templateFile;
103 this.stopped = false;
104 this.wsConnectionRestarted = false;
105 this.autoReconnectRetryCount = 0;
106 this.connectors = new Map<number, ConnectorStatus>();
107 this.requests = new Map<string, CachedRequest>();
108 this.messageBuffer = new Set<string>();
109 this.initialize();
110 this.authorizedTags = this.getAuthorizedTags();
111 }
112
113 private get wsConnectionUrl(): URL {
114 return this.getSupervisionUrlOcppConfiguration()
115 ? new URL(
116 this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value +
117 '/' +
118 this.stationInfo.chargingStationId
119 )
120 : this.wsConfiguredConnectionUrl;
121 }
122
123 public logPrefix(): string {
124 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
125 }
126
127 public getBootNotificationRequest(): BootNotificationRequest {
128 return this.bootNotificationRequest;
129 }
130
131 public getRandomIdTag(): string {
132 const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
133 return this.authorizedTags[index];
134 }
135
136 public hasAuthorizedTags(): boolean {
137 return !Utils.isEmptyArray(this.authorizedTags);
138 }
139
140 public getEnableStatistics(): boolean | undefined {
141 return !Utils.isUndefined(this.stationInfo.enableStatistics)
142 ? this.stationInfo.enableStatistics
143 : true;
144 }
145
146 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
147 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
148 }
149
150 public getNumberOfPhases(): number | undefined {
151 switch (this.getCurrentOutType()) {
152 case CurrentType.AC:
153 return !Utils.isUndefined(this.stationInfo.numberOfPhases)
154 ? this.stationInfo.numberOfPhases
155 : 3;
156 case CurrentType.DC:
157 return 0;
158 }
159 }
160
161 public isWebSocketConnectionOpened(): boolean {
162 return this?.wsConnection?.readyState === OPEN;
163 }
164
165 public getRegistrationStatus(): RegistrationStatus {
166 return this?.bootNotificationResponse?.status;
167 }
168
169 public isInUnknownState(): boolean {
170 return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status);
171 }
172
173 public isInPendingState(): boolean {
174 return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING;
175 }
176
177 public isInAcceptedState(): boolean {
178 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
179 }
180
181 public isInRejectedState(): boolean {
182 return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED;
183 }
184
185 public isRegistered(): boolean {
186 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
187 }
188
189 public isChargingStationAvailable(): boolean {
190 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
191 }
192
193 public isConnectorAvailable(id: number): boolean {
194 return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
195 }
196
197 public getNumberOfConnectors(): number {
198 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
199 }
200
201 public getConnectorStatus(id: number): ConnectorStatus {
202 return this.connectors.get(id);
203 }
204
205 public getCurrentOutType(): CurrentType | undefined {
206 return this.stationInfo.currentOutType ?? CurrentType.AC;
207 }
208
209 public getOcppStrictCompliance(): boolean {
210 return this.stationInfo.ocppStrictCompliance ?? false;
211 }
212
213 public getVoltageOut(): number | undefined {
214 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
215 this.templateFile
216 }, cannot define default voltage out`;
217 let defaultVoltageOut: number;
218 switch (this.getCurrentOutType()) {
219 case CurrentType.AC:
220 defaultVoltageOut = Voltage.VOLTAGE_230;
221 break;
222 case CurrentType.DC:
223 defaultVoltageOut = Voltage.VOLTAGE_400;
224 break;
225 default:
226 logger.error(errMsg);
227 throw new Error(errMsg);
228 }
229 return !Utils.isUndefined(this.stationInfo.voltageOut)
230 ? this.stationInfo.voltageOut
231 : defaultVoltageOut;
232 }
233
234 public getMaximumConfiguredPower(): number | undefined {
235 let maximumConfiguredPower =
236 (this.stationInfo['maxPower'] as number) ?? this.stationInfo.maximumPower;
237 if (this.getAmperageLimitation() < this.stationInfo.maximumAmperage) {
238 maximumConfiguredPower =
239 this.getCurrentOutType() === CurrentType.AC
240 ? ACElectricUtils.powerTotal(
241 this.getNumberOfPhases(),
242 this.getVoltageOut(),
243 this.getAmperageLimitation() * this.getNumberOfConnectors()
244 )
245 : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation());
246 }
247 return maximumConfiguredPower;
248 }
249
250 public getTransactionIdTag(transactionId: number): string | undefined {
251 for (const connectorId of this.connectors.keys()) {
252 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
253 return this.getConnectorStatus(connectorId).transactionIdTag;
254 }
255 }
256 }
257
258 public getOutOfOrderEndMeterValues(): boolean {
259 return this.stationInfo.outOfOrderEndMeterValues ?? false;
260 }
261
262 public getBeginEndMeterValues(): boolean {
263 return this.stationInfo.beginEndMeterValues ?? false;
264 }
265
266 public getMeteringPerTransaction(): boolean {
267 return this.stationInfo.meteringPerTransaction ?? true;
268 }
269
270 public getTransactionDataMeterValues(): boolean {
271 return this.stationInfo.transactionDataMeterValues ?? false;
272 }
273
274 public getMainVoltageMeterValues(): boolean {
275 return this.stationInfo.mainVoltageMeterValues ?? true;
276 }
277
278 public getPhaseLineToLineVoltageMeterValues(): boolean {
279 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
280 }
281
282 public getConnectorIdByTransactionId(transactionId: number): number | undefined {
283 for (const connectorId of this.connectors.keys()) {
284 if (
285 connectorId > 0 &&
286 this.getConnectorStatus(connectorId)?.transactionId === transactionId
287 ) {
288 return connectorId;
289 }
290 }
291 }
292
293 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
294 const transactionConnectorStatus = this.getConnectorStatus(
295 this.getConnectorIdByTransactionId(transactionId)
296 );
297 if (this.getMeteringPerTransaction()) {
298 return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue;
299 }
300 return transactionConnectorStatus?.energyActiveImportRegisterValue;
301 }
302
303 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
304 const connectorStatus = this.getConnectorStatus(connectorId);
305 if (this.getMeteringPerTransaction()) {
306 return connectorStatus?.transactionEnergyActiveImportRegisterValue;
307 }
308 return connectorStatus?.energyActiveImportRegisterValue;
309 }
310
311 public getAuthorizeRemoteTxRequests(): boolean {
312 const authorizeRemoteTxRequests = this.getConfigurationKey(
313 StandardParametersKey.AuthorizeRemoteTxRequests
314 );
315 return authorizeRemoteTxRequests
316 ? Utils.convertToBoolean(authorizeRemoteTxRequests.value)
317 : false;
318 }
319
320 public getLocalAuthListEnabled(): boolean {
321 const localAuthListEnabled = this.getConfigurationKey(
322 StandardParametersKey.LocalAuthListEnabled
323 );
324 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
325 }
326
327 public restartWebSocketPing(): void {
328 // Stop WebSocket ping
329 this.stopWebSocketPing();
330 // Start WebSocket ping
331 this.startWebSocketPing();
332 }
333
334 public getSampledValueTemplate(
335 connectorId: number,
336 measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
337 phase?: MeterValuePhase
338 ): SampledValueTemplate | undefined {
339 const onPhaseStr = phase ? `on phase ${phase} ` : '';
340 if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
341 logger.warn(
342 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
343 );
344 return;
345 }
346 if (
347 measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
348 !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
349 measurand
350 )
351 ) {
352 logger.debug(
353 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
354 StandardParametersKey.MeterValuesSampledData
355 }' OCPP parameter`
356 );
357 return;
358 }
359 const sampledValueTemplates: SampledValueTemplate[] =
360 this.getConnectorStatus(connectorId).MeterValues;
361 for (
362 let index = 0;
363 !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length;
364 index++
365 ) {
366 if (
367 !Constants.SUPPORTED_MEASURANDS.includes(
368 sampledValueTemplates[index]?.measurand ??
369 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
370 )
371 ) {
372 logger.warn(
373 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
374 );
375 } else if (
376 phase &&
377 sampledValueTemplates[index]?.phase === phase &&
378 sampledValueTemplates[index]?.measurand === measurand &&
379 this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
380 measurand
381 )
382 ) {
383 return sampledValueTemplates[index];
384 } else if (
385 !phase &&
386 !sampledValueTemplates[index].phase &&
387 sampledValueTemplates[index]?.measurand === measurand &&
388 this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
389 measurand
390 )
391 ) {
392 return sampledValueTemplates[index];
393 } else if (
394 measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
395 (!sampledValueTemplates[index].measurand ||
396 sampledValueTemplates[index].measurand === measurand)
397 ) {
398 return sampledValueTemplates[index];
399 }
400 }
401 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
402 const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
403 logger.error(errorMsg);
404 throw new Error(errorMsg);
405 }
406 logger.debug(
407 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
408 );
409 }
410
411 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
412 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
413 }
414
415 public startHeartbeat(): void {
416 if (
417 this.getHeartbeatInterval() &&
418 this.getHeartbeatInterval() > 0 &&
419 !this.heartbeatSetInterval
420 ) {
421 // eslint-disable-next-line @typescript-eslint/no-misused-promises
422 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
423 await this.ocppRequestService.sendMessageHandler<HeartbeatResponse>(
424 RequestCommand.HEARTBEAT
425 );
426 }, this.getHeartbeatInterval());
427 logger.info(
428 this.logPrefix() +
429 ' Heartbeat started every ' +
430 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
431 );
432 } else if (this.heartbeatSetInterval) {
433 logger.info(
434 this.logPrefix() +
435 ' Heartbeat already started every ' +
436 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
437 );
438 } else {
439 logger.error(
440 `${this.logPrefix()} Heartbeat interval set to ${
441 this.getHeartbeatInterval()
442 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
443 : this.getHeartbeatInterval()
444 }, not starting the heartbeat`
445 );
446 }
447 }
448
449 public restartHeartbeat(): void {
450 // Stop heartbeat
451 this.stopHeartbeat();
452 // Start heartbeat
453 this.startHeartbeat();
454 }
455
456 public startMeterValues(connectorId: number, interval: number): void {
457 if (connectorId === 0) {
458 logger.error(
459 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
460 );
461 return;
462 }
463 if (!this.getConnectorStatus(connectorId)) {
464 logger.error(
465 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
466 );
467 return;
468 }
469 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
470 logger.error(
471 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
472 );
473 return;
474 } else if (
475 this.getConnectorStatus(connectorId)?.transactionStarted &&
476 !this.getConnectorStatus(connectorId)?.transactionId
477 ) {
478 logger.error(
479 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
480 );
481 return;
482 }
483 if (interval > 0) {
484 // eslint-disable-next-line @typescript-eslint/no-misused-promises
485 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(
486 // eslint-disable-next-line @typescript-eslint/no-misused-promises
487 async (): Promise<void> => {
488 // FIXME: Implement OCPP version agnostic helpers
489 const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue(
490 this,
491 connectorId,
492 this.getConnectorStatus(connectorId).transactionId,
493 interval
494 );
495 await this.ocppRequestService.sendMessageHandler<MeterValuesResponse>(
496 RequestCommand.METER_VALUES,
497 {
498 connectorId,
499 transactionId: this.getConnectorStatus(connectorId).transactionId,
500 meterValue: [meterValue],
501 }
502 );
503 },
504 interval
505 );
506 } else {
507 logger.error(
508 `${this.logPrefix()} Charging station ${
509 StandardParametersKey.MeterValueSampleInterval
510 } configuration set to ${
511 interval ? Utils.formatDurationMilliSeconds(interval) : interval
512 }, not sending MeterValues`
513 );
514 }
515 }
516
517 public start(): void {
518 if (this.getEnableStatistics()) {
519 this.performanceStatistics.start();
520 }
521 this.openWSConnection();
522 // Monitor authorization file
523 FileUtils.watchJsonFile<string[]>(
524 this.logPrefix(),
525 FileType.Authorization,
526 this.getAuthorizationFile(),
527 this.authorizedTags
528 );
529 // Monitor charging station template file
530 FileUtils.watchJsonFile(
531 this.logPrefix(),
532 FileType.ChargingStationTemplate,
533 this.templateFile,
534 null,
535 (event, filename): void => {
536 if (filename && event === 'change') {
537 try {
538 logger.debug(
539 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
540 this.templateFile
541 } file have changed, reload`
542 );
543 // Initialize
544 this.initialize();
545 // Restart the ATG
546 if (
547 !this.stationInfo.AutomaticTransactionGenerator.enable &&
548 this.automaticTransactionGenerator
549 ) {
550 this.automaticTransactionGenerator.stop();
551 }
552 this.startAutomaticTransactionGenerator();
553 if (this.getEnableStatistics()) {
554 this.performanceStatistics.restart();
555 } else {
556 this.performanceStatistics.stop();
557 }
558 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
559 } catch (error) {
560 logger.error(
561 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
562 error
563 );
564 }
565 }
566 }
567 );
568 // Handle WebSocket message
569 this.wsConnection.on(
570 'message',
571 this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
572 );
573 // Handle WebSocket error
574 this.wsConnection.on(
575 'error',
576 this.onError.bind(this) as (this: WebSocket, error: Error) => void
577 );
578 // Handle WebSocket close
579 this.wsConnection.on(
580 'close',
581 this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
582 );
583 // Handle WebSocket open
584 this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void);
585 // Handle WebSocket ping
586 this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void);
587 // Handle WebSocket pong
588 this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void);
589 parentPort.postMessage({
590 id: ChargingStationWorkerMessageEvents.STARTED,
591 data: { id: this.stationInfo.chargingStationId },
592 });
593 }
594
595 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
596 // Stop message sequence
597 await this.stopMessageSequence(reason);
598 for (const connectorId of this.connectors.keys()) {
599 if (connectorId > 0) {
600 await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
601 RequestCommand.STATUS_NOTIFICATION,
602 {
603 connectorId,
604 status: ChargePointStatus.UNAVAILABLE,
605 errorCode: ChargePointErrorCode.NO_ERROR,
606 }
607 );
608 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
609 }
610 }
611 if (this.isWebSocketConnectionOpened()) {
612 this.wsConnection.close();
613 }
614 if (this.getEnableStatistics()) {
615 this.performanceStatistics.stop();
616 }
617 this.bootNotificationResponse = null;
618 parentPort.postMessage({
619 id: ChargingStationWorkerMessageEvents.STOPPED,
620 data: { id: this.stationInfo.chargingStationId },
621 });
622 this.stopped = true;
623 }
624
625 public getConfigurationKey(
626 key: string | StandardParametersKey,
627 caseInsensitive = false
628 ): ConfigurationKey | undefined {
629 return this.ocppConfiguration.configurationKey.find((configElement) => {
630 if (caseInsensitive) {
631 return configElement.key.toLowerCase() === key.toLowerCase();
632 }
633 return configElement.key === key;
634 });
635 }
636
637 public addConfigurationKey(
638 key: string | StandardParametersKey,
639 value: string,
640 options: { readonly?: boolean; visible?: boolean; reboot?: boolean } = {
641 readonly: false,
642 visible: true,
643 reboot: false,
644 },
645 params: { overwrite?: boolean; save?: boolean } = { overwrite: false, save: false }
646 ): void {
647 options = options ?? ({} as { readonly?: boolean; visible?: boolean; reboot?: boolean });
648 options.readonly = options?.readonly ?? false;
649 options.visible = options?.visible ?? true;
650 options.reboot = options?.reboot ?? false;
651 let keyFound = this.getConfigurationKey(key);
652 if (keyFound && params?.overwrite) {
653 this.deleteConfigurationKey(keyFound.key, { save: false });
654 keyFound = undefined;
655 }
656 if (!keyFound) {
657 this.ocppConfiguration.configurationKey.push({
658 key,
659 readonly: options.readonly,
660 value,
661 visible: options.visible,
662 reboot: options.reboot,
663 });
664 params?.save && this.saveOcppConfiguration();
665 } else {
666 logger.error(
667 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
668 keyFound
669 );
670 }
671 }
672
673 public setConfigurationKeyValue(
674 key: string | StandardParametersKey,
675 value: string,
676 caseInsensitive = false
677 ): void {
678 const keyFound = this.getConfigurationKey(key, caseInsensitive);
679 if (keyFound) {
680 this.ocppConfiguration.configurationKey[
681 this.ocppConfiguration.configurationKey.indexOf(keyFound)
682 ].value = value;
683 this.saveOcppConfiguration();
684 } else {
685 logger.error(
686 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
687 { key, value }
688 );
689 }
690 }
691
692 public deleteConfigurationKey(
693 key: string | StandardParametersKey,
694 params: { save?: boolean; caseInsensitive?: boolean } = { save: true, caseInsensitive: false }
695 ): ConfigurationKey[] {
696 const keyFound = this.getConfigurationKey(key, params?.caseInsensitive);
697 if (keyFound) {
698 const deletedConfigurationKey = this.ocppConfiguration.configurationKey.splice(
699 this.ocppConfiguration.configurationKey.indexOf(keyFound),
700 1
701 );
702 params?.save && this.saveOcppConfiguration();
703 return deletedConfigurationKey;
704 }
705 }
706
707 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
708 let cpReplaced = false;
709 if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
710 this.getConnectorStatus(connectorId).chargingProfiles?.forEach(
711 (chargingProfile: ChargingProfile, index: number) => {
712 if (
713 chargingProfile.chargingProfileId === cp.chargingProfileId ||
714 (chargingProfile.stackLevel === cp.stackLevel &&
715 chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)
716 ) {
717 this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
718 cpReplaced = true;
719 }
720 }
721 );
722 }
723 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
724 }
725
726 public resetConnectorStatus(connectorId: number): void {
727 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
728 this.getConnectorStatus(connectorId).idTagAuthorized = false;
729 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
730 this.getConnectorStatus(connectorId).transactionStarted = false;
731 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
732 delete this.getConnectorStatus(connectorId).authorizeIdTag;
733 delete this.getConnectorStatus(connectorId).transactionId;
734 delete this.getConnectorStatus(connectorId).transactionIdTag;
735 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
736 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
737 this.stopMeterValues(connectorId);
738 }
739
740 public bufferMessage(message: string): void {
741 this.messageBuffer.add(message);
742 }
743
744 private flushMessageBuffer() {
745 if (this.messageBuffer.size > 0) {
746 this.messageBuffer.forEach((message) => {
747 // TODO: evaluate the need to track performance
748 this.wsConnection.send(message);
749 this.messageBuffer.delete(message);
750 });
751 }
752 }
753
754 private getSupervisionUrlOcppConfiguration(): boolean {
755 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
756 }
757
758 private getSupervisionUrlOcppKey(): string {
759 return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
760 }
761
762 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
763 // In case of multiple instances: add instance index to charging station id
764 const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
765 const idSuffix = stationTemplate.nameSuffix ?? '';
766 const idStr = '000000000' + this.index.toString();
767 return stationTemplate.fixedName
768 ? stationTemplate.baseName
769 : stationTemplate.baseName +
770 '-' +
771 instanceIndex.toString() +
772 idStr.substring(idStr.length - 4) +
773 idSuffix;
774 }
775
776 private getRandomSerialNumberSuffix(params?: {
777 randomBytesLength?: number;
778 upperCase?: boolean;
779 }): string {
780 const randomSerialNumberSuffix = crypto
781 .randomBytes(params?.randomBytesLength ?? 16)
782 .toString('hex');
783 if (params?.upperCase) {
784 return randomSerialNumberSuffix.toUpperCase();
785 }
786 return randomSerialNumberSuffix;
787 }
788
789 private getTemplateFromFile(): ChargingStationTemplate | null {
790 let template: ChargingStationTemplate = null;
791 try {
792 const measureId = `${FileType.ChargingStationTemplate} read`;
793 const beginId = PerformanceStatistics.beginMeasure(measureId);
794 template = JSON.parse(fs.readFileSync(this.templateFile, 'utf8')) as ChargingStationTemplate;
795 PerformanceStatistics.endMeasure(measureId, beginId);
796 } catch (error) {
797 FileUtils.handleFileException(
798 this.logPrefix(),
799 FileType.ChargingStationTemplate,
800 this.templateFile,
801 error as NodeJS.ErrnoException
802 );
803 }
804 return template;
805 }
806
807 private createSerialNumber(
808 stationInfo: ChargingStationInfo,
809 existingStationInfo?: ChargingStationInfo,
810 params: { randomSerialNumberUpperCase?: boolean; randomSerialNumber?: boolean } = {
811 randomSerialNumberUpperCase: true,
812 randomSerialNumber: true,
813 }
814 ): void {
815 params = params ?? {};
816 params.randomSerialNumberUpperCase = params?.randomSerialNumberUpperCase ?? true;
817 params.randomSerialNumber = params?.randomSerialNumber ?? true;
818 if (existingStationInfo) {
819 existingStationInfo?.chargePointSerialNumber &&
820 (stationInfo.chargePointSerialNumber = existingStationInfo.chargePointSerialNumber);
821 existingStationInfo?.chargeBoxSerialNumber &&
822 (stationInfo.chargeBoxSerialNumber = existingStationInfo.chargeBoxSerialNumber);
823 } else {
824 const serialNumberSuffix = params?.randomSerialNumber
825 ? this.getRandomSerialNumberSuffix({ upperCase: params.randomSerialNumberUpperCase })
826 : '';
827 stationInfo.chargePointSerialNumber =
828 stationInfo?.chargePointSerialNumberPrefix &&
829 stationInfo.chargePointSerialNumberPrefix + serialNumberSuffix;
830 stationInfo.chargeBoxSerialNumber =
831 stationInfo?.chargeBoxSerialNumberPrefix &&
832 stationInfo.chargeBoxSerialNumberPrefix + serialNumberSuffix;
833 }
834 }
835
836 private getStationInfoFromTemplate(): ChargingStationInfo {
837 const stationInfo: ChargingStationInfo =
838 this.getTemplateFromFile() ?? ({} as ChargingStationInfo);
839 stationInfo.hash = crypto
840 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
841 .update(JSON.stringify(stationInfo))
842 .digest('hex');
843 const chargingStationId = this.getChargingStationId(stationInfo);
844 // Deprecation template keys section
845 this.warnDeprecatedTemplateKey(
846 stationInfo,
847 'supervisionUrl',
848 chargingStationId,
849 "Use 'supervisionUrls' instead"
850 );
851 this.convertDeprecatedTemplateKey(stationInfo, 'supervisionUrl', 'supervisionUrls');
852 stationInfo.wsOptions = stationInfo?.wsOptions ?? {};
853 if (!Utils.isEmptyArray(stationInfo.power)) {
854 stationInfo.power = stationInfo.power as number[];
855 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationInfo.power.length);
856 stationInfo.maximumPower =
857 stationInfo.powerUnit === PowerUnits.KILO_WATT
858 ? stationInfo.power[powerArrayRandomIndex] * 1000
859 : stationInfo.power[powerArrayRandomIndex];
860 } else {
861 stationInfo.power = stationInfo.power as number;
862 stationInfo.maximumPower =
863 stationInfo.powerUnit === PowerUnits.KILO_WATT
864 ? stationInfo.power * 1000
865 : stationInfo.power;
866 }
867 delete stationInfo.power;
868 delete stationInfo.powerUnit;
869 stationInfo.chargingStationId = chargingStationId;
870 stationInfo.resetTime = stationInfo.resetTime
871 ? stationInfo.resetTime * 1000
872 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
873 return stationInfo;
874 }
875
876 private getStationInfoFromFile(): ChargingStationInfo | null {
877 return this.getConfigurationFromFile()?.stationInfo ?? null;
878 }
879
880 private getStationInfo(): ChargingStationInfo {
881 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
882 this.hashId = this.getHashId(stationInfoFromTemplate);
883 this.configurationFile = path.join(
884 path.resolve(__dirname, '../'),
885 'assets',
886 'configurations',
887 this.hashId + '.json'
888 );
889 const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
890 if (stationInfoFromFile?.hash === stationInfoFromTemplate.hash) {
891 return stationInfoFromFile;
892 }
893 this.createSerialNumber(stationInfoFromTemplate, stationInfoFromFile);
894 return stationInfoFromTemplate;
895 }
896
897 private saveStationInfo(): void {
898 this.saveConfiguration(Section.stationInfo);
899 }
900
901 private getOcppVersion(): OCPPVersion {
902 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
903 }
904
905 private getOcppPersistentConfiguration(): boolean {
906 return this.stationInfo.ocppPersistentConfiguration ?? true;
907 }
908
909 private handleUnsupportedVersion(version: OCPPVersion) {
910 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
911 this.templateFile
912 }`;
913 logger.error(errMsg);
914 throw new Error(errMsg);
915 }
916
917 private createBootNotificationRequest(stationInfo: ChargingStationInfo): BootNotificationRequest {
918 return {
919 chargePointModel: stationInfo.chargePointModel,
920 chargePointVendor: stationInfo.chargePointVendor,
921 ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumber) && {
922 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumber,
923 }),
924 ...(!Utils.isUndefined(stationInfo.chargePointSerialNumber) && {
925 chargePointSerialNumber: stationInfo.chargePointSerialNumber,
926 }),
927 ...(!Utils.isUndefined(stationInfo.firmwareVersion) && {
928 firmwareVersion: stationInfo.firmwareVersion,
929 }),
930 ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
931 ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
932 ...(!Utils.isUndefined(stationInfo.meterSerialNumber) && {
933 meterSerialNumber: stationInfo.meterSerialNumber,
934 }),
935 ...(!Utils.isUndefined(stationInfo.meterType) && {
936 meterType: stationInfo.meterType,
937 }),
938 };
939 }
940
941 private getHashId(stationInfo: ChargingStationInfo): string {
942 const hashBootNotificationRequest = {
943 chargePointModel: stationInfo.chargePointModel,
944 chargePointVendor: stationInfo.chargePointVendor,
945 ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumberPrefix) && {
946 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumberPrefix,
947 }),
948 ...(!Utils.isUndefined(stationInfo.chargePointSerialNumberPrefix) && {
949 chargePointSerialNumber: stationInfo.chargePointSerialNumberPrefix,
950 }),
951 ...(!Utils.isUndefined(stationInfo.firmwareVersion) && {
952 firmwareVersion: stationInfo.firmwareVersion,
953 }),
954 ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
955 ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
956 ...(!Utils.isUndefined(stationInfo.meterSerialNumber) && {
957 meterSerialNumber: stationInfo.meterSerialNumber,
958 }),
959 ...(!Utils.isUndefined(stationInfo.meterType) && {
960 meterType: stationInfo.meterType,
961 }),
962 };
963 return crypto
964 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
965 .update(JSON.stringify(hashBootNotificationRequest) + stationInfo.chargingStationId)
966 .digest('hex');
967 }
968
969 private initialize(): void {
970 this.stationInfo = this.getStationInfo();
971 logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
972 this.bootNotificationRequest = this.createBootNotificationRequest(this.stationInfo);
973 this.ocppConfiguration = this.getOcppConfiguration();
974 delete this.stationInfo.Configuration;
975 // Build connectors if needed
976 const maxConnectors = this.getMaxNumberOfConnectors();
977 if (maxConnectors <= 0) {
978 logger.warn(
979 `${this.logPrefix()} Charging station template ${
980 this.templateFile
981 } with ${maxConnectors} connectors`
982 );
983 }
984 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
985 if (templateMaxConnectors <= 0) {
986 logger.warn(
987 `${this.logPrefix()} Charging station template ${
988 this.templateFile
989 } with no connector configuration`
990 );
991 }
992 if (!this.stationInfo.Connectors[0]) {
993 logger.warn(
994 `${this.logPrefix()} Charging station template ${
995 this.templateFile
996 } with no connector Id 0 configuration`
997 );
998 }
999 // Sanity check
1000 if (
1001 maxConnectors >
1002 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
1003 !this.stationInfo.randomConnectors
1004 ) {
1005 logger.warn(
1006 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
1007 this.templateFile
1008 }, forcing random connector configurations affectation`
1009 );
1010 this.stationInfo.randomConnectors = true;
1011 }
1012 const connectorsConfigHash = crypto
1013 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1014 .update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString())
1015 .digest('hex');
1016 const connectorsConfigChanged =
1017 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
1018 if (this.connectors?.size === 0 || connectorsConfigChanged) {
1019 connectorsConfigChanged && this.connectors.clear();
1020 this.connectorsConfigurationHash = connectorsConfigHash;
1021 // Add connector Id 0
1022 let lastConnector = '0';
1023 for (lastConnector in this.stationInfo.Connectors) {
1024 const lastConnectorId = Utils.convertToInt(lastConnector);
1025 if (
1026 lastConnectorId === 0 &&
1027 this.getUseConnectorId0() &&
1028 this.stationInfo.Connectors[lastConnector]
1029 ) {
1030 this.connectors.set(
1031 lastConnectorId,
1032 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector])
1033 );
1034 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
1035 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
1036 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
1037 }
1038 }
1039 }
1040 // Generate all connectors
1041 if (
1042 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0
1043 ) {
1044 for (let index = 1; index <= maxConnectors; index++) {
1045 const randConnectorId = this.stationInfo.randomConnectors
1046 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
1047 : index;
1048 this.connectors.set(
1049 index,
1050 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId])
1051 );
1052 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
1053 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
1054 this.getConnectorStatus(index).chargingProfiles = [];
1055 }
1056 }
1057 }
1058 }
1059 // The connectors attribute need to be initialized
1060 this.stationInfo.maximumAmperage = this.getMaximumAmperage();
1061 this.saveStationInfo();
1062 // Avoid duplication of connectors related information in RAM
1063 delete this.stationInfo.Connectors;
1064 // Initialize transaction attributes on connectors
1065 for (const connectorId of this.connectors.keys()) {
1066 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
1067 this.initializeConnectorStatus(connectorId);
1068 }
1069 }
1070 this.wsConfiguredConnectionUrl = new URL(
1071 this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId
1072 );
1073 // OCPP configuration
1074 this.initializeOcppConfiguration();
1075 switch (this.getOcppVersion()) {
1076 case OCPPVersion.VERSION_16:
1077 this.ocppIncomingRequestService =
1078 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(this);
1079 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
1080 this,
1081 OCPP16ResponseService.getInstance<OCPP16ResponseService>(this)
1082 );
1083 break;
1084 default:
1085 this.handleUnsupportedVersion(this.getOcppVersion());
1086 break;
1087 }
1088 if (this.stationInfo.autoRegister) {
1089 this.bootNotificationResponse = {
1090 currentTime: new Date().toISOString(),
1091 interval: this.getHeartbeatInterval() / 1000,
1092 status: RegistrationStatus.ACCEPTED,
1093 };
1094 }
1095 this.stationInfo.powerDivider = this.getPowerDivider();
1096 if (this.getEnableStatistics()) {
1097 this.performanceStatistics = PerformanceStatistics.getInstance(
1098 this.hashId,
1099 this.stationInfo.chargingStationId,
1100 this.wsConnectionUrl
1101 );
1102 }
1103 }
1104
1105 private initializeOcppConfiguration(): void {
1106 if (
1107 this.getSupervisionUrlOcppConfiguration() &&
1108 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1109 ) {
1110 this.addConfigurationKey(
1111 this.getSupervisionUrlOcppKey(),
1112 this.getConfiguredSupervisionUrl().href,
1113 { reboot: true }
1114 );
1115 } else if (
1116 !this.getSupervisionUrlOcppConfiguration() &&
1117 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1118 ) {
1119 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save: false });
1120 }
1121 if (
1122 this.stationInfo.amperageLimitationOcppKey &&
1123 !this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey)
1124 ) {
1125 this.addConfigurationKey(
1126 this.stationInfo.amperageLimitationOcppKey,
1127 (this.stationInfo.maximumAmperage * this.getAmperageLimitationUnitDivider()).toString()
1128 );
1129 }
1130 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
1131 this.addConfigurationKey(
1132 StandardParametersKey.SupportedFeatureProfiles,
1133 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`
1134 );
1135 }
1136 this.addConfigurationKey(
1137 StandardParametersKey.NumberOfConnectors,
1138 this.getNumberOfConnectors().toString(),
1139 { readonly: true },
1140 { overwrite: true }
1141 );
1142 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
1143 this.addConfigurationKey(
1144 StandardParametersKey.MeterValuesSampledData,
1145 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1146 );
1147 }
1148 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
1149 const connectorPhaseRotation = [];
1150 for (const connectorId of this.connectors.keys()) {
1151 // AC/DC
1152 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1153 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1154 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1155 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1156 // AC
1157 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1158 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1159 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1160 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1161 }
1162 }
1163 this.addConfigurationKey(
1164 StandardParametersKey.ConnectorPhaseRotation,
1165 connectorPhaseRotation.toString()
1166 );
1167 }
1168 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
1169 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
1170 }
1171 if (
1172 !this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) &&
1173 this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(
1174 SupportedFeatureProfiles.Local_Auth_List_Management
1175 )
1176 ) {
1177 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
1178 }
1179 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
1180 this.addConfigurationKey(
1181 StandardParametersKey.ConnectionTimeOut,
1182 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1183 );
1184 }
1185 this.saveOcppConfiguration();
1186 }
1187
1188 private getConfigurationFromFile(): ChargingStationConfiguration | null {
1189 let configuration: ChargingStationConfiguration = null;
1190 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
1191 try {
1192 const measureId = `${FileType.ChargingStationConfiguration} read`;
1193 const beginId = PerformanceStatistics.beginMeasure(
1194 `${FileType.ChargingStationConfiguration} read`
1195 );
1196 configuration = JSON.parse(
1197 fs.readFileSync(this.configurationFile, 'utf8')
1198 ) as ChargingStationConfiguration;
1199 PerformanceStatistics.endMeasure(measureId, beginId);
1200 } catch (error) {
1201 FileUtils.handleFileException(
1202 this.logPrefix(),
1203 FileType.ChargingStationConfiguration,
1204 this.configurationFile,
1205 error as NodeJS.ErrnoException
1206 );
1207 }
1208 }
1209 return configuration;
1210 }
1211
1212 private saveConfiguration(section?: Section): void {
1213 if (this.configurationFile) {
1214 try {
1215 const configurationData: ChargingStationConfiguration =
1216 this.getConfigurationFromFile() ?? {};
1217 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1218 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
1219 }
1220 switch (section) {
1221 case Section.ocppConfiguration:
1222 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
1223 break;
1224 case Section.stationInfo:
1225 configurationData.stationInfo = this.stationInfo;
1226 break;
1227 default:
1228 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
1229 configurationData.stationInfo = this.stationInfo;
1230 break;
1231 }
1232 const measureId = `${FileType.ChargingStationConfiguration} write`;
1233 const beginId = PerformanceStatistics.beginMeasure(measureId);
1234 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1235 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1236 fs.closeSync(fileDescriptor);
1237 PerformanceStatistics.endMeasure(measureId, beginId);
1238 } catch (error) {
1239 FileUtils.handleFileException(
1240 this.logPrefix(),
1241 FileType.ChargingStationConfiguration,
1242 this.configurationFile,
1243 error as NodeJS.ErrnoException
1244 );
1245 }
1246 } else {
1247 logger.error(
1248 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
1249 );
1250 }
1251 }
1252
1253 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration {
1254 return this.getTemplateFromFile().Configuration ?? ({} as ChargingStationOcppConfiguration);
1255 }
1256
1257 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
1258 let configuration: ChargingStationConfiguration = null;
1259 if (this.getOcppPersistentConfiguration()) {
1260 const configurationFromFile = this.getConfigurationFromFile();
1261 configuration = configurationFromFile?.configurationKey && configurationFromFile;
1262 }
1263 configuration && delete configuration.stationInfo;
1264 return configuration;
1265 }
1266
1267 private getOcppConfiguration(): ChargingStationOcppConfiguration {
1268 let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
1269 if (!ocppConfiguration) {
1270 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1271 }
1272 return ocppConfiguration;
1273 }
1274
1275 private saveOcppConfiguration(): void {
1276 if (this.getOcppPersistentConfiguration()) {
1277 this.saveConfiguration(Section.ocppConfiguration);
1278 }
1279 }
1280
1281 private async onOpen(): Promise<void> {
1282 logger.info(
1283 `${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`
1284 );
1285 if (!this.isInAcceptedState()) {
1286 // Send BootNotification
1287 let registrationRetryCount = 0;
1288 do {
1289 this.bootNotificationResponse =
1290 await this.ocppRequestService.sendMessageHandler<BootNotificationResponse>(
1291 RequestCommand.BOOT_NOTIFICATION,
1292 {
1293 chargePointModel: this.bootNotificationRequest.chargePointModel,
1294 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1295 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1296 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1297 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1298 iccid: this.bootNotificationRequest.iccid,
1299 imsi: this.bootNotificationRequest.imsi,
1300 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1301 meterType: this.bootNotificationRequest.meterType,
1302 },
1303 { skipBufferingOnError: true }
1304 );
1305 if (!this.isInAcceptedState()) {
1306 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1307 await Utils.sleep(
1308 this.bootNotificationResponse?.interval
1309 ? this.bootNotificationResponse.interval * 1000
1310 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1311 );
1312 }
1313 } while (
1314 !this.isInAcceptedState() &&
1315 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1316 this.getRegistrationMaxRetries() === -1)
1317 );
1318 }
1319 if (this.isInAcceptedState()) {
1320 await this.startMessageSequence();
1321 this.stopped && (this.stopped = false);
1322 if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) {
1323 this.flushMessageBuffer();
1324 }
1325 } else {
1326 logger.error(
1327 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1328 );
1329 }
1330 this.autoReconnectRetryCount = 0;
1331 this.wsConnectionRestarted = false;
1332 }
1333
1334 private async onClose(code: number, reason: string): Promise<void> {
1335 switch (code) {
1336 // Normal close
1337 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
1338 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
1339 logger.info(
1340 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1341 code
1342 )}' and reason '${reason}'`
1343 );
1344 this.autoReconnectRetryCount = 0;
1345 break;
1346 // Abnormal close
1347 default:
1348 logger.error(
1349 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1350 code
1351 )}' and reason '${reason}'`
1352 );
1353 await this.reconnect(code);
1354 break;
1355 }
1356 }
1357
1358 private async onMessage(data: Data): Promise<void> {
1359 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [
1360 0,
1361 '',
1362 '' as IncomingRequestCommand,
1363 {},
1364 {},
1365 ];
1366 let responseCallback: (
1367 payload: JsonType | string,
1368 requestPayload: JsonType | OCPPError
1369 ) => void;
1370 let rejectCallback: (error: OCPPError, requestStatistic?: boolean) => void;
1371 let requestCommandName: RequestCommand | IncomingRequestCommand;
1372 let requestPayload: JsonType | OCPPError;
1373 let cachedRequest: CachedRequest;
1374 let errMsg: string;
1375 try {
1376 const request = JSON.parse(data.toString()) as IncomingRequest;
1377 if (Utils.isIterable(request)) {
1378 // Parse the message
1379 [messageType, messageId, commandName, commandPayload, errorDetails] = request;
1380 } else {
1381 throw new OCPPError(
1382 ErrorType.PROTOCOL_ERROR,
1383 'Incoming request is not iterable',
1384 commandName
1385 );
1386 }
1387 // Check the Type of message
1388 switch (messageType) {
1389 // Incoming Message
1390 case MessageType.CALL_MESSAGE:
1391 if (this.getEnableStatistics()) {
1392 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1393 }
1394 // Process the call
1395 await this.ocppIncomingRequestService.handleRequest(
1396 messageId,
1397 commandName,
1398 commandPayload
1399 );
1400 break;
1401 // Outcome Message
1402 case MessageType.CALL_RESULT_MESSAGE:
1403 // Respond
1404 cachedRequest = this.requests.get(messageId);
1405 if (Utils.isIterable(cachedRequest)) {
1406 [responseCallback, , , requestPayload] = cachedRequest;
1407 } else {
1408 throw new OCPPError(
1409 ErrorType.PROTOCOL_ERROR,
1410 `Cached request for message id ${messageId} response is not iterable`,
1411 commandName
1412 );
1413 }
1414 if (!responseCallback) {
1415 // Error
1416 throw new OCPPError(
1417 ErrorType.INTERNAL_ERROR,
1418 `Response for unknown message id ${messageId}`,
1419 commandName
1420 );
1421 }
1422 responseCallback(commandName, requestPayload);
1423 break;
1424 // Error Message
1425 case MessageType.CALL_ERROR_MESSAGE:
1426 cachedRequest = this.requests.get(messageId);
1427 if (Utils.isIterable(cachedRequest)) {
1428 [, rejectCallback, requestCommandName] = cachedRequest;
1429 } else {
1430 throw new OCPPError(
1431 ErrorType.PROTOCOL_ERROR,
1432 `Cached request for message id ${messageId} error response is not iterable`
1433 );
1434 }
1435 if (!rejectCallback) {
1436 // Error
1437 throw new OCPPError(
1438 ErrorType.INTERNAL_ERROR,
1439 `Error response for unknown message id ${messageId}`,
1440 requestCommandName
1441 );
1442 }
1443 rejectCallback(
1444 new OCPPError(commandName, commandPayload.toString(), requestCommandName, errorDetails)
1445 );
1446 break;
1447 // Error
1448 default:
1449 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1450 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
1451 logger.error(errMsg);
1452 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1453 }
1454 } catch (error) {
1455 // Log
1456 logger.error(
1457 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1458 this.logPrefix(),
1459 data.toString(),
1460 this.requests.get(messageId),
1461 error
1462 );
1463 // Send error
1464 messageType === MessageType.CALL_MESSAGE &&
1465 (await this.ocppRequestService.sendError(messageId, error as OCPPError, commandName));
1466 }
1467 }
1468
1469 private onPing(): void {
1470 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1471 }
1472
1473 private onPong(): void {
1474 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1475 }
1476
1477 private onError(error: WSError): void {
1478 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
1479 }
1480
1481 private getAuthorizationFile(): string | undefined {
1482 return (
1483 this.stationInfo.authorizationFile &&
1484 path.join(
1485 path.resolve(__dirname, '../'),
1486 'assets',
1487 path.basename(this.stationInfo.authorizationFile)
1488 )
1489 );
1490 }
1491
1492 private getAuthorizedTags(): string[] {
1493 let authorizedTags: string[] = [];
1494 const authorizationFile = this.getAuthorizationFile();
1495 if (authorizationFile) {
1496 try {
1497 // Load authorization file
1498 authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[];
1499 } catch (error) {
1500 FileUtils.handleFileException(
1501 this.logPrefix(),
1502 FileType.Authorization,
1503 authorizationFile,
1504 error as NodeJS.ErrnoException
1505 );
1506 }
1507 } else {
1508 logger.info(
1509 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1510 );
1511 }
1512 return authorizedTags;
1513 }
1514
1515 private getUseConnectorId0(): boolean | undefined {
1516 return !Utils.isUndefined(this.stationInfo.useConnectorId0)
1517 ? this.stationInfo.useConnectorId0
1518 : true;
1519 }
1520
1521 private getNumberOfRunningTransactions(): number {
1522 let trxCount = 0;
1523 for (const connectorId of this.connectors.keys()) {
1524 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1525 trxCount++;
1526 }
1527 }
1528 return trxCount;
1529 }
1530
1531 // 0 for disabling
1532 private getConnectionTimeout(): number | undefined {
1533 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
1534 return (
1535 parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ??
1536 Constants.DEFAULT_CONNECTION_TIMEOUT
1537 );
1538 }
1539 return Constants.DEFAULT_CONNECTION_TIMEOUT;
1540 }
1541
1542 // -1 for unlimited, 0 for disabling
1543 private getAutoReconnectMaxRetries(): number | undefined {
1544 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1545 return this.stationInfo.autoReconnectMaxRetries;
1546 }
1547 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1548 return Configuration.getAutoReconnectMaxRetries();
1549 }
1550 return -1;
1551 }
1552
1553 // 0 for disabling
1554 private getRegistrationMaxRetries(): number | undefined {
1555 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1556 return this.stationInfo.registrationMaxRetries;
1557 }
1558 return -1;
1559 }
1560
1561 private getPowerDivider(): number {
1562 let powerDivider = this.getNumberOfConnectors();
1563 if (this.stationInfo.powerSharedByConnectors) {
1564 powerDivider = this.getNumberOfRunningTransactions();
1565 }
1566 return powerDivider;
1567 }
1568
1569 private getTemplateMaxNumberOfConnectors(): number {
1570 return Object.keys(this.stationInfo.Connectors).length;
1571 }
1572
1573 private getMaxNumberOfConnectors(): number {
1574 let maxConnectors: number;
1575 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
1576 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
1577 // Distribute evenly the number of connectors
1578 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
1579 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
1580 maxConnectors = this.stationInfo.numberOfConnectors as number;
1581 } else {
1582 maxConnectors = this.stationInfo.Connectors[0]
1583 ? this.getTemplateMaxNumberOfConnectors() - 1
1584 : this.getTemplateMaxNumberOfConnectors();
1585 }
1586 return maxConnectors;
1587 }
1588
1589 private getMaximumAmperage(): number | undefined {
1590 switch (this.getCurrentOutType()) {
1591 case CurrentType.AC:
1592 return ACElectricUtils.amperagePerPhaseFromPower(
1593 this.getNumberOfPhases(),
1594 ((this.stationInfo['maxPower'] as number) ?? this.stationInfo.maximumPower) /
1595 this.getNumberOfConnectors(),
1596 this.getVoltageOut()
1597 );
1598 case CurrentType.DC:
1599 return DCElectricUtils.amperage(this.stationInfo.maximumPower, this.getVoltageOut());
1600 }
1601 }
1602
1603 private getAmperageLimitationUnitDivider(): number {
1604 let unitDivider = 1;
1605 switch (this.stationInfo.amperageLimitationUnit) {
1606 case AmpereUnits.DECI_AMPERE:
1607 unitDivider = 10;
1608 break;
1609 case AmpereUnits.CENTI_AMPERE:
1610 unitDivider = 100;
1611 break;
1612 case AmpereUnits.MILLI_AMPERE:
1613 unitDivider = 1000;
1614 break;
1615 }
1616 return unitDivider;
1617 }
1618
1619 private getAmperageLimitation(): number | undefined {
1620 if (
1621 this.stationInfo.amperageLimitationOcppKey &&
1622 this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey)
1623 ) {
1624 return (
1625 Utils.convertToInt(
1626 this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey).value
1627 ) / this.getAmperageLimitationUnitDivider()
1628 );
1629 }
1630 }
1631
1632 private async startMessageSequence(): Promise<void> {
1633 if (this.stationInfo.autoRegister) {
1634 await this.ocppRequestService.sendMessageHandler<BootNotificationResponse>(
1635 RequestCommand.BOOT_NOTIFICATION,
1636 {
1637 chargePointModel: this.bootNotificationRequest.chargePointModel,
1638 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1639 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1640 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1641 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1642 iccid: this.bootNotificationRequest.iccid,
1643 imsi: this.bootNotificationRequest.imsi,
1644 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1645 meterType: this.bootNotificationRequest.meterType,
1646 },
1647 { skipBufferingOnError: true }
1648 );
1649 }
1650 // Start WebSocket ping
1651 this.startWebSocketPing();
1652 // Start heartbeat
1653 this.startHeartbeat();
1654 // Initialize connectors status
1655 for (const connectorId of this.connectors.keys()) {
1656 if (connectorId === 0) {
1657 continue;
1658 } else if (
1659 !this.stopped &&
1660 !this.getConnectorStatus(connectorId)?.status &&
1661 this.getConnectorStatus(connectorId)?.bootStatus
1662 ) {
1663 // Send status in template at startup
1664 await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
1665 RequestCommand.STATUS_NOTIFICATION,
1666 {
1667 connectorId,
1668 status: this.getConnectorStatus(connectorId).bootStatus,
1669 errorCode: ChargePointErrorCode.NO_ERROR,
1670 }
1671 );
1672 this.getConnectorStatus(connectorId).status =
1673 this.getConnectorStatus(connectorId).bootStatus;
1674 } else if (
1675 this.stopped &&
1676 this.getConnectorStatus(connectorId)?.status &&
1677 this.getConnectorStatus(connectorId)?.bootStatus
1678 ) {
1679 // Send status in template after reset
1680 await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
1681 RequestCommand.STATUS_NOTIFICATION,
1682 {
1683 connectorId,
1684 status: this.getConnectorStatus(connectorId).bootStatus,
1685 errorCode: ChargePointErrorCode.NO_ERROR,
1686 }
1687 );
1688 this.getConnectorStatus(connectorId).status =
1689 this.getConnectorStatus(connectorId).bootStatus;
1690 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
1691 // Send previous status at template reload
1692 await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
1693 RequestCommand.STATUS_NOTIFICATION,
1694 {
1695 connectorId,
1696 status: this.getConnectorStatus(connectorId).status,
1697 errorCode: ChargePointErrorCode.NO_ERROR,
1698 }
1699 );
1700 } else {
1701 // Send default status
1702 await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
1703 RequestCommand.STATUS_NOTIFICATION,
1704 {
1705 connectorId,
1706 status: ChargePointStatus.AVAILABLE,
1707 errorCode: ChargePointErrorCode.NO_ERROR,
1708 }
1709 );
1710 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
1711 }
1712 }
1713 // Start the ATG
1714 this.startAutomaticTransactionGenerator();
1715 }
1716
1717 private startAutomaticTransactionGenerator() {
1718 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
1719 if (!this.automaticTransactionGenerator) {
1720 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this);
1721 }
1722 if (!this.automaticTransactionGenerator.started) {
1723 this.automaticTransactionGenerator.start();
1724 }
1725 }
1726 }
1727
1728 private async stopMessageSequence(
1729 reason: StopTransactionReason = StopTransactionReason.NONE
1730 ): Promise<void> {
1731 // Stop WebSocket ping
1732 this.stopWebSocketPing();
1733 // Stop heartbeat
1734 this.stopHeartbeat();
1735 // Stop the ATG
1736 if (
1737 this.stationInfo.AutomaticTransactionGenerator.enable &&
1738 this.automaticTransactionGenerator?.started
1739 ) {
1740 this.automaticTransactionGenerator.stop();
1741 } else {
1742 for (const connectorId of this.connectors.keys()) {
1743 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1744 const transactionId = this.getConnectorStatus(connectorId).transactionId;
1745 if (
1746 this.getBeginEndMeterValues() &&
1747 this.getOcppStrictCompliance() &&
1748 !this.getOutOfOrderEndMeterValues()
1749 ) {
1750 // FIXME: Implement OCPP version agnostic helpers
1751 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
1752 this,
1753 connectorId,
1754 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
1755 );
1756 await this.ocppRequestService.sendMessageHandler<MeterValuesResponse>(
1757 RequestCommand.METER_VALUES,
1758 {
1759 connectorId,
1760 transactionId,
1761 meterValue: transactionEndMeterValue,
1762 }
1763 );
1764 }
1765 await this.ocppRequestService.sendMessageHandler<StopTransactionResponse>(
1766 RequestCommand.STOP_TRANSACTION,
1767 {
1768 transactionId,
1769 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
1770 idTag: this.getTransactionIdTag(transactionId),
1771 reason,
1772 }
1773 );
1774 }
1775 }
1776 }
1777 }
1778
1779 private startWebSocketPing(): void {
1780 const webSocketPingInterval: number = this.getConfigurationKey(
1781 StandardParametersKey.WebSocketPingInterval
1782 )
1783 ? Utils.convertToInt(
1784 this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value
1785 )
1786 : 0;
1787 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1788 this.webSocketPingSetInterval = setInterval(() => {
1789 if (this.isWebSocketConnectionOpened()) {
1790 this.wsConnection.ping((): void => {
1791 /* This is intentional */
1792 });
1793 }
1794 }, webSocketPingInterval * 1000);
1795 logger.info(
1796 this.logPrefix() +
1797 ' WebSocket ping started every ' +
1798 Utils.formatDurationSeconds(webSocketPingInterval)
1799 );
1800 } else if (this.webSocketPingSetInterval) {
1801 logger.info(
1802 this.logPrefix() +
1803 ' WebSocket ping every ' +
1804 Utils.formatDurationSeconds(webSocketPingInterval) +
1805 ' already started'
1806 );
1807 } else {
1808 logger.error(
1809 `${this.logPrefix()} WebSocket ping interval set to ${
1810 webSocketPingInterval
1811 ? Utils.formatDurationSeconds(webSocketPingInterval)
1812 : webSocketPingInterval
1813 }, not starting the WebSocket ping`
1814 );
1815 }
1816 }
1817
1818 private stopWebSocketPing(): void {
1819 if (this.webSocketPingSetInterval) {
1820 clearInterval(this.webSocketPingSetInterval);
1821 }
1822 }
1823
1824 private warnDeprecatedTemplateKey(
1825 template: ChargingStationTemplate,
1826 key: string,
1827 chargingStationId: string,
1828 logMsgToAppend = ''
1829 ): void {
1830 if (!Utils.isUndefined(template[key])) {
1831 const logPrefixStr = ` ${chargingStationId} |`;
1832 logger.warn(
1833 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1834 this.templateFile
1835 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1836 );
1837 }
1838 }
1839
1840 private convertDeprecatedTemplateKey(
1841 template: ChargingStationTemplate,
1842 deprecatedKey: string,
1843 key: string
1844 ): void {
1845 if (!Utils.isUndefined(template[deprecatedKey])) {
1846 template[key] = template[deprecatedKey] as unknown;
1847 delete template[deprecatedKey];
1848 }
1849 }
1850
1851 private getConfiguredSupervisionUrl(): URL {
1852 const supervisionUrls = Utils.cloneObject<string | string[]>(
1853 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1854 );
1855 if (!Utils.isEmptyArray(supervisionUrls)) {
1856 let urlIndex = 0;
1857 switch (Configuration.getSupervisionUrlDistribution()) {
1858 case SupervisionUrlDistribution.ROUND_ROBIN:
1859 urlIndex = (this.index - 1) % supervisionUrls.length;
1860 break;
1861 case SupervisionUrlDistribution.RANDOM:
1862 // Get a random url
1863 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
1864 break;
1865 case SupervisionUrlDistribution.SEQUENTIAL:
1866 if (this.index <= supervisionUrls.length) {
1867 urlIndex = this.index - 1;
1868 } else {
1869 logger.warn(
1870 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1871 );
1872 }
1873 break;
1874 default:
1875 logger.error(
1876 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1877 SupervisionUrlDistribution.ROUND_ROBIN
1878 }`
1879 );
1880 urlIndex = (this.index - 1) % supervisionUrls.length;
1881 break;
1882 }
1883 return new URL(supervisionUrls[urlIndex]);
1884 }
1885 return new URL(supervisionUrls as string);
1886 }
1887
1888 private getHeartbeatInterval(): number | undefined {
1889 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
1890 if (HeartbeatInterval) {
1891 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1892 }
1893 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
1894 if (HeartBeatInterval) {
1895 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1896 }
1897 !this.stationInfo.autoRegister &&
1898 logger.warn(
1899 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1900 Constants.DEFAULT_HEARTBEAT_INTERVAL
1901 }`
1902 );
1903 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1904 }
1905
1906 private stopHeartbeat(): void {
1907 if (this.heartbeatSetInterval) {
1908 clearInterval(this.heartbeatSetInterval);
1909 }
1910 }
1911
1912 private openWSConnection(
1913 options: WsOptions = this.stationInfo.wsOptions,
1914 forceCloseOpened = false
1915 ): void {
1916 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
1917 if (
1918 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
1919 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
1920 ) {
1921 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1922 }
1923 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
1924 this.wsConnection.close();
1925 }
1926 let protocol: string;
1927 switch (this.getOcppVersion()) {
1928 case OCPPVersion.VERSION_16:
1929 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1930 break;
1931 default:
1932 this.handleUnsupportedVersion(this.getOcppVersion());
1933 break;
1934 }
1935 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
1936 logger.info(
1937 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()
1938 );
1939 }
1940
1941 private stopMeterValues(connectorId: number) {
1942 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1943 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1944 }
1945 }
1946
1947 private getReconnectExponentialDelay(): boolean | undefined {
1948 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
1949 ? this.stationInfo.reconnectExponentialDelay
1950 : false;
1951 }
1952
1953 private async reconnect(code: number): Promise<void> {
1954 // Stop WebSocket ping
1955 this.stopWebSocketPing();
1956 // Stop heartbeat
1957 this.stopHeartbeat();
1958 // Stop the ATG if needed
1959 if (
1960 this.stationInfo.AutomaticTransactionGenerator.enable &&
1961 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1962 this.automaticTransactionGenerator?.started
1963 ) {
1964 this.automaticTransactionGenerator.stop();
1965 }
1966 if (
1967 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
1968 this.getAutoReconnectMaxRetries() === -1
1969 ) {
1970 this.autoReconnectRetryCount++;
1971 const reconnectDelay = this.getReconnectExponentialDelay()
1972 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
1973 : this.getConnectionTimeout() * 1000;
1974 const reconnectTimeout = reconnectDelay - 100 > 0 && reconnectDelay;
1975 logger.error(
1976 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1977 reconnectDelay,
1978 2
1979 )}ms, timeout ${reconnectTimeout}ms`
1980 );
1981 await Utils.sleep(reconnectDelay);
1982 logger.error(
1983 this.logPrefix() +
1984 ' WebSocket: reconnecting try #' +
1985 this.autoReconnectRetryCount.toString()
1986 );
1987 this.openWSConnection(
1988 { ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout },
1989 true
1990 );
1991 this.wsConnectionRestarted = true;
1992 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1993 logger.error(
1994 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
1995 this.autoReconnectRetryCount
1996 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1997 );
1998 }
1999 }
2000
2001 private initializeConnectorStatus(connectorId: number): void {
2002 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
2003 this.getConnectorStatus(connectorId).idTagAuthorized = false;
2004 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
2005 this.getConnectorStatus(connectorId).transactionStarted = false;
2006 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
2007 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
2008 }
2009 }