4e11e9e27f806f800577217204b3c9fe1571d8f6
[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 parentPort.postMessage(MessageChannelUtils.buildStartedMessage(this));
523 this.starting = false;
524 } else {
525 logger.warn(`${this.logPrefix()} Charging station is already starting...`);
526 }
527 } else {
528 logger.warn(`${this.logPrefix()} Charging station is already started...`);
529 }
530 }
531
532 public async stop(reason?: StopTransactionReason): Promise<void> {
533 if (this.started === true) {
534 if (this.stopping === false) {
535 this.stopping = true;
536 await this.stopMessageSequence(reason);
537 for (const connectorId of this.connectors.keys()) {
538 if (connectorId > 0) {
539 await this.ocppRequestService.requestHandler<
540 StatusNotificationRequest,
541 StatusNotificationResponse
542 >(this, RequestCommand.STATUS_NOTIFICATION, {
543 connectorId,
544 status: ChargePointStatus.UNAVAILABLE,
545 errorCode: ChargePointErrorCode.NO_ERROR,
546 });
547 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
548 }
549 }
550 this.closeWSConnection();
551 if (this.getEnableStatistics()) {
552 this.performanceStatistics.stop();
553 }
554 this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
555 this.templateFileWatcher.close();
556 this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash);
557 this.bootNotificationResponse = null;
558 this.started = false;
559 parentPort.postMessage(MessageChannelUtils.buildStoppedMessage(this));
560 this.stopping = false;
561 } else {
562 logger.warn(`${this.logPrefix()} Charging station is already stopping...`);
563 }
564 } else {
565 logger.warn(`${this.logPrefix()} Charging station is already stopped...`);
566 }
567 }
568
569 public async reset(reason?: StopTransactionReason): Promise<void> {
570 await this.stop(reason);
571 await Utils.sleep(this.stationInfo.resetTime);
572 this.initialize();
573 this.start();
574 }
575
576 public saveOcppConfiguration(): void {
577 if (this.getOcppPersistentConfiguration()) {
578 this.saveConfiguration();
579 }
580 }
581
582 public resetConnectorStatus(connectorId: number): void {
583 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
584 this.getConnectorStatus(connectorId).idTagAuthorized = false;
585 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
586 this.getConnectorStatus(connectorId).transactionStarted = false;
587 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
588 delete this.getConnectorStatus(connectorId).authorizeIdTag;
589 delete this.getConnectorStatus(connectorId).transactionId;
590 delete this.getConnectorStatus(connectorId).transactionIdTag;
591 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
592 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
593 this.stopMeterValues(connectorId);
594 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
595 }
596
597 public hasFeatureProfile(featureProfile: SupportedFeatureProfiles): boolean {
598 return ChargingStationConfigurationUtils.getConfigurationKey(
599 this,
600 StandardParametersKey.SupportedFeatureProfiles
601 )?.value.includes(featureProfile);
602 }
603
604 public bufferMessage(message: string): void {
605 this.messageBuffer.add(message);
606 }
607
608 public openWSConnection(
609 options: WsOptions = this.stationInfo?.wsOptions ?? {},
610 params: { closeOpened?: boolean; terminateOpened?: boolean } = {
611 closeOpened: false,
612 terminateOpened: false,
613 }
614 ): void {
615 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
616 params.closeOpened = params?.closeOpened ?? false;
617 params.terminateOpened = params?.terminateOpened ?? false;
618 if (
619 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
620 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
621 ) {
622 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
623 }
624 if (params?.closeOpened) {
625 this.closeWSConnection();
626 }
627 if (params?.terminateOpened) {
628 this.terminateWSConnection();
629 }
630 let protocol: string;
631 switch (this.getOcppVersion()) {
632 case OCPPVersion.VERSION_16:
633 protocol = 'ocpp' + OCPPVersion.VERSION_16;
634 break;
635 default:
636 this.handleUnsupportedVersion(this.getOcppVersion());
637 break;
638 }
639
640 if (this.isWebSocketConnectionOpened()) {
641 logger.warn(
642 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
643 );
644 return;
645 }
646
647 logger.info(
648 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
649 );
650
651 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
652
653 // Handle WebSocket message
654 this.wsConnection.on(
655 'message',
656 this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
657 );
658 // Handle WebSocket error
659 this.wsConnection.on(
660 'error',
661 this.onError.bind(this) as (this: WebSocket, error: Error) => void
662 );
663 // Handle WebSocket close
664 this.wsConnection.on(
665 'close',
666 this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
667 );
668 // Handle WebSocket open
669 this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void);
670 // Handle WebSocket ping
671 this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void);
672 // Handle WebSocket pong
673 this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void);
674 }
675
676 public closeWSConnection(): void {
677 if (this.isWebSocketConnectionOpened()) {
678 this.wsConnection.close();
679 this.wsConnection = null;
680 }
681 }
682
683 public startAutomaticTransactionGenerator(
684 connectorIds?: number[],
685 automaticTransactionGeneratorConfiguration?: AutomaticTransactionGeneratorConfiguration
686 ): void {
687 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(
688 automaticTransactionGeneratorConfiguration ??
689 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
690 this
691 );
692 if (!Utils.isEmptyArray(connectorIds)) {
693 for (const connectorId of connectorIds) {
694 this.automaticTransactionGenerator.startConnector(connectorId);
695 }
696 } else {
697 this.automaticTransactionGenerator.start();
698 }
699 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
700 }
701
702 public stopAutomaticTransactionGenerator(connectorIds?: number[]): void {
703 if (!Utils.isEmptyArray(connectorIds)) {
704 for (const connectorId of connectorIds) {
705 this.automaticTransactionGenerator?.stopConnector(connectorId);
706 }
707 } else {
708 this.automaticTransactionGenerator?.stop();
709 }
710 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
711 }
712
713 public async stopTransactionOnConnector(
714 connectorId: number,
715 reason = StopTransactionReason.NONE
716 ): Promise<StopTransactionResponse> {
717 const transactionId = this.getConnectorStatus(connectorId).transactionId;
718 if (
719 this.getBeginEndMeterValues() &&
720 this.getOcppStrictCompliance() &&
721 !this.getOutOfOrderEndMeterValues()
722 ) {
723 // FIXME: Implement OCPP version agnostic helpers
724 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
725 this,
726 connectorId,
727 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
728 );
729 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
730 this,
731 RequestCommand.METER_VALUES,
732 {
733 connectorId,
734 transactionId,
735 meterValue: [transactionEndMeterValue],
736 }
737 );
738 }
739 return this.ocppRequestService.requestHandler<StopTransactionRequest, StopTransactionResponse>(
740 this,
741 RequestCommand.STOP_TRANSACTION,
742 {
743 transactionId,
744 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId, true),
745 reason,
746 }
747 );
748 }
749
750 private flushMessageBuffer(): void {
751 if (this.messageBuffer.size > 0) {
752 this.messageBuffer.forEach((message) => {
753 // TODO: evaluate the need to track performance
754 this.wsConnection.send(message);
755 this.messageBuffer.delete(message);
756 });
757 }
758 }
759
760 private getSupervisionUrlOcppConfiguration(): boolean {
761 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
762 }
763
764 private getSupervisionUrlOcppKey(): string {
765 return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
766 }
767
768 private getTemplateFromFile(): ChargingStationTemplate | null {
769 let template: ChargingStationTemplate = null;
770 try {
771 if (this.sharedLRUCache.hasChargingStationTemplate(this.stationInfo?.templateHash)) {
772 template = this.sharedLRUCache.getChargingStationTemplate(this.stationInfo.templateHash);
773 } else {
774 const measureId = `${FileType.ChargingStationTemplate} read`;
775 const beginId = PerformanceStatistics.beginMeasure(measureId);
776 template = JSON.parse(
777 fs.readFileSync(this.templateFile, 'utf8')
778 ) as ChargingStationTemplate;
779 PerformanceStatistics.endMeasure(measureId, beginId);
780 template.templateHash = crypto
781 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
782 .update(JSON.stringify(template))
783 .digest('hex');
784 this.sharedLRUCache.setChargingStationTemplate(template);
785 }
786 } catch (error) {
787 FileUtils.handleFileException(
788 this.logPrefix(),
789 FileType.ChargingStationTemplate,
790 this.templateFile,
791 error as NodeJS.ErrnoException
792 );
793 }
794 return template;
795 }
796
797 private getStationInfoFromTemplate(): ChargingStationInfo {
798 const stationTemplate: ChargingStationTemplate = this.getTemplateFromFile();
799 if (Utils.isNullOrUndefined(stationTemplate)) {
800 const errorMsg = 'Failed to read charging station template file';
801 logger.error(`${this.logPrefix()} ${errorMsg}`);
802 throw new BaseError(errorMsg);
803 }
804 if (Utils.isEmptyObject(stationTemplate)) {
805 const errorMsg = `Empty charging station information from template file ${this.templateFile}`;
806 logger.error(`${this.logPrefix()} ${errorMsg}`);
807 throw new BaseError(errorMsg);
808 }
809 // Deprecation template keys section
810 ChargingStationUtils.warnDeprecatedTemplateKey(
811 stationTemplate,
812 'supervisionUrl',
813 this.templateFile,
814 this.logPrefix(),
815 "Use 'supervisionUrls' instead"
816 );
817 ChargingStationUtils.convertDeprecatedTemplateKey(
818 stationTemplate,
819 'supervisionUrl',
820 'supervisionUrls'
821 );
822 const stationInfo: ChargingStationInfo =
823 ChargingStationUtils.stationTemplateToStationInfo(stationTemplate);
824 stationInfo.hashId = ChargingStationUtils.getHashId(this.index, stationTemplate);
825 stationInfo.chargingStationId = ChargingStationUtils.getChargingStationId(
826 this.index,
827 stationTemplate
828 );
829 ChargingStationUtils.createSerialNumber(stationTemplate, stationInfo);
830 if (!Utils.isEmptyArray(stationTemplate.power)) {
831 stationTemplate.power = stationTemplate.power as number[];
832 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplate.power.length);
833 stationInfo.maximumPower =
834 stationTemplate.powerUnit === PowerUnits.KILO_WATT
835 ? stationTemplate.power[powerArrayRandomIndex] * 1000
836 : stationTemplate.power[powerArrayRandomIndex];
837 } else {
838 stationTemplate.power = stationTemplate.power as number;
839 stationInfo.maximumPower =
840 stationTemplate.powerUnit === PowerUnits.KILO_WATT
841 ? stationTemplate.power * 1000
842 : stationTemplate.power;
843 }
844 stationInfo.resetTime = stationTemplate.resetTime
845 ? stationTemplate.resetTime * 1000
846 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
847 const configuredMaxConnectors =
848 ChargingStationUtils.getConfiguredNumberOfConnectors(stationTemplate);
849 ChargingStationUtils.checkConfiguredMaxConnectors(
850 configuredMaxConnectors,
851 this.templateFile,
852 this.logPrefix()
853 );
854 const templateMaxConnectors =
855 ChargingStationUtils.getTemplateMaxNumberOfConnectors(stationTemplate);
856 ChargingStationUtils.checkTemplateMaxConnectors(
857 templateMaxConnectors,
858 this.templateFile,
859 this.logPrefix()
860 );
861 if (
862 configuredMaxConnectors >
863 (stationTemplate?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
864 !stationTemplate?.randomConnectors
865 ) {
866 logger.warn(
867 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
868 this.templateFile
869 }, forcing random connector configurations affectation`
870 );
871 stationInfo.randomConnectors = true;
872 }
873 // Build connectors if needed (FIXME: should be factored out)
874 this.initializeConnectors(stationInfo, configuredMaxConnectors, templateMaxConnectors);
875 stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo);
876 ChargingStationUtils.createStationInfoHash(stationInfo);
877 return stationInfo;
878 }
879
880 private getStationInfoFromFile(): ChargingStationInfo | null {
881 let stationInfo: ChargingStationInfo = null;
882 this.getStationInfoPersistentConfiguration() &&
883 (stationInfo = this.getConfigurationFromFile()?.stationInfo ?? null);
884 stationInfo && ChargingStationUtils.createStationInfoHash(stationInfo);
885 return stationInfo;
886 }
887
888 private getStationInfo(): ChargingStationInfo {
889 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
890 const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
891 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
892 if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
893 if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) {
894 return this.stationInfo;
895 }
896 return stationInfoFromFile;
897 }
898 stationInfoFromFile &&
899 ChargingStationUtils.propagateSerialNumber(
900 this.getTemplateFromFile(),
901 stationInfoFromFile,
902 stationInfoFromTemplate
903 );
904 return stationInfoFromTemplate;
905 }
906
907 private saveStationInfo(): void {
908 if (this.getStationInfoPersistentConfiguration()) {
909 this.saveConfiguration();
910 }
911 }
912
913 private getOcppVersion(): OCPPVersion {
914 return this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
915 }
916
917 private getOcppPersistentConfiguration(): boolean {
918 return this.stationInfo?.ocppPersistentConfiguration ?? true;
919 }
920
921 private getStationInfoPersistentConfiguration(): boolean {
922 return this.stationInfo?.stationInfoPersistentConfiguration ?? true;
923 }
924
925 private handleUnsupportedVersion(version: OCPPVersion) {
926 const errMsg = `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
927 logger.error(`${this.logPrefix()} ${errMsg}`);
928 throw new BaseError(errMsg);
929 }
930
931 private initialize(): void {
932 this.configurationFile = path.join(
933 path.dirname(this.templateFile.replace('station-templates', 'configurations')),
934 ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile()) + '.json'
935 );
936 this.stationInfo = this.getStationInfo();
937 this.saveStationInfo();
938 logger.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
939 // Avoid duplication of connectors related information in RAM
940 this.stationInfo?.Connectors && delete this.stationInfo.Connectors;
941 this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl();
942 if (this.getEnableStatistics()) {
943 this.performanceStatistics = PerformanceStatistics.getInstance(
944 this.stationInfo.hashId,
945 this.stationInfo.chargingStationId,
946 this.configuredSupervisionUrl
947 );
948 }
949 this.bootNotificationRequest = ChargingStationUtils.createBootNotificationRequest(
950 this.stationInfo
951 );
952 this.powerDivider = this.getPowerDivider();
953 // OCPP configuration
954 this.ocppConfiguration = this.getOcppConfiguration();
955 this.initializeOcppConfiguration();
956 switch (this.getOcppVersion()) {
957 case OCPPVersion.VERSION_16:
958 this.ocppIncomingRequestService =
959 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>();
960 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
961 OCPP16ResponseService.getInstance<OCPP16ResponseService>()
962 );
963 break;
964 default:
965 this.handleUnsupportedVersion(this.getOcppVersion());
966 break;
967 }
968 if (this.stationInfo?.autoRegister) {
969 this.bootNotificationResponse = {
970 currentTime: new Date().toISOString(),
971 interval: this.getHeartbeatInterval() / 1000,
972 status: RegistrationStatus.ACCEPTED,
973 };
974 }
975 }
976
977 private initializeOcppConfiguration(): void {
978 if (
979 !ChargingStationConfigurationUtils.getConfigurationKey(
980 this,
981 StandardParametersKey.HeartbeatInterval
982 )
983 ) {
984 ChargingStationConfigurationUtils.addConfigurationKey(
985 this,
986 StandardParametersKey.HeartbeatInterval,
987 '0'
988 );
989 }
990 if (
991 !ChargingStationConfigurationUtils.getConfigurationKey(
992 this,
993 StandardParametersKey.HeartBeatInterval
994 )
995 ) {
996 ChargingStationConfigurationUtils.addConfigurationKey(
997 this,
998 StandardParametersKey.HeartBeatInterval,
999 '0',
1000 { visible: false }
1001 );
1002 }
1003 if (
1004 this.getSupervisionUrlOcppConfiguration() &&
1005 !ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1006 ) {
1007 ChargingStationConfigurationUtils.addConfigurationKey(
1008 this,
1009 this.getSupervisionUrlOcppKey(),
1010 this.configuredSupervisionUrl.href,
1011 { reboot: true }
1012 );
1013 } else if (
1014 !this.getSupervisionUrlOcppConfiguration() &&
1015 ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1016 ) {
1017 ChargingStationConfigurationUtils.deleteConfigurationKey(
1018 this,
1019 this.getSupervisionUrlOcppKey(),
1020 { save: false }
1021 );
1022 }
1023 if (
1024 this.stationInfo.amperageLimitationOcppKey &&
1025 !ChargingStationConfigurationUtils.getConfigurationKey(
1026 this,
1027 this.stationInfo.amperageLimitationOcppKey
1028 )
1029 ) {
1030 ChargingStationConfigurationUtils.addConfigurationKey(
1031 this,
1032 this.stationInfo.amperageLimitationOcppKey,
1033 (
1034 this.stationInfo.maximumAmperage *
1035 ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
1036 ).toString()
1037 );
1038 }
1039 if (
1040 !ChargingStationConfigurationUtils.getConfigurationKey(
1041 this,
1042 StandardParametersKey.SupportedFeatureProfiles
1043 )
1044 ) {
1045 ChargingStationConfigurationUtils.addConfigurationKey(
1046 this,
1047 StandardParametersKey.SupportedFeatureProfiles,
1048 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1049 );
1050 }
1051 ChargingStationConfigurationUtils.addConfigurationKey(
1052 this,
1053 StandardParametersKey.NumberOfConnectors,
1054 this.getNumberOfConnectors().toString(),
1055 { readonly: true },
1056 { overwrite: true }
1057 );
1058 if (
1059 !ChargingStationConfigurationUtils.getConfigurationKey(
1060 this,
1061 StandardParametersKey.MeterValuesSampledData
1062 )
1063 ) {
1064 ChargingStationConfigurationUtils.addConfigurationKey(
1065 this,
1066 StandardParametersKey.MeterValuesSampledData,
1067 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1068 );
1069 }
1070 if (
1071 !ChargingStationConfigurationUtils.getConfigurationKey(
1072 this,
1073 StandardParametersKey.ConnectorPhaseRotation
1074 )
1075 ) {
1076 const connectorPhaseRotation = [];
1077 for (const connectorId of this.connectors.keys()) {
1078 // AC/DC
1079 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1080 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1081 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1082 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1083 // AC
1084 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1085 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1086 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1087 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1088 }
1089 }
1090 ChargingStationConfigurationUtils.addConfigurationKey(
1091 this,
1092 StandardParametersKey.ConnectorPhaseRotation,
1093 connectorPhaseRotation.toString()
1094 );
1095 }
1096 if (
1097 !ChargingStationConfigurationUtils.getConfigurationKey(
1098 this,
1099 StandardParametersKey.AuthorizeRemoteTxRequests
1100 )
1101 ) {
1102 ChargingStationConfigurationUtils.addConfigurationKey(
1103 this,
1104 StandardParametersKey.AuthorizeRemoteTxRequests,
1105 'true'
1106 );
1107 }
1108 if (
1109 !ChargingStationConfigurationUtils.getConfigurationKey(
1110 this,
1111 StandardParametersKey.LocalAuthListEnabled
1112 ) &&
1113 ChargingStationConfigurationUtils.getConfigurationKey(
1114 this,
1115 StandardParametersKey.SupportedFeatureProfiles
1116 )?.value.includes(SupportedFeatureProfiles.LocalAuthListManagement)
1117 ) {
1118 ChargingStationConfigurationUtils.addConfigurationKey(
1119 this,
1120 StandardParametersKey.LocalAuthListEnabled,
1121 'false'
1122 );
1123 }
1124 if (
1125 !ChargingStationConfigurationUtils.getConfigurationKey(
1126 this,
1127 StandardParametersKey.ConnectionTimeOut
1128 )
1129 ) {
1130 ChargingStationConfigurationUtils.addConfigurationKey(
1131 this,
1132 StandardParametersKey.ConnectionTimeOut,
1133 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1134 );
1135 }
1136 this.saveOcppConfiguration();
1137 }
1138
1139 private initializeConnectors(
1140 stationInfo: ChargingStationInfo,
1141 configuredMaxConnectors: number,
1142 templateMaxConnectors: number
1143 ): void {
1144 if (!stationInfo?.Connectors && this.connectors.size === 0) {
1145 const logMsg = `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1146 logger.error(`${this.logPrefix()} ${logMsg}`);
1147 throw new BaseError(logMsg);
1148 }
1149 if (!stationInfo?.Connectors[0]) {
1150 logger.warn(
1151 `${this.logPrefix()} Charging station information from template ${
1152 this.templateFile
1153 } with no connector Id 0 configuration`
1154 );
1155 }
1156 if (stationInfo?.Connectors) {
1157 const connectorsConfigHash = crypto
1158 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1159 .update(JSON.stringify(stationInfo?.Connectors) + configuredMaxConnectors.toString())
1160 .digest('hex');
1161 const connectorsConfigChanged =
1162 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
1163 if (this.connectors?.size === 0 || connectorsConfigChanged) {
1164 connectorsConfigChanged && this.connectors.clear();
1165 this.connectorsConfigurationHash = connectorsConfigHash;
1166 // Add connector Id 0
1167 let lastConnector = '0';
1168 for (lastConnector in stationInfo?.Connectors) {
1169 const lastConnectorId = Utils.convertToInt(lastConnector);
1170 if (
1171 lastConnectorId === 0 &&
1172 this.getUseConnectorId0(stationInfo) === true &&
1173 stationInfo?.Connectors[lastConnector]
1174 ) {
1175 this.connectors.set(
1176 lastConnectorId,
1177 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[lastConnector])
1178 );
1179 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
1180 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
1181 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
1182 }
1183 }
1184 }
1185 // Generate all connectors
1186 if ((stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
1187 for (let index = 1; index <= configuredMaxConnectors; index++) {
1188 const randConnectorId = stationInfo?.randomConnectors
1189 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
1190 : index;
1191 this.connectors.set(
1192 index,
1193 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[randConnectorId])
1194 );
1195 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
1196 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
1197 this.getConnectorStatus(index).chargingProfiles = [];
1198 }
1199 }
1200 }
1201 }
1202 } else {
1203 logger.warn(
1204 `${this.logPrefix()} Charging station information from template ${
1205 this.templateFile
1206 } with no connectors configuration defined, using already defined connectors`
1207 );
1208 }
1209 // Initialize transaction attributes on connectors
1210 for (const connectorId of this.connectors.keys()) {
1211 if (
1212 connectorId > 0 &&
1213 (this.getConnectorStatus(connectorId).transactionStarted === undefined ||
1214 this.getConnectorStatus(connectorId).transactionStarted === false)
1215 ) {
1216 this.initializeConnectorStatus(connectorId);
1217 }
1218 }
1219 }
1220
1221 private getConfigurationFromFile(): ChargingStationConfiguration | null {
1222 let configuration: ChargingStationConfiguration = null;
1223 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
1224 try {
1225 if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) {
1226 configuration = this.sharedLRUCache.getChargingStationConfiguration(
1227 this.configurationFileHash
1228 );
1229 } else {
1230 const measureId = `${FileType.ChargingStationConfiguration} read`;
1231 const beginId = PerformanceStatistics.beginMeasure(measureId);
1232 configuration = JSON.parse(
1233 fs.readFileSync(this.configurationFile, 'utf8')
1234 ) as ChargingStationConfiguration;
1235 PerformanceStatistics.endMeasure(measureId, beginId);
1236 this.configurationFileHash = configuration.configurationHash;
1237 this.sharedLRUCache.setChargingStationConfiguration(configuration);
1238 }
1239 } catch (error) {
1240 FileUtils.handleFileException(
1241 this.logPrefix(),
1242 FileType.ChargingStationConfiguration,
1243 this.configurationFile,
1244 error as NodeJS.ErrnoException
1245 );
1246 }
1247 }
1248 return configuration;
1249 }
1250
1251 private saveConfiguration(): void {
1252 if (this.configurationFile) {
1253 try {
1254 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1255 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
1256 }
1257 const configurationData: ChargingStationConfiguration =
1258 this.getConfigurationFromFile() ?? {};
1259 this.ocppConfiguration?.configurationKey &&
1260 (configurationData.configurationKey = this.ocppConfiguration.configurationKey);
1261 this.stationInfo && (configurationData.stationInfo = this.stationInfo);
1262 delete configurationData.configurationHash;
1263 const configurationHash = crypto
1264 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1265 .update(JSON.stringify(configurationData))
1266 .digest('hex');
1267 if (this.configurationFileHash !== configurationHash) {
1268 configurationData.configurationHash = configurationHash;
1269 const measureId = `${FileType.ChargingStationConfiguration} write`;
1270 const beginId = PerformanceStatistics.beginMeasure(measureId);
1271 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1272 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1273 fs.closeSync(fileDescriptor);
1274 PerformanceStatistics.endMeasure(measureId, beginId);
1275 this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
1276 this.configurationFileHash = configurationHash;
1277 this.sharedLRUCache.setChargingStationConfiguration(configurationData);
1278 } else {
1279 logger.debug(
1280 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1281 this.configurationFile
1282 }`
1283 );
1284 }
1285 } catch (error) {
1286 FileUtils.handleFileException(
1287 this.logPrefix(),
1288 FileType.ChargingStationConfiguration,
1289 this.configurationFile,
1290 error as NodeJS.ErrnoException
1291 );
1292 }
1293 } else {
1294 logger.error(
1295 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1296 );
1297 }
1298 }
1299
1300 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | null {
1301 return this.getTemplateFromFile()?.Configuration ?? null;
1302 }
1303
1304 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
1305 let configuration: ChargingStationConfiguration = null;
1306 if (this.getOcppPersistentConfiguration()) {
1307 const configurationFromFile = this.getConfigurationFromFile();
1308 configuration = configurationFromFile?.configurationKey && configurationFromFile;
1309 }
1310 configuration && delete configuration.stationInfo;
1311 return configuration;
1312 }
1313
1314 private getOcppConfiguration(): ChargingStationOcppConfiguration | null {
1315 let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
1316 if (!ocppConfiguration) {
1317 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1318 }
1319 return ocppConfiguration;
1320 }
1321
1322 private async onOpen(): Promise<void> {
1323 if (this.isWebSocketConnectionOpened()) {
1324 logger.info(
1325 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1326 );
1327 if (!this.isRegistered()) {
1328 // Send BootNotification
1329 let registrationRetryCount = 0;
1330 do {
1331 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
1332 BootNotificationRequest,
1333 BootNotificationResponse
1334 >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, {
1335 skipBufferingOnError: true,
1336 });
1337 if (!this.isRegistered()) {
1338 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1339 await Utils.sleep(
1340 this.bootNotificationResponse?.interval
1341 ? this.bootNotificationResponse.interval * 1000
1342 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1343 );
1344 }
1345 } while (
1346 !this.isRegistered() &&
1347 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1348 this.getRegistrationMaxRetries() === -1)
1349 );
1350 }
1351 if (this.isRegistered()) {
1352 if (this.isInAcceptedState()) {
1353 await this.startMessageSequence();
1354 }
1355 } else {
1356 logger.error(
1357 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1358 );
1359 }
1360 this.wsConnectionRestarted = false;
1361 this.autoReconnectRetryCount = 0;
1362 this.started = true;
1363 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
1364 } else {
1365 logger.warn(
1366 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1367 );
1368 }
1369 }
1370
1371 private async onClose(code: number, reason: string): Promise<void> {
1372 switch (code) {
1373 // Normal close
1374 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
1375 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
1376 logger.info(
1377 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1378 code
1379 )}' and reason '${reason}'`
1380 );
1381 this.autoReconnectRetryCount = 0;
1382 break;
1383 // Abnormal close
1384 default:
1385 logger.error(
1386 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1387 code
1388 )}' and reason '${reason}'`
1389 );
1390 await this.reconnect();
1391 break;
1392 }
1393 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
1394 }
1395
1396 private async onMessage(data: Data): Promise<void> {
1397 let messageType: number;
1398 let messageId: string;
1399 let commandName: IncomingRequestCommand;
1400 let commandPayload: JsonType;
1401 let errorType: ErrorType;
1402 let errorMessage: string;
1403 let errorDetails: JsonType;
1404 let responseCallback: (payload: JsonType, requestPayload: JsonType) => void;
1405 let errorCallback: (error: OCPPError, requestStatistic?: boolean) => void;
1406 let requestCommandName: RequestCommand | IncomingRequestCommand;
1407 let requestPayload: JsonType;
1408 let cachedRequest: CachedRequest;
1409 let errMsg: string;
1410 try {
1411 const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
1412 if (Array.isArray(request) === true) {
1413 [messageType, messageId] = request;
1414 // Check the type of message
1415 switch (messageType) {
1416 // Incoming Message
1417 case MessageType.CALL_MESSAGE:
1418 [, , commandName, commandPayload] = request as IncomingRequest;
1419 if (this.getEnableStatistics() === true) {
1420 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1421 }
1422 logger.debug(
1423 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1424 request
1425 )}`
1426 );
1427 // Process the message
1428 await this.ocppIncomingRequestService.incomingRequestHandler(
1429 this,
1430 messageId,
1431 commandName,
1432 commandPayload
1433 );
1434 break;
1435 // Outcome Message
1436 case MessageType.CALL_RESULT_MESSAGE:
1437 [, , commandPayload] = request as Response;
1438 if (this.requests.has(messageId) === false) {
1439 // Error
1440 throw new OCPPError(
1441 ErrorType.INTERNAL_ERROR,
1442 `Response for unknown message id ${messageId}`,
1443 null,
1444 commandPayload
1445 );
1446 }
1447 // Respond
1448 cachedRequest = this.requests.get(messageId);
1449 if (Array.isArray(cachedRequest) === true) {
1450 [responseCallback, errorCallback, requestCommandName, requestPayload] = cachedRequest;
1451 } else {
1452 throw new OCPPError(
1453 ErrorType.PROTOCOL_ERROR,
1454 `Cached request for message id ${messageId} response is not an array`,
1455 null,
1456 cachedRequest as unknown as JsonType
1457 );
1458 }
1459 logger.debug(
1460 `${this.logPrefix()} << Command '${
1461 requestCommandName ?? Constants.UNKNOWN_COMMAND
1462 }' received response payload: ${JSON.stringify(request)}`
1463 );
1464 responseCallback(commandPayload, requestPayload);
1465 break;
1466 // Error Message
1467 case MessageType.CALL_ERROR_MESSAGE:
1468 [, , errorType, errorMessage, errorDetails] = request as ErrorResponse;
1469 if (this.requests.has(messageId) === false) {
1470 // Error
1471 throw new OCPPError(
1472 ErrorType.INTERNAL_ERROR,
1473 `Error response for unknown message id ${messageId}`,
1474 null,
1475 { errorType, errorMessage, errorDetails }
1476 );
1477 }
1478 cachedRequest = this.requests.get(messageId);
1479 if (Array.isArray(cachedRequest) === true) {
1480 [, errorCallback, requestCommandName] = cachedRequest;
1481 } else {
1482 throw new OCPPError(
1483 ErrorType.PROTOCOL_ERROR,
1484 `Cached request for message id ${messageId} error response is not an array`,
1485 null,
1486 cachedRequest as unknown as JsonType
1487 );
1488 }
1489 logger.debug(
1490 `${this.logPrefix()} << Command '${
1491 requestCommandName ?? Constants.UNKNOWN_COMMAND
1492 }' received error payload: ${JSON.stringify(request)}`
1493 );
1494 errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails));
1495 break;
1496 // Error
1497 default:
1498 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1499 errMsg = `Wrong message type ${messageType}`;
1500 logger.error(`${this.logPrefix()} ${errMsg}`);
1501 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1502 }
1503 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
1504 } else {
1505 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not an array', null, {
1506 request,
1507 });
1508 }
1509 } catch (error) {
1510 // Log
1511 logger.error(
1512 `${this.logPrefix()} Incoming OCPP command '${
1513 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1514 }' message '${data.toString()}'${
1515 messageType !== MessageType.CALL_MESSAGE
1516 ? ` matching cached request '${JSON.stringify(this.requests.get(messageId))}'`
1517 : ''
1518 } processing error:`,
1519 error
1520 );
1521 if (error instanceof OCPPError === false) {
1522 logger.warn(
1523 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1524 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1525 }' message '${data.toString()}' handling is not an OCPPError:`,
1526 error
1527 );
1528 }
1529 switch (messageType) {
1530 case MessageType.CALL_MESSAGE:
1531 // Send error
1532 await this.ocppRequestService.sendError(
1533 this,
1534 messageId,
1535 error as OCPPError,
1536 commandName ?? requestCommandName ?? null
1537 );
1538 break;
1539 case MessageType.CALL_RESULT_MESSAGE:
1540 case MessageType.CALL_ERROR_MESSAGE:
1541 if (errorCallback) {
1542 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1543 errorCallback(error as OCPPError, false);
1544 } else {
1545 // Remove the request from the cache in case of error at response handling
1546 this.requests.delete(messageId);
1547 }
1548 break;
1549 }
1550 }
1551 }
1552
1553 private onPing(): void {
1554 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1555 }
1556
1557 private onPong(): void {
1558 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1559 }
1560
1561 private onError(error: WSError): void {
1562 this.closeWSConnection();
1563 logger.error(this.logPrefix() + ' WebSocket error:', error);
1564 }
1565
1566 private getEnergyActiveImportRegister(
1567 connectorStatus: ConnectorStatus,
1568 meterStop = false
1569 ): number {
1570 if (this.getMeteringPerTransaction() === true) {
1571 return (
1572 (meterStop === true
1573 ? Math.round(connectorStatus?.transactionEnergyActiveImportRegisterValue)
1574 : connectorStatus?.transactionEnergyActiveImportRegisterValue) ?? 0
1575 );
1576 }
1577 return (
1578 (meterStop === true
1579 ? Math.round(connectorStatus?.energyActiveImportRegisterValue)
1580 : connectorStatus?.energyActiveImportRegisterValue) ?? 0
1581 );
1582 }
1583
1584 private getUseConnectorId0(stationInfo?: ChargingStationInfo): boolean {
1585 const localStationInfo = stationInfo ?? this.stationInfo;
1586 return !Utils.isUndefined(localStationInfo.useConnectorId0)
1587 ? localStationInfo.useConnectorId0
1588 : true;
1589 }
1590
1591 private getNumberOfRunningTransactions(): number {
1592 let trxCount = 0;
1593 for (const connectorId of this.connectors.keys()) {
1594 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) {
1595 trxCount++;
1596 }
1597 }
1598 return trxCount;
1599 }
1600
1601 private async stopRunningTransactions(reason = StopTransactionReason.NONE): Promise<void> {
1602 for (const connectorId of this.connectors.keys()) {
1603 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) {
1604 await this.stopTransactionOnConnector(connectorId, reason);
1605 }
1606 }
1607 }
1608
1609 // 0 for disabling
1610 private getConnectionTimeout(): number {
1611 if (
1612 ChargingStationConfigurationUtils.getConfigurationKey(
1613 this,
1614 StandardParametersKey.ConnectionTimeOut
1615 )
1616 ) {
1617 return (
1618 parseInt(
1619 ChargingStationConfigurationUtils.getConfigurationKey(
1620 this,
1621 StandardParametersKey.ConnectionTimeOut
1622 ).value
1623 ) ?? Constants.DEFAULT_CONNECTION_TIMEOUT
1624 );
1625 }
1626 return Constants.DEFAULT_CONNECTION_TIMEOUT;
1627 }
1628
1629 // -1 for unlimited, 0 for disabling
1630 private getAutoReconnectMaxRetries(): number {
1631 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1632 return this.stationInfo.autoReconnectMaxRetries;
1633 }
1634 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1635 return Configuration.getAutoReconnectMaxRetries();
1636 }
1637 return -1;
1638 }
1639
1640 // 0 for disabling
1641 private getRegistrationMaxRetries(): number {
1642 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1643 return this.stationInfo.registrationMaxRetries;
1644 }
1645 return -1;
1646 }
1647
1648 private getPowerDivider(): number {
1649 let powerDivider = this.getNumberOfConnectors();
1650 if (this.stationInfo?.powerSharedByConnectors) {
1651 powerDivider = this.getNumberOfRunningTransactions();
1652 }
1653 return powerDivider;
1654 }
1655
1656 private getMaximumPower(stationInfo?: ChargingStationInfo): number {
1657 const localStationInfo = stationInfo ?? this.stationInfo;
1658 return (localStationInfo['maxPower'] as number) ?? localStationInfo.maximumPower;
1659 }
1660
1661 private getMaximumAmperage(stationInfo: ChargingStationInfo): number | undefined {
1662 const maximumPower = this.getMaximumPower(stationInfo);
1663 switch (this.getCurrentOutType(stationInfo)) {
1664 case CurrentType.AC:
1665 return ACElectricUtils.amperagePerPhaseFromPower(
1666 this.getNumberOfPhases(stationInfo),
1667 maximumPower / this.getNumberOfConnectors(),
1668 this.getVoltageOut(stationInfo)
1669 );
1670 case CurrentType.DC:
1671 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo));
1672 }
1673 }
1674
1675 private getAmperageLimitation(): number | undefined {
1676 if (
1677 this.stationInfo.amperageLimitationOcppKey &&
1678 ChargingStationConfigurationUtils.getConfigurationKey(
1679 this,
1680 this.stationInfo.amperageLimitationOcppKey
1681 )
1682 ) {
1683 return (
1684 Utils.convertToInt(
1685 ChargingStationConfigurationUtils.getConfigurationKey(
1686 this,
1687 this.stationInfo.amperageLimitationOcppKey
1688 ).value
1689 ) / ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
1690 );
1691 }
1692 }
1693
1694 private getChargingProfilePowerLimit(connectorId: number): number | undefined {
1695 let limit: number, matchingChargingProfile: ChargingProfile;
1696 let chargingProfiles: ChargingProfile[] = [];
1697 // Get charging profiles for connector and sort by stack level
1698 chargingProfiles = this.getConnectorStatus(connectorId).chargingProfiles.sort(
1699 (a, b) => b.stackLevel - a.stackLevel
1700 );
1701 // Get profiles on connector 0
1702 if (this.getConnectorStatus(0).chargingProfiles) {
1703 chargingProfiles.push(
1704 ...this.getConnectorStatus(0).chargingProfiles.sort((a, b) => b.stackLevel - a.stackLevel)
1705 );
1706 }
1707 if (!Utils.isEmptyArray(chargingProfiles)) {
1708 const result = ChargingStationUtils.getLimitFromChargingProfiles(
1709 chargingProfiles,
1710 this.logPrefix()
1711 );
1712 if (!Utils.isNullOrUndefined(result)) {
1713 limit = result.limit;
1714 matchingChargingProfile = result.matchingChargingProfile;
1715 switch (this.getCurrentOutType()) {
1716 case CurrentType.AC:
1717 limit =
1718 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
1719 ChargingRateUnitType.WATT
1720 ? limit
1721 : ACElectricUtils.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit);
1722 break;
1723 case CurrentType.DC:
1724 limit =
1725 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
1726 ChargingRateUnitType.WATT
1727 ? limit
1728 : DCElectricUtils.power(this.getVoltageOut(), limit);
1729 }
1730 const connectorMaximumPower = this.getMaximumPower() / this.powerDivider;
1731 if (limit > connectorMaximumPower) {
1732 logger.error(
1733 `${this.logPrefix()} Charging profile id ${
1734 matchingChargingProfile.chargingProfileId
1735 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
1736 this.getConnectorStatus(connectorId).chargingProfiles
1737 );
1738 limit = connectorMaximumPower;
1739 }
1740 }
1741 }
1742 return limit;
1743 }
1744
1745 private async startMessageSequence(): Promise<void> {
1746 if (this.stationInfo?.autoRegister) {
1747 await this.ocppRequestService.requestHandler<
1748 BootNotificationRequest,
1749 BootNotificationResponse
1750 >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, {
1751 skipBufferingOnError: true,
1752 });
1753 }
1754 // Start WebSocket ping
1755 this.startWebSocketPing();
1756 // Start heartbeat
1757 this.startHeartbeat();
1758 // Initialize connectors status
1759 for (const connectorId of this.connectors.keys()) {
1760 if (connectorId === 0) {
1761 continue;
1762 } else if (
1763 this.started === true &&
1764 !this.getConnectorStatus(connectorId)?.status &&
1765 this.getConnectorStatus(connectorId)?.bootStatus
1766 ) {
1767 // Send status in template at startup
1768 await this.ocppRequestService.requestHandler<
1769 StatusNotificationRequest,
1770 StatusNotificationResponse
1771 >(this, RequestCommand.STATUS_NOTIFICATION, {
1772 connectorId,
1773 status: this.getConnectorStatus(connectorId).bootStatus,
1774 errorCode: ChargePointErrorCode.NO_ERROR,
1775 });
1776 this.getConnectorStatus(connectorId).status =
1777 this.getConnectorStatus(connectorId).bootStatus;
1778 } else if (
1779 this.started === false &&
1780 this.getConnectorStatus(connectorId)?.status &&
1781 this.getConnectorStatus(connectorId)?.bootStatus
1782 ) {
1783 // Send status in template after reset
1784 await this.ocppRequestService.requestHandler<
1785 StatusNotificationRequest,
1786 StatusNotificationResponse
1787 >(this, RequestCommand.STATUS_NOTIFICATION, {
1788 connectorId,
1789 status: this.getConnectorStatus(connectorId).bootStatus,
1790 errorCode: ChargePointErrorCode.NO_ERROR,
1791 });
1792 this.getConnectorStatus(connectorId).status =
1793 this.getConnectorStatus(connectorId).bootStatus;
1794 } else if (this.started === true && this.getConnectorStatus(connectorId)?.status) {
1795 // Send previous status at template reload
1796 await this.ocppRequestService.requestHandler<
1797 StatusNotificationRequest,
1798 StatusNotificationResponse
1799 >(this, RequestCommand.STATUS_NOTIFICATION, {
1800 connectorId,
1801 status: this.getConnectorStatus(connectorId).status,
1802 errorCode: ChargePointErrorCode.NO_ERROR,
1803 });
1804 } else {
1805 // Send default status
1806 await this.ocppRequestService.requestHandler<
1807 StatusNotificationRequest,
1808 StatusNotificationResponse
1809 >(this, RequestCommand.STATUS_NOTIFICATION, {
1810 connectorId,
1811 status: ChargePointStatus.AVAILABLE,
1812 errorCode: ChargePointErrorCode.NO_ERROR,
1813 });
1814 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
1815 }
1816 }
1817 // Start the ATG
1818 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable === true) {
1819 this.startAutomaticTransactionGenerator();
1820 }
1821 this.wsConnectionRestarted === true && this.flushMessageBuffer();
1822 }
1823
1824 private async stopMessageSequence(
1825 reason: StopTransactionReason = StopTransactionReason.NONE
1826 ): Promise<void> {
1827 // Stop WebSocket ping
1828 this.stopWebSocketPing();
1829 // Stop heartbeat
1830 this.stopHeartbeat();
1831 // Stop ongoing transactions
1832 if (this.automaticTransactionGenerator?.started === true) {
1833 this.stopAutomaticTransactionGenerator();
1834 } else {
1835 await this.stopRunningTransactions(reason);
1836 }
1837 }
1838
1839 private startWebSocketPing(): void {
1840 const webSocketPingInterval: number = ChargingStationConfigurationUtils.getConfigurationKey(
1841 this,
1842 StandardParametersKey.WebSocketPingInterval
1843 )
1844 ? Utils.convertToInt(
1845 ChargingStationConfigurationUtils.getConfigurationKey(
1846 this,
1847 StandardParametersKey.WebSocketPingInterval
1848 ).value
1849 )
1850 : 0;
1851 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1852 this.webSocketPingSetInterval = setInterval(() => {
1853 if (this.isWebSocketConnectionOpened()) {
1854 this.wsConnection.ping((): void => {
1855 /* This is intentional */
1856 });
1857 }
1858 }, webSocketPingInterval * 1000);
1859 logger.info(
1860 this.logPrefix() +
1861 ' WebSocket ping started every ' +
1862 Utils.formatDurationSeconds(webSocketPingInterval)
1863 );
1864 } else if (this.webSocketPingSetInterval) {
1865 logger.info(
1866 this.logPrefix() +
1867 ' WebSocket ping every ' +
1868 Utils.formatDurationSeconds(webSocketPingInterval) +
1869 ' already started'
1870 );
1871 } else {
1872 logger.error(
1873 `${this.logPrefix()} WebSocket ping interval set to ${
1874 webSocketPingInterval
1875 ? Utils.formatDurationSeconds(webSocketPingInterval)
1876 : webSocketPingInterval
1877 }, not starting the WebSocket ping`
1878 );
1879 }
1880 }
1881
1882 private stopWebSocketPing(): void {
1883 if (this.webSocketPingSetInterval) {
1884 clearInterval(this.webSocketPingSetInterval);
1885 }
1886 }
1887
1888 private getConfiguredSupervisionUrl(): URL {
1889 const supervisionUrls = Utils.cloneObject<string | string[]>(
1890 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1891 );
1892 if (!Utils.isEmptyArray(supervisionUrls)) {
1893 switch (Configuration.getSupervisionUrlDistribution()) {
1894 case SupervisionUrlDistribution.ROUND_ROBIN:
1895 // FIXME
1896 this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length;
1897 break;
1898 case SupervisionUrlDistribution.RANDOM:
1899 this.configuredSupervisionUrlIndex = Math.floor(
1900 Utils.secureRandom() * supervisionUrls.length
1901 );
1902 break;
1903 case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY:
1904 this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length;
1905 break;
1906 default:
1907 logger.error(
1908 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1909 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1910 }`
1911 );
1912 this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length;
1913 break;
1914 }
1915 return new URL(supervisionUrls[this.configuredSupervisionUrlIndex]);
1916 }
1917 return new URL(supervisionUrls as string);
1918 }
1919
1920 private getHeartbeatInterval(): number {
1921 const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1922 this,
1923 StandardParametersKey.HeartbeatInterval
1924 );
1925 if (HeartbeatInterval) {
1926 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1927 }
1928 const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1929 this,
1930 StandardParametersKey.HeartBeatInterval
1931 );
1932 if (HeartBeatInterval) {
1933 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1934 }
1935 !this.stationInfo?.autoRegister &&
1936 logger.warn(
1937 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1938 Constants.DEFAULT_HEARTBEAT_INTERVAL
1939 }`
1940 );
1941 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1942 }
1943
1944 private stopHeartbeat(): void {
1945 if (this.heartbeatSetInterval) {
1946 clearInterval(this.heartbeatSetInterval);
1947 }
1948 }
1949
1950 private terminateWSConnection(): void {
1951 if (this.isWebSocketConnectionOpened()) {
1952 this.wsConnection.terminate();
1953 this.wsConnection = null;
1954 }
1955 }
1956
1957 private stopMeterValues(connectorId: number) {
1958 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1959 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1960 }
1961 }
1962
1963 private getReconnectExponentialDelay(): boolean {
1964 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
1965 ? this.stationInfo.reconnectExponentialDelay
1966 : false;
1967 }
1968
1969 private async reconnect(): Promise<void> {
1970 // Stop WebSocket ping
1971 this.stopWebSocketPing();
1972 // Stop heartbeat
1973 this.stopHeartbeat();
1974 // Stop the ATG if needed
1975 if (this.automaticTransactionGenerator?.configuration?.stopOnConnectionFailure === true) {
1976 this.stopAutomaticTransactionGenerator();
1977 }
1978 if (
1979 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
1980 this.getAutoReconnectMaxRetries() === -1
1981 ) {
1982 this.autoReconnectRetryCount++;
1983 const reconnectDelay = this.getReconnectExponentialDelay()
1984 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
1985 : this.getConnectionTimeout() * 1000;
1986 const reconnectDelayWithdraw = 1000;
1987 const reconnectTimeout =
1988 reconnectDelay && reconnectDelay - reconnectDelayWithdraw > 0
1989 ? reconnectDelay - reconnectDelayWithdraw
1990 : 0;
1991 logger.error(
1992 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1993 reconnectDelay,
1994 2
1995 )}ms, timeout ${reconnectTimeout}ms`
1996 );
1997 await Utils.sleep(reconnectDelay);
1998 logger.error(
1999 this.logPrefix() +
2000 ' WebSocket: reconnecting try #' +
2001 this.autoReconnectRetryCount.toString()
2002 );
2003 this.openWSConnection(
2004 { ...(this.stationInfo?.wsOptions ?? {}), handshakeTimeout: reconnectTimeout },
2005 { closeOpened: true }
2006 );
2007 this.wsConnectionRestarted = true;
2008 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2009 logger.error(
2010 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2011 this.autoReconnectRetryCount
2012 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2013 );
2014 }
2015 }
2016
2017 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration | null {
2018 return this.getTemplateFromFile()?.AutomaticTransactionGenerator ?? null;
2019 }
2020
2021 private initializeConnectorStatus(connectorId: number): void {
2022 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
2023 this.getConnectorStatus(connectorId).idTagAuthorized = false;
2024 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
2025 this.getConnectorStatus(connectorId).transactionStarted = false;
2026 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
2027 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
2028 }
2029 }