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