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