1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { createHash
} from
'node:crypto';
13 import { dirname
, join
} from
'node:path';
14 import { URL
} from
'node:url';
15 import { parentPort
} from
'node:worker_threads';
17 import merge from
'just-merge';
18 import { type RawData
, WebSocket
} from
'ws';
20 import { AutomaticTransactionGenerator
} from
'./AutomaticTransactionGenerator';
21 import { ChargingStationWorkerBroadcastChannel
} from
'./broadcast-channel/ChargingStationWorkerBroadcastChannel';
22 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
25 checkConnectorsConfiguration
,
26 checkStationInfoConnectorStatus
,
28 countReservableConnectors
,
29 createBootNotificationRequest
,
31 getAmperageLimitationUnitDivider
,
32 getBootConnectorStatus
,
33 getChargingStationConnectorChargingProfilesPowerLimit
,
39 getPhaseRotationValue
,
40 initializeConnectorsMapStatus
,
41 propagateSerialNumber
,
42 stationTemplateToStationInfo
,
43 warnTemplateKeysDeprecation
,
44 } from
'./ChargingStationUtils';
45 import { IdTagsCache
} from
'./IdTagsCache';
47 OCPP16IncomingRequestService
,
49 OCPP16ResponseService
,
51 OCPP20IncomingRequestService
,
53 OCPP20ResponseService
,
54 type OCPPIncomingRequestService
,
55 type OCPPRequestService
,
58 import { SharedLRUCache
} from
'./SharedLRUCache';
59 import { BaseError
, OCPPError
} from
'../exception';
60 import { PerformanceStatistics
} from
'../performance';
62 type AutomaticTransactionGeneratorConfiguration
,
64 type BootNotificationRequest
,
65 type BootNotificationResponse
,
67 type ChargingStationConfiguration
,
68 type ChargingStationInfo
,
69 type ChargingStationOcppConfiguration
,
70 type ChargingStationTemplate
,
78 type EvseStatusConfiguration
,
81 type FirmwareStatusNotificationRequest
,
82 type FirmwareStatusNotificationResponse
,
84 type HeartbeatRequest
,
85 type HeartbeatResponse
,
87 type IncomingRequestCommand
,
92 type MeterValuesRequest
,
93 type MeterValuesResponse
,
97 RegistrationStatusEnumType
,
100 ReservationFilterKey
,
101 ReservationTerminationReason
,
103 StandardParametersKey
,
105 type StatusNotificationRequest
,
106 type StatusNotificationResponse
,
107 StopTransactionReason
,
108 type StopTransactionRequest
,
109 type StopTransactionResponse
,
110 SupervisionUrlDistribution
,
111 SupportedFeatureProfiles
,
114 WebSocketCloseEventStatusCode
,
124 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
125 buildConnectorsStatus
,
134 formatDurationMilliSeconds
,
135 formatDurationSeconds
,
137 getWebSocketCloseEventStatusString
,
151 export class ChargingStation
{
152 public readonly index
: number;
153 public readonly templateFile
: string;
154 public stationInfo
!: ChargingStationInfo
;
155 public started
: boolean;
156 public starting
: boolean;
157 public idTagsCache
: IdTagsCache
;
158 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
159 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
160 public wsConnection
!: WebSocket
| null;
161 public readonly connectors
: Map
<number, ConnectorStatus
>;
162 public readonly evses
: Map
<number, EvseStatus
>;
163 public readonly requests
: Map
<string, CachedRequest
>;
164 public performanceStatistics
!: PerformanceStatistics
| undefined;
165 public heartbeatSetInterval
!: NodeJS
.Timeout
;
166 public ocppRequestService
!: OCPPRequestService
;
167 public bootNotificationRequest
!: BootNotificationRequest
;
168 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
169 public powerDivider
!: number;
170 private stopping
: boolean;
171 private configurationFile
!: string;
172 private configurationFileHash
!: string;
173 private connectorsConfigurationHash
!: string;
174 private evsesConfigurationHash
!: string;
175 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
176 private readonly messageBuffer
: Set
<string>;
177 private configuredSupervisionUrl
!: URL
;
178 private wsConnectionRestarted
: boolean;
179 private autoReconnectRetryCount
: number;
180 private templateFileWatcher
!: FSWatcher
| undefined;
181 private templateFileHash
!: string;
182 private readonly sharedLRUCache
: SharedLRUCache
;
183 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
184 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
185 private reservationExpirationSetInterval
?: NodeJS
.Timeout
;
187 constructor(index
: number, templateFile
: string) {
188 this.started
= false;
189 this.starting
= false;
190 this.stopping
= false;
191 this.wsConnectionRestarted
= false;
192 this.autoReconnectRetryCount
= 0;
194 this.templateFile
= templateFile
;
195 this.connectors
= new Map
<number, ConnectorStatus
>();
196 this.evses
= new Map
<number, EvseStatus
>();
197 this.requests
= new Map
<string, CachedRequest
>();
198 this.messageBuffer
= new Set
<string>();
199 this.sharedLRUCache
= SharedLRUCache
.getInstance();
200 this.idTagsCache
= IdTagsCache
.getInstance();
201 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
206 public get
hasEvses(): boolean {
207 return this.connectors
.size
=== 0 && this.evses
.size
> 0;
210 private get
wsConnectionUrl(): URL
{
213 this.getSupervisionUrlOcppConfiguration() &&
214 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
216 ChargingStationConfigurationUtils.getConfigurationKey(
218 this.getSupervisionUrlOcppKey()
221 ? ChargingStationConfigurationUtils.getConfigurationKey(
223 this.getSupervisionUrlOcppKey()
225 : this.configuredSupervisionUrl.href
226 }/${this.stationInfo.chargingStationId}`
230 public logPrefix
= (): string => {
233 (isNotEmptyString(this?.stationInfo?.chargingStationId)
234 ? this?.stationInfo?.chargingStationId
235 : getChargingStationId(this.index, this.getTemplateFromFile())) ??
236 'Error at building log prefix'
241 public hasIdTags(): boolean {
242 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
)));
245 public getEnableStatistics(): boolean {
246 return this.stationInfo
.enableStatistics
?? false;
249 public getMustAuthorizeAtRemoteStart(): boolean {
250 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
253 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
254 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
255 switch (this.getCurrentOutType(stationInfo
)) {
257 return !isUndefined(localStationInfo
.numberOfPhases
) ? localStationInfo
.numberOfPhases
: 3;
263 public isWebSocketConnectionOpened(): boolean {
264 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
267 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
268 return this?.bootNotificationResponse
?.status;
271 public inUnknownState(): boolean {
272 return isNullOrUndefined(this?.bootNotificationResponse
?.status);
275 public inPendingState(): boolean {
276 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
279 public inAcceptedState(): boolean {
280 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
283 public inRejectedState(): boolean {
284 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
287 public isRegistered(): boolean {
289 this.inUnknownState() === false &&
290 (this.inAcceptedState() === true || this.inPendingState() === true)
294 public isChargingStationAvailable(): boolean {
295 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
298 public hasConnector(connectorId
: number): boolean {
300 for (const evseStatus
of this.evses
.values()) {
301 if (evseStatus
.connectors
.has(connectorId
)) {
307 return this.connectors
.has(connectorId
);
310 public isConnectorAvailable(connectorId
: number): boolean {
313 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
317 public getNumberOfConnectors(): number {
319 let numberOfConnectors
= 0;
320 for (const [evseId
, evseStatus
] of this.evses
) {
322 numberOfConnectors
+= evseStatus
.connectors
.size
;
325 return numberOfConnectors
;
327 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
330 public getNumberOfEvses(): number {
331 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
334 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
336 for (const evseStatus
of this.evses
.values()) {
337 if (evseStatus
.connectors
.has(connectorId
)) {
338 return evseStatus
.connectors
.get(connectorId
);
343 return this.connectors
.get(connectorId
);
346 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
347 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
350 public getOcppStrictCompliance(): boolean {
351 return this.stationInfo
?.ocppStrictCompliance
?? true;
354 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
355 const defaultVoltageOut
= getDefaultVoltageOut(
356 this.getCurrentOutType(stationInfo
),
360 return (stationInfo
?? this.stationInfo
).voltageOut
?? defaultVoltageOut
;
363 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
364 const localStationInfo
= stationInfo
?? this.stationInfo
;
365 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
368 public getConnectorMaximumAvailablePower(connectorId
: number): number {
369 let connectorAmperageLimitationPowerLimit
: number;
371 !isNullOrUndefined(this.getAmperageLimitation()) &&
372 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
374 connectorAmperageLimitationPowerLimit
=
375 (this.getCurrentOutType() === CurrentType
.AC
376 ? ACElectricUtils
.powerTotal(
377 this.getNumberOfPhases(),
378 this.getVoltageOut(),
379 this.getAmperageLimitation() *
380 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
382 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
385 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
386 const connectorChargingProfilesPowerLimit
=
387 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
389 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
390 isNaN(connectorAmperageLimitationPowerLimit
)
392 : connectorAmperageLimitationPowerLimit
,
393 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
397 public getTransactionIdTag(transactionId
: number): string | undefined {
399 for (const evseStatus
of this.evses
.values()) {
400 for (const connectorStatus
of evseStatus
.connectors
.values()) {
401 if (connectorStatus
.transactionId
=== transactionId
) {
402 return connectorStatus
.transactionIdTag
;
407 for (const connectorId
of this.connectors
.keys()) {
408 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
409 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
415 public getNumberOfRunningTransactions(): number {
418 for (const [evseId
, evseStatus
] of this.evses
) {
422 for (const connectorStatus
of evseStatus
.connectors
.values()) {
423 if (connectorStatus
.transactionStarted
=== true) {
429 for (const connectorId
of this.connectors
.keys()) {
430 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
438 public getOutOfOrderEndMeterValues(): boolean {
439 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
442 public getBeginEndMeterValues(): boolean {
443 return this.stationInfo
?.beginEndMeterValues
?? false;
446 public getMeteringPerTransaction(): boolean {
447 return this.stationInfo
?.meteringPerTransaction
?? true;
450 public getTransactionDataMeterValues(): boolean {
451 return this.stationInfo
?.transactionDataMeterValues
?? false;
454 public getMainVoltageMeterValues(): boolean {
455 return this.stationInfo
?.mainVoltageMeterValues
?? true;
458 public getPhaseLineToLineVoltageMeterValues(): boolean {
459 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
462 public getCustomValueLimitationMeterValues(): boolean {
463 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
466 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
468 for (const evseStatus
of this.evses
.values()) {
469 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
470 if (connectorStatus
.transactionId
=== transactionId
) {
476 for (const connectorId
of this.connectors
.keys()) {
477 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
484 public getEnergyActiveImportRegisterByTransactionId(
485 transactionId
: number,
488 return this.getEnergyActiveImportRegister(
489 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
494 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
495 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
498 public getAuthorizeRemoteTxRequests(): boolean {
499 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
501 StandardParametersKey
.AuthorizeRemoteTxRequests
503 return authorizeRemoteTxRequests
? convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
506 public getLocalAuthListEnabled(): boolean {
507 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
509 StandardParametersKey
.LocalAuthListEnabled
511 return localAuthListEnabled
? convertToBoolean(localAuthListEnabled
.value
) : false;
514 public getHeartbeatInterval(): number {
515 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
517 StandardParametersKey
.HeartbeatInterval
519 if (HeartbeatInterval
) {
520 return convertToInt(HeartbeatInterval
.value
) * 1000;
522 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
524 StandardParametersKey
.HeartBeatInterval
526 if (HeartBeatInterval
) {
527 return convertToInt(HeartBeatInterval
.value
) * 1000;
529 this.stationInfo
?.autoRegister
=== false &&
531 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
532 Constants.DEFAULT_HEARTBEAT_INTERVAL
535 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
538 public setSupervisionUrl(url
: string): void {
540 this.getSupervisionUrlOcppConfiguration() &&
541 isNotEmptyString(this.getSupervisionUrlOcppKey())
543 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
545 this.getSupervisionUrlOcppKey(),
549 this.stationInfo
.supervisionUrls
= url
;
550 this.saveStationInfo();
551 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
555 public startHeartbeat(): void {
556 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
557 this.heartbeatSetInterval
= setInterval(() => {
558 this.ocppRequestService
559 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
562 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
566 }, this.getHeartbeatInterval());
568 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
569 this.getHeartbeatInterval()
572 } else if (this.heartbeatSetInterval
) {
574 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
575 this.getHeartbeatInterval()
580 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()},
581 not starting the heartbeat`
586 public restartHeartbeat(): void {
588 this.stopHeartbeat();
590 this.startHeartbeat();
593 public restartWebSocketPing(): void {
594 // Stop WebSocket ping
595 this.stopWebSocketPing();
596 // Start WebSocket ping
597 this.startWebSocketPing();
600 public startMeterValues(connectorId
: number, interval
: number): void {
601 if (connectorId
=== 0) {
603 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`
607 if (!this.getConnectorStatus(connectorId
)) {
609 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
610 ${connectorId.toString()}`
614 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
616 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
617 with no transaction started`
621 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
622 isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
625 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
626 with no transaction id`
631 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
632 // FIXME: Implement OCPP version agnostic helpers
633 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
636 this.getConnectorStatus(connectorId
).transactionId
,
639 this.ocppRequestService
640 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
642 RequestCommand
.METER_VALUES
,
645 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
646 meterValue
: [meterValue
],
651 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
658 `${this.logPrefix()} Charging station ${
659 StandardParametersKey.MeterValueSampleInterval
660 } configuration set to ${interval}, not sending MeterValues`
665 public stopMeterValues(connectorId
: number) {
666 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
667 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
671 public start(): void {
672 if (this.started
=== false) {
673 if (this.starting
=== false) {
674 this.starting
= true;
675 if (this.getEnableStatistics() === true) {
676 this.performanceStatistics
?.start();
678 if (this.hasFeatureProfile(SupportedFeatureProfiles
.Reservation
)) {
679 this.startReservationExpirationSetInterval();
681 this.openWSConnection();
682 // Monitor charging station template file
683 this.templateFileWatcher
= watchJsonFile(
685 FileType
.ChargingStationTemplate
,
688 (event
, filename
): void => {
689 if (isNotEmptyString(filename
) && event
=== 'change') {
692 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
694 } file have changed, reload`
696 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
699 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
));
701 this.stopAutomaticTransactionGenerator();
702 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
703 this.startAutomaticTransactionGenerator();
705 if (this.getEnableStatistics() === true) {
706 this.performanceStatistics
?.restart();
708 this.performanceStatistics
?.stop();
710 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
713 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
721 parentPort
?.postMessage(buildStartedMessage(this));
722 this.starting
= false;
724 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
727 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
731 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
732 if (this.started
=== true) {
733 if (this.stopping
=== false) {
734 this.stopping
= true;
735 await this.stopMessageSequence(reason
);
736 this.closeWSConnection();
737 if (this.getEnableStatistics() === true) {
738 this.performanceStatistics
?.stop();
740 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
741 this.templateFileWatcher
?.close();
742 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
743 delete this.bootNotificationResponse
;
744 this.started
= false;
745 this.saveConfiguration();
746 parentPort
?.postMessage(buildStoppedMessage(this));
747 this.stopping
= false;
749 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
752 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
756 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
757 await this.stop(reason
);
758 await sleep(this.stationInfo
.resetTime
);
763 public saveOcppConfiguration(): void {
764 if (this.getOcppPersistentConfiguration()) {
765 this.saveConfiguration();
769 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
770 return ChargingStationConfigurationUtils
.getConfigurationKey(
772 StandardParametersKey
.SupportedFeatureProfiles
773 )?.value
?.includes(featureProfile
);
776 public bufferMessage(message
: string): void {
777 this.messageBuffer
.add(message
);
780 public openWSConnection(
781 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
782 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
784 terminateOpened
: false,
787 options
= { handshakeTimeout
: this.getConnectionTimeout() * 1000, ...options
};
788 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
789 if (this.started
=== false && this.starting
=== false) {
791 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()}
792 on stopped charging station`
797 !isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
798 !isNullOrUndefined(this.stationInfo
.supervisionPassword
)
800 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
802 if (params
?.closeOpened
) {
803 this.closeWSConnection();
805 if (params
?.terminateOpened
) {
806 this.terminateWSConnection();
809 if (this.isWebSocketConnectionOpened() === true) {
811 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()}
818 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
821 this.wsConnection
= new WebSocket(
822 this.wsConnectionUrl
,
823 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
827 // Handle WebSocket message
828 this.wsConnection
.on(
830 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
832 // Handle WebSocket error
833 this.wsConnection
.on(
835 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
837 // Handle WebSocket close
838 this.wsConnection
.on(
840 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
842 // Handle WebSocket open
843 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
844 // Handle WebSocket ping
845 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
846 // Handle WebSocket pong
847 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
850 public closeWSConnection(): void {
851 if (this.isWebSocketConnectionOpened() === true) {
852 this.wsConnection
?.close();
853 this.wsConnection
= null;
857 public getAutomaticTransactionGeneratorConfiguration():
858 | AutomaticTransactionGeneratorConfiguration
860 let automaticTransactionGeneratorConfiguration
:
861 | AutomaticTransactionGeneratorConfiguration
863 const automaticTransactionGeneratorConfigurationFromFile
=
864 this.getConfigurationFromFile()?.automaticTransactionGenerator
;
866 this.getAutomaticTransactionGeneratorPersistentConfiguration() &&
867 automaticTransactionGeneratorConfigurationFromFile
869 automaticTransactionGeneratorConfiguration
=
870 automaticTransactionGeneratorConfigurationFromFile
;
872 automaticTransactionGeneratorConfiguration
=
873 this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
876 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
877 ...automaticTransactionGeneratorConfiguration
,
881 public getAutomaticTransactionGeneratorStatuses(): Status
[] | undefined {
882 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
;
885 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
886 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
887 if (isNotEmptyArray(connectorIds
)) {
888 for (const connectorId
of connectorIds
) {
889 this.automaticTransactionGenerator
?.startConnector(connectorId
);
892 this.automaticTransactionGenerator
?.start();
894 this.saveAutomaticTransactionGeneratorConfiguration();
895 parentPort
?.postMessage(buildUpdatedMessage(this));
898 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
899 if (isNotEmptyArray(connectorIds
)) {
900 for (const connectorId
of connectorIds
) {
901 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
904 this.automaticTransactionGenerator
?.stop();
906 this.saveAutomaticTransactionGeneratorConfiguration();
907 parentPort
?.postMessage(buildUpdatedMessage(this));
910 public async stopTransactionOnConnector(
912 reason
= StopTransactionReason
.NONE
913 ): Promise
<StopTransactionResponse
> {
914 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
916 this.getBeginEndMeterValues() === true &&
917 this.getOcppStrictCompliance() === true &&
918 this.getOutOfOrderEndMeterValues() === false
920 // FIXME: Implement OCPP version agnostic helpers
921 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
924 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
926 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
928 RequestCommand
.METER_VALUES
,
932 meterValue
: [transactionEndMeterValue
],
936 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
938 RequestCommand
.STOP_TRANSACTION
,
941 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
947 public getReservationOnConnectorId0Enabled(): boolean {
948 return convertToBoolean(
949 ChargingStationConfigurationUtils
.getConfigurationKey(
951 StandardParametersKey
.ReserveConnectorZeroSupported
956 public async addReservation(reservation
: Reservation
): Promise
<void> {
957 const [exists
, reservationFound
] = this.doesReservationExists(reservation
);
959 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
);
961 this.getConnectorStatus(reservation
.connectorId
).reservation
= reservation
;
962 await OCPPServiceUtils
.sendAndSetConnectorStatus(
964 reservation
.connectorId
,
965 ConnectorStatusEnum
.Reserved
,
967 { send
: reservation
.connectorId
!== 0 }
971 public async removeReservation(
972 reservation
: Reservation
,
973 reason
?: ReservationTerminationReason
975 const connector
= this.getConnectorStatus(reservation
.connectorId
);
977 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
978 delete connector
.reservation
;
980 case ReservationTerminationReason
.TRANSACTION_STARTED
:
981 delete connector
.reservation
;
983 case ReservationTerminationReason
.RESERVATION_CANCELED
:
984 case ReservationTerminationReason
.REPLACE_EXISTING
:
985 case ReservationTerminationReason
.EXPIRED
:
986 await OCPPServiceUtils
.sendAndSetConnectorStatus(
988 reservation
.connectorId
,
989 ConnectorStatusEnum
.Available
,
991 { send
: reservation
.connectorId
!== 0 }
993 delete connector
.reservation
;
1000 public getReservationBy(
1001 filterKey
: ReservationFilterKey
,
1002 value
: number | string
1003 ): Reservation
| undefined {
1004 if (this.hasEvses
) {
1005 for (const evseStatus
of this.evses
.values()) {
1006 for (const connectorStatus
of evseStatus
.connectors
.values()) {
1007 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
1008 return connectorStatus
.reservation
;
1013 for (const connectorStatus
of this.connectors
.values()) {
1014 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
1015 return connectorStatus
.reservation
;
1021 public doesReservationExists(reservation
: Partial
<Reservation
>): [boolean, Reservation
] {
1022 const foundReservation
= this.getReservationBy(
1023 ReservationFilterKey
.RESERVATION_ID
,
1026 return isUndefined(foundReservation
) ? [false, null] : [true, foundReservation
];
1029 public startReservationExpirationSetInterval(customInterval
?: number): void {
1031 customInterval
?? Constants
.DEFAULT_RESERVATION_EXPIRATION_OBSERVATION_INTERVAL
;
1033 `${this.logPrefix()} Reservation expiration date interval is set to ${interval}
1034 and starts on charging station now`
1036 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1037 this.reservationExpirationSetInterval
= setInterval(async (): Promise
<void> => {
1038 const now
= new Date();
1039 if (this.hasEvses
) {
1040 for (const evseStatus
of this.evses
.values()) {
1041 for (const connectorStatus
of evseStatus
.connectors
.values()) {
1042 if (connectorStatus
?.reservation
?.expiryDate
< now
) {
1043 await this.removeReservation(
1044 connectorStatus
.reservation
,
1045 ReservationTerminationReason
.EXPIRED
1051 for (const connectorStatus
of this.connectors
.values()) {
1052 if (connectorStatus
?.reservation
?.expiryDate
< now
) {
1053 await this.removeReservation(
1054 connectorStatus
.reservation
,
1055 ReservationTerminationReason
.EXPIRED
1063 public restartReservationExpiryDateSetInterval(): void {
1064 this.stopReservationExpirationSetInterval();
1065 this.startReservationExpirationSetInterval();
1068 public validateIncomingRequestWithReservation(connectorId
: number, idTag
: string): boolean {
1069 return this.getReservationBy(ReservationFilterKey
.CONNECTOR_ID
, connectorId
)?.idTag
=== idTag
;
1072 public isConnectorReservable(
1073 reservationId
: number,
1075 connectorId
?: number
1077 const [alreadyExists
] = this.doesReservationExists({ id
: reservationId
});
1078 if (alreadyExists
) {
1079 return alreadyExists
;
1081 const userReservedAlready
= isUndefined(
1082 this.getReservationBy(ReservationFilterKey
.ID_TAG
, idTag
)
1086 const notConnectorZero
= isUndefined(connectorId
) ? true : connectorId
> 0;
1087 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0;
1088 return !alreadyExists
&& !userReservedAlready
&& notConnectorZero
&& freeConnectorsAvailable
;
1091 private getNumberOfReservableConnectors(): number {
1092 let reservableConnectors
= 0;
1093 if (this.hasEvses
) {
1094 for (const evseStatus
of this.evses
.values()) {
1095 reservableConnectors
+= countReservableConnectors(evseStatus
.connectors
);
1098 reservableConnectors
= countReservableConnectors(this.connectors
);
1100 return reservableConnectors
- this.getNumberOfReservationsOnConnectorZero();
1103 private getNumberOfReservationsOnConnectorZero(): number {
1104 let numberOfReservations
= 0;
1105 if (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
) {
1106 ++numberOfReservations
;
1107 } else if (this.connectors
.get(0)?.reservation
) {
1108 ++numberOfReservations
;
1110 return numberOfReservations
;
1113 private flushMessageBuffer(): void {
1114 if (this.messageBuffer
.size
> 0) {
1115 for (const message
of this.messageBuffer
.values()) {
1116 let beginId
: string;
1117 let commandName
: RequestCommand
;
1118 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
1119 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
1121 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
1122 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
1124 this.wsConnection
?.send(message
);
1125 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
1127 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
1129 )} payload sent: ${message}`
1131 this.messageBuffer
.delete(message
);
1136 private getSupervisionUrlOcppConfiguration(): boolean {
1137 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
1140 private stopReservationExpirationSetInterval(): void {
1141 if (this.reservationExpirationSetInterval
) {
1142 clearInterval(this.reservationExpirationSetInterval
);
1146 private getSupervisionUrlOcppKey(): string {
1147 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
1150 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
1151 let template
: ChargingStationTemplate
;
1153 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1154 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
1156 const measureId
= `${FileType.ChargingStationTemplate} read`;
1157 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1158 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
1159 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1160 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1161 .update(JSON
.stringify(template
))
1163 this.sharedLRUCache
.setChargingStationTemplate(template
);
1164 this.templateFileHash
= template
.templateHash
;
1167 handleFileException(
1169 FileType
.ChargingStationTemplate
,
1170 error
as NodeJS
.ErrnoException
,
1177 private getStationInfoFromTemplate(): ChargingStationInfo
{
1178 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
1179 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1180 warnTemplateKeysDeprecation(stationTemplate
, this.logPrefix(), this.templateFile
);
1181 if (stationTemplate
?.Connectors
) {
1182 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1184 const stationInfo
: ChargingStationInfo
= stationTemplateToStationInfo(stationTemplate
);
1185 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
);
1186 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
);
1187 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
1188 createSerialNumber(stationTemplate
, stationInfo
);
1189 if (isNotEmptyArray(stationTemplate
?.power
)) {
1190 stationTemplate
.power
= stationTemplate
.power
as number[];
1191 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
);
1192 stationInfo
.maximumPower
=
1193 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1194 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1195 : stationTemplate
.power
[powerArrayRandomIndex
];
1197 stationTemplate
.power
= stationTemplate
?.power
as number;
1198 stationInfo
.maximumPower
=
1199 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1200 ? stationTemplate
.power
* 1000
1201 : stationTemplate
.power
;
1203 stationInfo
.firmwareVersionPattern
=
1204 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
1206 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1207 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
1210 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1212 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1215 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1222 stationTemplate
?.firmwareUpgrade
?? {}
1224 stationInfo
.resetTime
= !isNullOrUndefined(stationTemplate
?.resetTime
)
1225 ? stationTemplate
.resetTime
* 1000
1226 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1227 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1231 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
1232 let stationInfo
: ChargingStationInfo
| undefined;
1233 if (this.getStationInfoPersistentConfiguration()) {
1234 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1236 delete stationInfo
?.infoHash
;
1242 private getStationInfo(): ChargingStationInfo
{
1243 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1244 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
1246 // 1. charging station info from template
1247 // 2. charging station info from configuration file
1248 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1249 return stationInfoFromFile
;
1251 stationInfoFromFile
&&
1252 propagateSerialNumber(
1253 this.getTemplateFromFile(),
1254 stationInfoFromFile
,
1255 stationInfoFromTemplate
1257 return stationInfoFromTemplate
;
1260 private saveStationInfo(): void {
1261 if (this.getStationInfoPersistentConfiguration()) {
1262 this.saveConfiguration();
1266 private getOcppPersistentConfiguration(): boolean {
1267 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1270 private getStationInfoPersistentConfiguration(): boolean {
1271 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1274 private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean {
1275 return this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
?? true;
1278 private handleUnsupportedVersion(version
: OCPPVersion
) {
1279 const errorMsg
= `Unsupported protocol version '${version}' configured
1280 in template file ${this.templateFile}`;
1281 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1282 throw new BaseError(errorMsg
);
1285 private initialize(): void {
1286 const stationTemplate
= this.getTemplateFromFile();
1287 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1288 this.configurationFile
= join(
1289 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1290 `${getHashId(this.index, stationTemplate)}.json`
1292 const chargingStationConfiguration
= this.getConfigurationFromFile();
1294 chargingStationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
1295 (chargingStationConfiguration
?.connectorsStatus
|| chargingStationConfiguration
?.evsesStatus
)
1297 this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration
);
1299 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1301 this.stationInfo
= this.getStationInfo();
1303 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1304 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1305 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1307 const patternGroup
: number | undefined =
1308 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1309 this.stationInfo
.firmwareVersion
?.split('.').length
;
1310 const match
= this.stationInfo
?.firmwareVersion
1311 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1312 ?.slice(1, patternGroup
+ 1);
1313 const patchLevelIndex
= match
.length
- 1;
1314 match
[patchLevelIndex
] = (
1315 convertToInt(match
[patchLevelIndex
]) +
1316 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1318 this.stationInfo
.firmwareVersion
= match
?.join('.');
1320 this.saveStationInfo();
1321 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1322 if (this.getEnableStatistics() === true) {
1323 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1324 this.stationInfo
.hashId
,
1325 this.stationInfo
.chargingStationId
,
1326 this.configuredSupervisionUrl
1329 this.bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
);
1330 this.powerDivider
= this.getPowerDivider();
1331 // OCPP configuration
1332 this.ocppConfiguration
= this.getOcppConfiguration();
1333 this.initializeOcppConfiguration();
1334 this.initializeOcppServices();
1335 if (this.stationInfo
?.autoRegister
=== true) {
1336 this.bootNotificationResponse
= {
1337 currentTime
: new Date(),
1338 interval
: this.getHeartbeatInterval() / 1000,
1339 status: RegistrationStatusEnumType
.ACCEPTED
,
1344 private initializeOcppServices(): void {
1345 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1346 switch (ocppVersion
) {
1347 case OCPPVersion
.VERSION_16
:
1348 this.ocppIncomingRequestService
=
1349 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1350 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1351 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1354 case OCPPVersion
.VERSION_20
:
1355 case OCPPVersion
.VERSION_201
:
1356 this.ocppIncomingRequestService
=
1357 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1358 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1359 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1363 this.handleUnsupportedVersion(ocppVersion
);
1368 private initializeOcppConfiguration(): void {
1370 !ChargingStationConfigurationUtils
.getConfigurationKey(
1372 StandardParametersKey
.HeartbeatInterval
1375 ChargingStationConfigurationUtils
.addConfigurationKey(
1377 StandardParametersKey
.HeartbeatInterval
,
1382 !ChargingStationConfigurationUtils
.getConfigurationKey(
1384 StandardParametersKey
.HeartBeatInterval
1387 ChargingStationConfigurationUtils
.addConfigurationKey(
1389 StandardParametersKey
.HeartBeatInterval
,
1395 this.getSupervisionUrlOcppConfiguration() &&
1396 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1397 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1399 ChargingStationConfigurationUtils
.addConfigurationKey(
1401 this.getSupervisionUrlOcppKey(),
1402 this.configuredSupervisionUrl
.href
,
1406 !this.getSupervisionUrlOcppConfiguration() &&
1407 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1408 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1410 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1412 this.getSupervisionUrlOcppKey(),
1417 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1418 !ChargingStationConfigurationUtils
.getConfigurationKey(
1420 this.stationInfo
.amperageLimitationOcppKey
1423 ChargingStationConfigurationUtils
.addConfigurationKey(
1425 this.stationInfo
.amperageLimitationOcppKey
,
1427 this.stationInfo
.maximumAmperage
* getAmperageLimitationUnitDivider(this.stationInfo
)
1432 !ChargingStationConfigurationUtils
.getConfigurationKey(
1434 StandardParametersKey
.SupportedFeatureProfiles
1437 ChargingStationConfigurationUtils
.addConfigurationKey(
1439 StandardParametersKey
.SupportedFeatureProfiles
,
1440 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1443 ChargingStationConfigurationUtils
.addConfigurationKey(
1445 StandardParametersKey
.NumberOfConnectors
,
1446 this.getNumberOfConnectors().toString(),
1451 !ChargingStationConfigurationUtils
.getConfigurationKey(
1453 StandardParametersKey
.MeterValuesSampledData
1456 ChargingStationConfigurationUtils
.addConfigurationKey(
1458 StandardParametersKey
.MeterValuesSampledData
,
1459 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1463 !ChargingStationConfigurationUtils
.getConfigurationKey(
1465 StandardParametersKey
.ConnectorPhaseRotation
1468 const connectorsPhaseRotation
: string[] = [];
1469 if (this.hasEvses
) {
1470 for (const evseStatus
of this.evses
.values()) {
1471 for (const connectorId
of evseStatus
.connectors
.keys()) {
1472 connectorsPhaseRotation
.push(
1473 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1478 for (const connectorId
of this.connectors
.keys()) {
1479 connectorsPhaseRotation
.push(
1480 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1484 ChargingStationConfigurationUtils
.addConfigurationKey(
1486 StandardParametersKey
.ConnectorPhaseRotation
,
1487 connectorsPhaseRotation
.toString()
1491 !ChargingStationConfigurationUtils
.getConfigurationKey(
1493 StandardParametersKey
.AuthorizeRemoteTxRequests
1496 ChargingStationConfigurationUtils
.addConfigurationKey(
1498 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1503 !ChargingStationConfigurationUtils
.getConfigurationKey(
1505 StandardParametersKey
.LocalAuthListEnabled
1507 ChargingStationConfigurationUtils
.getConfigurationKey(
1509 StandardParametersKey
.SupportedFeatureProfiles
1510 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1512 ChargingStationConfigurationUtils
.addConfigurationKey(
1514 StandardParametersKey
.LocalAuthListEnabled
,
1519 !ChargingStationConfigurationUtils
.getConfigurationKey(
1521 StandardParametersKey
.ConnectionTimeOut
1524 ChargingStationConfigurationUtils
.addConfigurationKey(
1526 StandardParametersKey
.ConnectionTimeOut
,
1527 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1530 this.saveOcppConfiguration();
1533 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1534 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1535 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1536 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1538 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1539 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1540 const evseStatus
= cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1541 delete evseStatus
.connectorsStatus
;
1542 this.evses
.set(evseId
, {
1543 ...(evseStatus
as EvseStatus
),
1544 connectors
: new Map
<number, ConnectorStatus
>(
1545 evseStatusConfiguration
.connectorsStatus
.map((connectorStatus
, connectorId
) => [
1552 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1553 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1554 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1555 throw new BaseError(errorMsg
);
1557 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1558 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1559 throw new BaseError(errorMsg
);
1563 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1564 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1565 this.initializeConnectorsFromTemplate(stationTemplate
);
1566 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1567 this.initializeEvsesFromTemplate(stationTemplate
);
1568 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1569 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1570 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1571 throw new BaseError(errorMsg
);
1573 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1574 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1575 throw new BaseError(errorMsg
);
1579 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1580 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1581 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1582 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1583 throw new BaseError(errorMsg
);
1585 if (!stationTemplate
?.Connectors
[0]) {
1587 `${this.logPrefix()} Charging station information from template ${
1589 } with no connector id 0 configuration`
1592 if (stationTemplate
?.Connectors
) {
1593 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1594 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1595 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1597 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`
1600 const connectorsConfigChanged
=
1601 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1602 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1603 connectorsConfigChanged
&& this.connectors
.clear();
1604 this.connectorsConfigurationHash
= connectorsConfigHash
;
1605 if (templateMaxConnectors
> 0) {
1606 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1608 connectorId
=== 0 &&
1609 (!stationTemplate
?.Connectors
[connectorId
] ||
1610 this.getUseConnectorId0(stationTemplate
) === false)
1614 const templateConnectorId
=
1615 connectorId
> 0 && stationTemplate
?.randomConnectors
1616 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1618 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1619 checkStationInfoConnectorStatus(
1620 templateConnectorId
,
1625 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1627 initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1628 this.saveConnectorsStatus();
1631 `${this.logPrefix()} Charging station information from template ${
1633 } with no connectors configuration defined, cannot create connectors`
1639 `${this.logPrefix()} Charging station information from template ${
1641 } with no connectors configuration defined, using already defined connectors`
1646 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1647 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1648 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1649 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1650 throw new BaseError(errorMsg
);
1652 if (!stationTemplate
?.Evses
[0]) {
1654 `${this.logPrefix()} Charging station information from template ${
1656 } with no evse id 0 configuration`
1659 if (!stationTemplate
?.Evses
[0]?.Connectors
[0]) {
1661 `${this.logPrefix()} Charging station information from template ${
1663 } with evse id 0 with no connector id 0 configuration`
1666 if (stationTemplate
?.Evses
) {
1667 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1668 .update(JSON
.stringify(stationTemplate
?.Evses
))
1670 const evsesConfigChanged
=
1671 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1672 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1673 evsesConfigChanged
&& this.evses
.clear();
1674 this.evsesConfigurationHash
= evsesConfigHash
;
1675 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
?.Evses
);
1676 if (templateMaxEvses
> 0) {
1677 for (const evse
in stationTemplate
.Evses
) {
1678 const evseId
= convertToInt(evse
);
1679 this.evses
.set(evseId
, {
1680 connectors
: buildConnectorsMap(
1681 stationTemplate
?.Evses
[evse
]?.Connectors
,
1685 availability
: AvailabilityType
.Operative
,
1687 initializeConnectorsMapStatus(this.evses
.get(evseId
)?.connectors
, this.logPrefix());
1689 this.saveEvsesStatus();
1692 `${this.logPrefix()} Charging station information from template ${
1694 } with no evses configuration defined, cannot create evses`
1700 `${this.logPrefix()} Charging station information from template ${
1702 } with no evses configuration defined, using already defined evses`
1707 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1708 let configuration
: ChargingStationConfiguration
| undefined;
1709 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1711 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1712 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1713 this.configurationFileHash
1716 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1717 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1718 configuration
= JSON
.parse(
1719 readFileSync(this.configurationFile
, 'utf8')
1720 ) as ChargingStationConfiguration
;
1721 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1722 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1723 this.configurationFileHash
= configuration
.configurationHash
;
1726 handleFileException(
1727 this.configurationFile
,
1728 FileType
.ChargingStationConfiguration
,
1729 error
as NodeJS
.ErrnoException
,
1734 return configuration
;
1737 private saveAutomaticTransactionGeneratorConfiguration(): void {
1738 if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) {
1739 this.saveConfiguration();
1743 private saveConnectorsStatus() {
1744 this.saveConfiguration();
1747 private saveEvsesStatus() {
1748 this.saveConfiguration();
1751 private saveConfiguration(): void {
1752 if (isNotEmptyString(this.configurationFile
)) {
1754 if (!existsSync(dirname(this.configurationFile
))) {
1755 mkdirSync(dirname(this.configurationFile
), { recursive
: true });
1757 let configurationData
: ChargingStationConfiguration
=
1758 cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()) ?? {};
1759 if (this.getStationInfoPersistentConfiguration() && this.stationInfo
) {
1760 configurationData
.stationInfo
= this.stationInfo
;
1762 delete configurationData
.stationInfo
;
1764 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration
?.configurationKey
) {
1765 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1767 delete configurationData
.configurationKey
;
1769 configurationData
= merge
<ChargingStationConfiguration
>(
1771 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1774 !this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
1775 !this.getAutomaticTransactionGeneratorConfiguration()
1777 delete configurationData
.automaticTransactionGenerator
;
1779 if (this.connectors
.size
> 0) {
1780 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1782 delete configurationData
.connectorsStatus
;
1784 if (this.evses
.size
> 0) {
1785 configurationData
.evsesStatus
= buildEvsesStatus(this);
1787 delete configurationData
.evsesStatus
;
1789 delete configurationData
.configurationHash
;
1790 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1793 stationInfo
: configurationData
.stationInfo
,
1794 configurationKey
: configurationData
.configurationKey
,
1795 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1796 } as ChargingStationConfiguration
)
1799 if (this.configurationFileHash
!== configurationHash
) {
1800 AsyncLock
.acquire(AsyncLockType
.configuration
)
1802 configurationData
.configurationHash
= configurationHash
;
1803 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1804 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1805 const fileDescriptor
= openSync(this.configurationFile
, 'w');
1806 writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1807 closeSync(fileDescriptor
);
1808 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1809 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1810 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1811 this.configurationFileHash
= configurationHash
;
1814 handleFileException(
1815 this.configurationFile
,
1816 FileType
.ChargingStationConfiguration
,
1817 error
as NodeJS
.ErrnoException
,
1822 AsyncLock
.release(AsyncLockType
.configuration
).catch(Constants
.EMPTY_FUNCTION
);
1826 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1827 this.configurationFile
1832 handleFileException(
1833 this.configurationFile
,
1834 FileType
.ChargingStationConfiguration
,
1835 error
as NodeJS
.ErrnoException
,
1841 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1846 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1847 return this.getTemplateFromFile()?.Configuration
;
1850 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1851 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1852 if (this.getOcppPersistentConfiguration() === true && configurationKey
) {
1853 return { configurationKey
};
1858 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1859 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1860 this.getOcppConfigurationFromFile();
1861 if (!ocppConfiguration
) {
1862 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1864 return ocppConfiguration
;
1867 private async onOpen(): Promise
<void> {
1868 if (this.isWebSocketConnectionOpened() === true) {
1870 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1872 if (this.isRegistered() === false) {
1873 // Send BootNotification
1874 let registrationRetryCount
= 0;
1876 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1877 BootNotificationRequest
,
1878 BootNotificationResponse
1879 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1880 skipBufferingOnError
: true,
1882 if (this.isRegistered() === false) {
1883 this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount
;
1885 this?.bootNotificationResponse
?.interval
1886 ? this.bootNotificationResponse
.interval
* 1000
1887 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1891 this.isRegistered() === false &&
1892 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1893 this.getRegistrationMaxRetries() === -1)
1896 if (this.isRegistered() === true) {
1897 if (this.inAcceptedState() === true) {
1898 await this.startMessageSequence();
1902 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1905 this.wsConnectionRestarted
= false;
1906 this.autoReconnectRetryCount
= 0;
1907 parentPort
?.postMessage(buildUpdatedMessage(this));
1910 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1915 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1918 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1919 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1921 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1923 )}' and reason '${reason.toString()}'`
1925 this.autoReconnectRetryCount
= 0;
1930 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1932 )}' and reason '${reason.toString()}'`
1934 this.started
=== true && (await this.reconnect());
1937 parentPort
?.postMessage(buildUpdatedMessage(this));
1940 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1941 const cachedRequest
= this.requests
.get(messageId
);
1942 if (Array.isArray(cachedRequest
) === true) {
1943 return cachedRequest
;
1945 throw new OCPPError(
1946 ErrorType
.PROTOCOL_ERROR
,
1947 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1949 )} is not an array`,
1951 cachedRequest
as JsonType
1955 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1956 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1957 if (this.getEnableStatistics() === true) {
1958 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1961 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1965 // Process the message
1966 await this.ocppIncomingRequestService
.incomingRequestHandler(
1974 private handleResponseMessage(response
: Response
): void {
1975 const [messageType
, messageId
, commandPayload
] = response
;
1976 if (this.requests
.has(messageId
) === false) {
1978 throw new OCPPError(
1979 ErrorType
.INTERNAL_ERROR
,
1980 `Response for unknown message id ${messageId}`,
1986 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1991 `${this.logPrefix()} << Command '${
1992 requestCommandName ?? Constants.UNKNOWN_COMMAND
1993 }' received response payload: ${JSON.stringify(response)}`
1995 responseCallback(commandPayload
, requestPayload
);
1998 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1999 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
2000 if (this.requests
.has(messageId
) === false) {
2002 throw new OCPPError(
2003 ErrorType
.INTERNAL_ERROR
,
2004 `Error response for unknown message id ${messageId}`,
2006 { errorType
, errorMessage
, errorDetails
}
2009 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
2011 `${this.logPrefix()} << Command '${
2012 requestCommandName ?? Constants.UNKNOWN_COMMAND
2013 }' received error response payload: ${JSON.stringify(errorResponse)}`
2015 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
2018 private async onMessage(data
: RawData
): Promise
<void> {
2019 let request
: IncomingRequest
| Response
| ErrorResponse
;
2020 let messageType
: number;
2021 let errorMsg
: string;
2023 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
2024 if (Array.isArray(request
) === true) {
2025 [messageType
] = request
;
2026 // Check the type of message
2027 switch (messageType
) {
2029 case MessageType
.CALL_MESSAGE
:
2030 await this.handleIncomingMessage(request
as IncomingRequest
);
2033 case MessageType
.CALL_RESULT_MESSAGE
:
2034 this.handleResponseMessage(request
as Response
);
2037 case MessageType
.CALL_ERROR_MESSAGE
:
2038 this.handleErrorMessage(request
as ErrorResponse
);
2042 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2043 errorMsg
= `Wrong message type ${messageType}`;
2044 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2045 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
2047 parentPort
?.postMessage(buildUpdatedMessage(this));
2049 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
2054 let commandName
: IncomingRequestCommand
;
2055 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
2056 let errorCallback
: ErrorCallback
;
2057 const [, messageId
] = request
;
2058 switch (messageType
) {
2059 case MessageType
.CALL_MESSAGE
:
2060 [, , commandName
] = request
as IncomingRequest
;
2062 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
2064 case MessageType
.CALL_RESULT_MESSAGE
:
2065 case MessageType
.CALL_ERROR_MESSAGE
:
2066 if (this.requests
.has(messageId
) === true) {
2067 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
2068 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
2069 errorCallback(error
as OCPPError
, false);
2071 // Remove the request from the cache in case of error at response handling
2072 this.requests
.delete(messageId
);
2076 if (error
instanceof OCPPError
=== false) {
2078 `${this.logPrefix()} Error thrown at incoming OCPP command '${
2079 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2080 }' message '${data.toString()}' handling is not an OCPPError:`,
2085 `${this.logPrefix()} Incoming OCPP command '${
2086 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2087 }' message '${data.toString()}'${
2088 messageType !== MessageType.CALL_MESSAGE
2089 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
2091 } processing error:`,
2097 private onPing(): void {
2098 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
2101 private onPong(): void {
2102 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
2105 private onError(error
: WSError
): void {
2106 this.closeWSConnection();
2107 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
2110 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
2111 if (this.getMeteringPerTransaction() === true) {
2114 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
2115 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2120 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
2121 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2125 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
2126 return stationTemplate
?.useConnectorId0
?? true;
2129 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
2130 if (this.hasEvses
) {
2131 for (const [evseId
, evseStatus
] of this.evses
) {
2135 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2136 if (connectorStatus
.transactionStarted
=== true) {
2137 await this.stopTransactionOnConnector(connectorId
, reason
);
2142 for (const connectorId
of this.connectors
.keys()) {
2143 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2144 await this.stopTransactionOnConnector(connectorId
, reason
);
2151 private getConnectionTimeout(): number {
2153 ChargingStationConfigurationUtils
.getConfigurationKey(
2155 StandardParametersKey
.ConnectionTimeOut
2160 ChargingStationConfigurationUtils
.getConfigurationKey(
2162 StandardParametersKey
.ConnectionTimeOut
2164 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
2167 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
2170 // -1 for unlimited, 0 for disabling
2171 private getAutoReconnectMaxRetries(): number | undefined {
2173 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
2178 private getRegistrationMaxRetries(): number | undefined {
2179 return this.stationInfo
.registrationMaxRetries
?? -1;
2182 private getPowerDivider(): number {
2183 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
2184 if (this.stationInfo
?.powerSharedByConnectors
) {
2185 powerDivider
= this.getNumberOfRunningTransactions();
2187 return powerDivider
;
2190 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
2191 const maximumPower
= this.getMaximumPower(stationInfo
);
2192 switch (this.getCurrentOutType(stationInfo
)) {
2193 case CurrentType
.AC
:
2194 return ACElectricUtils
.amperagePerPhaseFromPower(
2195 this.getNumberOfPhases(stationInfo
),
2196 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2197 this.getVoltageOut(stationInfo
)
2199 case CurrentType
.DC
:
2200 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
2204 private getAmperageLimitation(): number | undefined {
2206 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2207 ChargingStationConfigurationUtils
.getConfigurationKey(
2209 this.stationInfo
.amperageLimitationOcppKey
2214 ChargingStationConfigurationUtils
.getConfigurationKey(
2216 this.stationInfo
.amperageLimitationOcppKey
2218 ) / getAmperageLimitationUnitDivider(this.stationInfo
)
2223 private async startMessageSequence(): Promise
<void> {
2224 if (this.stationInfo
?.autoRegister
=== true) {
2225 await this.ocppRequestService
.requestHandler
<
2226 BootNotificationRequest
,
2227 BootNotificationResponse
2228 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2229 skipBufferingOnError
: true,
2232 // Start WebSocket ping
2233 this.startWebSocketPing();
2235 this.startHeartbeat();
2236 // Initialize connectors status
2237 if (this.hasEvses
) {
2238 for (const [evseId
, evseStatus
] of this.evses
) {
2240 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2241 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
);
2242 await OCPPServiceUtils
.sendAndSetConnectorStatus(
2245 connectorBootStatus
,
2252 for (const connectorId
of this.connectors
.keys()) {
2253 if (connectorId
> 0) {
2254 const connectorBootStatus
= getBootConnectorStatus(
2257 this.getConnectorStatus(connectorId
)
2259 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2263 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2264 await this.ocppRequestService
.requestHandler
<
2265 FirmwareStatusNotificationRequest
,
2266 FirmwareStatusNotificationResponse
2267 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2268 status: FirmwareStatus
.Installed
,
2270 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2274 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2275 this.startAutomaticTransactionGenerator();
2277 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2280 private async stopMessageSequence(
2281 reason
: StopTransactionReason
= StopTransactionReason
.NONE
2283 // Stop WebSocket ping
2284 this.stopWebSocketPing();
2286 this.stopHeartbeat();
2287 // Stop ongoing transactions
2288 if (this.automaticTransactionGenerator
?.started
=== true) {
2289 this.stopAutomaticTransactionGenerator();
2291 await this.stopRunningTransactions(reason
);
2293 if (this.hasEvses
) {
2294 for (const [evseId
, evseStatus
] of this.evses
) {
2296 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2297 await this.ocppRequestService
.requestHandler
<
2298 StatusNotificationRequest
,
2299 StatusNotificationResponse
2302 RequestCommand
.STATUS_NOTIFICATION
,
2303 OCPPServiceUtils
.buildStatusNotificationRequest(
2306 ConnectorStatusEnum
.Unavailable
,
2310 delete connectorStatus
?.status;
2315 for (const connectorId
of this.connectors
.keys()) {
2316 if (connectorId
> 0) {
2317 await this.ocppRequestService
.requestHandler
<
2318 StatusNotificationRequest
,
2319 StatusNotificationResponse
2322 RequestCommand
.STATUS_NOTIFICATION
,
2323 OCPPServiceUtils
.buildStatusNotificationRequest(
2326 ConnectorStatusEnum
.Unavailable
2329 delete this.getConnectorStatus(connectorId
)?.status;
2335 private startWebSocketPing(): void {
2336 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
2338 StandardParametersKey
.WebSocketPingInterval
2341 ChargingStationConfigurationUtils
.getConfigurationKey(
2343 StandardParametersKey
.WebSocketPingInterval
2347 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2348 this.webSocketPingSetInterval
= setInterval(() => {
2349 if (this.isWebSocketConnectionOpened() === true) {
2350 this.wsConnection
?.ping();
2352 }, webSocketPingInterval
* 1000);
2354 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2355 webSocketPingInterval
2358 } else if (this.webSocketPingSetInterval
) {
2360 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2361 webSocketPingInterval
2366 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2371 private stopWebSocketPing(): void {
2372 if (this.webSocketPingSetInterval
) {
2373 clearInterval(this.webSocketPingSetInterval
);
2374 delete this.webSocketPingSetInterval
;
2378 private getConfiguredSupervisionUrl(): URL
{
2379 let configuredSupervisionUrl
: string;
2380 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2381 if (isNotEmptyArray(supervisionUrls
)) {
2382 let configuredSupervisionUrlIndex
: number;
2383 switch (Configuration
.getSupervisionUrlDistribution()) {
2384 case SupervisionUrlDistribution
.RANDOM
:
2385 configuredSupervisionUrlIndex
= Math.floor(secureRandom() * supervisionUrls
.length
);
2387 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2388 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2390 Object.values(SupervisionUrlDistribution
).includes(
2391 Configuration
.getSupervisionUrlDistribution()
2394 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2395 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2398 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2401 configuredSupervisionUrl
= supervisionUrls
[configuredSupervisionUrlIndex
];
2403 configuredSupervisionUrl
= supervisionUrls
as string;
2405 if (isNotEmptyString(configuredSupervisionUrl
)) {
2406 return new URL(configuredSupervisionUrl
);
2408 const errorMsg
= 'No supervision url(s) configured';
2409 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2410 throw new BaseError(`${errorMsg}`);
2413 private stopHeartbeat(): void {
2414 if (this.heartbeatSetInterval
) {
2415 clearInterval(this.heartbeatSetInterval
);
2416 delete this.heartbeatSetInterval
;
2420 private terminateWSConnection(): void {
2421 if (this.isWebSocketConnectionOpened() === true) {
2422 this.wsConnection
?.terminate();
2423 this.wsConnection
= null;
2427 private getReconnectExponentialDelay(): boolean {
2428 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2431 private async reconnect(): Promise
<void> {
2432 // Stop WebSocket ping
2433 this.stopWebSocketPing();
2435 this.stopHeartbeat();
2436 // Stop the ATG if needed
2437 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
=== true) {
2438 this.stopAutomaticTransactionGenerator();
2441 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2442 this.getAutoReconnectMaxRetries() === -1
2444 ++this.autoReconnectRetryCount
;
2445 const reconnectDelay
= this.getReconnectExponentialDelay()
2446 ? exponentialDelay(this.autoReconnectRetryCount
)
2447 : this.getConnectionTimeout() * 1000;
2448 const reconnectDelayWithdraw
= 1000;
2449 const reconnectTimeout
=
2450 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2451 ? reconnectDelay
- reconnectDelayWithdraw
2454 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2457 )}ms, timeout ${reconnectTimeout}ms`
2459 await sleep(reconnectDelay
);
2461 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2463 this.openWSConnection(
2465 ...(this.stationInfo
?.wsOptions
?? {}),
2466 handshakeTimeout
: reconnectTimeout
,
2468 { closeOpened
: true }
2470 this.wsConnectionRestarted
= true;
2471 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2473 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2474 this.autoReconnectRetryCount
2475 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`