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