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