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