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