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