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