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