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