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