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