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