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 getPayloadSchemaValidation(): boolean {
254 return this.stationInfo
.payloadSchemaValidation
?? true;
257 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
258 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
259 switch (this.getCurrentOutType(stationInfo
)) {
261 return !isUndefined(localStationInfo
.numberOfPhases
) ? localStationInfo
.numberOfPhases
: 3;
267 public isWebSocketConnectionOpened(): boolean {
268 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
271 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
272 return this?.bootNotificationResponse
?.status;
275 public inUnknownState(): boolean {
276 return isNullOrUndefined(this?.bootNotificationResponse
?.status);
279 public inPendingState(): boolean {
280 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
283 public inAcceptedState(): boolean {
284 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
287 public inRejectedState(): boolean {
288 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
291 public isRegistered(): boolean {
293 this.inUnknownState() === false &&
294 (this.inAcceptedState() === true || this.inPendingState() === true)
298 public isChargingStationAvailable(): boolean {
299 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
302 public hasConnector(connectorId
: number): boolean {
304 for (const evseStatus
of this.evses
.values()) {
305 if (evseStatus
.connectors
.has(connectorId
)) {
311 return this.connectors
.has(connectorId
);
314 public isConnectorAvailable(connectorId
: number): boolean {
317 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
321 public getNumberOfConnectors(): number {
323 let numberOfConnectors
= 0;
324 for (const [evseId
, evseStatus
] of this.evses
) {
326 numberOfConnectors
+= evseStatus
.connectors
.size
;
329 return numberOfConnectors
;
331 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
334 public getNumberOfEvses(): number {
335 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
338 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
340 for (const evseStatus
of this.evses
.values()) {
341 if (evseStatus
.connectors
.has(connectorId
)) {
342 return evseStatus
.connectors
.get(connectorId
);
347 return this.connectors
.get(connectorId
);
350 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
351 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
354 public getOcppStrictCompliance(): boolean {
355 return this.stationInfo
?.ocppStrictCompliance
?? false;
358 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
359 const defaultVoltageOut
= getDefaultVoltageOut(
360 this.getCurrentOutType(stationInfo
),
364 return (stationInfo
?? this.stationInfo
).voltageOut
?? defaultVoltageOut
;
367 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
368 const localStationInfo
= stationInfo
?? this.stationInfo
;
369 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
372 public getConnectorMaximumAvailablePower(connectorId
: number): number {
373 let connectorAmperageLimitationPowerLimit
: number;
375 !isNullOrUndefined(this.getAmperageLimitation()) &&
376 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
378 connectorAmperageLimitationPowerLimit
=
379 (this.getCurrentOutType() === CurrentType
.AC
380 ? ACElectricUtils
.powerTotal(
381 this.getNumberOfPhases(),
382 this.getVoltageOut(),
383 this.getAmperageLimitation() *
384 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
386 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
389 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
390 const connectorChargingProfilesPowerLimit
=
391 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
393 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
394 isNaN(connectorAmperageLimitationPowerLimit
)
396 : connectorAmperageLimitationPowerLimit
,
397 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
401 public getTransactionIdTag(transactionId
: number): string | undefined {
403 for (const evseStatus
of this.evses
.values()) {
404 for (const connectorStatus
of evseStatus
.connectors
.values()) {
405 if (connectorStatus
.transactionId
=== transactionId
) {
406 return connectorStatus
.transactionIdTag
;
411 for (const connectorId
of this.connectors
.keys()) {
412 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
413 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
419 public getNumberOfRunningTransactions(): number {
422 for (const [evseId
, evseStatus
] of this.evses
) {
426 for (const connectorStatus
of evseStatus
.connectors
.values()) {
427 if (connectorStatus
.transactionStarted
=== true) {
433 for (const connectorId
of this.connectors
.keys()) {
434 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
442 public getOutOfOrderEndMeterValues(): boolean {
443 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
446 public getBeginEndMeterValues(): boolean {
447 return this.stationInfo
?.beginEndMeterValues
?? false;
450 public getMeteringPerTransaction(): boolean {
451 return this.stationInfo
?.meteringPerTransaction
?? true;
454 public getTransactionDataMeterValues(): boolean {
455 return this.stationInfo
?.transactionDataMeterValues
?? false;
458 public getMainVoltageMeterValues(): boolean {
459 return this.stationInfo
?.mainVoltageMeterValues
?? true;
462 public getPhaseLineToLineVoltageMeterValues(): boolean {
463 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
466 public getCustomValueLimitationMeterValues(): boolean {
467 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
470 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
472 for (const evseStatus
of this.evses
.values()) {
473 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
474 if (connectorStatus
.transactionId
=== transactionId
) {
480 for (const connectorId
of this.connectors
.keys()) {
481 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
488 public getEnergyActiveImportRegisterByTransactionId(
489 transactionId
: number,
492 return this.getEnergyActiveImportRegister(
493 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
498 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
499 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
502 public getAuthorizeRemoteTxRequests(): boolean {
503 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
505 StandardParametersKey
.AuthorizeRemoteTxRequests
507 return authorizeRemoteTxRequests
? convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
510 public getLocalAuthListEnabled(): boolean {
511 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
513 StandardParametersKey
.LocalAuthListEnabled
515 return localAuthListEnabled
? convertToBoolean(localAuthListEnabled
.value
) : false;
518 public getHeartbeatInterval(): number {
519 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
521 StandardParametersKey
.HeartbeatInterval
523 if (HeartbeatInterval
) {
524 return convertToInt(HeartbeatInterval
.value
) * 1000;
526 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
528 StandardParametersKey
.HeartBeatInterval
530 if (HeartBeatInterval
) {
531 return convertToInt(HeartBeatInterval
.value
) * 1000;
533 this.stationInfo
?.autoRegister
=== false &&
535 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
536 Constants.DEFAULT_HEARTBEAT_INTERVAL
539 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
542 public setSupervisionUrl(url
: string): void {
544 this.getSupervisionUrlOcppConfiguration() &&
545 isNotEmptyString(this.getSupervisionUrlOcppKey())
547 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
549 this.getSupervisionUrlOcppKey(),
553 this.stationInfo
.supervisionUrls
= url
;
554 this.saveStationInfo();
555 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
559 public startHeartbeat(): void {
560 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
561 this.heartbeatSetInterval
= setInterval(() => {
562 this.ocppRequestService
563 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
566 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
570 }, this.getHeartbeatInterval());
572 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
573 this.getHeartbeatInterval()
576 } else if (this.heartbeatSetInterval
) {
578 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
579 this.getHeartbeatInterval()
584 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()},
585 not starting the heartbeat`
590 public restartHeartbeat(): void {
592 this.stopHeartbeat();
594 this.startHeartbeat();
597 public restartWebSocketPing(): void {
598 // Stop WebSocket ping
599 this.stopWebSocketPing();
600 // Start WebSocket ping
601 this.startWebSocketPing();
604 public startMeterValues(connectorId
: number, interval
: number): void {
605 if (connectorId
=== 0) {
607 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`
611 if (!this.getConnectorStatus(connectorId
)) {
613 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
614 ${connectorId.toString()}`
618 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
620 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
621 with no transaction started`
625 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
626 isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
629 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
630 with no transaction id`
635 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
636 // FIXME: Implement OCPP version agnostic helpers
637 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
640 this.getConnectorStatus(connectorId
).transactionId
,
643 this.ocppRequestService
644 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
646 RequestCommand
.METER_VALUES
,
649 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
650 meterValue
: [meterValue
],
655 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
662 `${this.logPrefix()} Charging station ${
663 StandardParametersKey.MeterValueSampleInterval
664 } configuration set to ${interval}, not sending MeterValues`
669 public stopMeterValues(connectorId
: number) {
670 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
671 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
675 public start(): void {
676 if (this.started
=== false) {
677 if (this.starting
=== false) {
678 this.starting
= true;
679 if (this.getEnableStatistics() === true) {
680 this.performanceStatistics
?.start();
682 if (this.hasFeatureProfile(SupportedFeatureProfiles
.Reservation
)) {
683 this.startReservationExpirationSetInterval();
685 this.openWSConnection();
686 // Monitor charging station template file
687 this.templateFileWatcher
= watchJsonFile(
689 FileType
.ChargingStationTemplate
,
692 (event
, filename
): void => {
693 if (isNotEmptyString(filename
) && event
=== 'change') {
696 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
698 } file have changed, reload`
700 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
703 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
));
705 this.stopAutomaticTransactionGenerator();
706 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
707 this.startAutomaticTransactionGenerator();
709 if (this.getEnableStatistics() === true) {
710 this.performanceStatistics
?.restart();
712 this.performanceStatistics
?.stop();
714 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
717 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
725 parentPort
?.postMessage(buildStartedMessage(this));
726 this.starting
= false;
728 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
731 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
735 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
736 if (this.started
=== true) {
737 if (this.stopping
=== false) {
738 this.stopping
= true;
739 await this.stopMessageSequence(reason
);
740 this.closeWSConnection();
741 if (this.getEnableStatistics() === true) {
742 this.performanceStatistics
?.stop();
744 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
745 this.templateFileWatcher
?.close();
746 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
747 delete this.bootNotificationResponse
;
748 this.started
= false;
749 this.saveConfiguration();
750 parentPort
?.postMessage(buildStoppedMessage(this));
751 this.stopping
= false;
753 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
756 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
760 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
761 await this.stop(reason
);
762 await sleep(this.stationInfo
.resetTime
);
767 public saveOcppConfiguration(): void {
768 if (this.getOcppPersistentConfiguration()) {
769 this.saveConfiguration();
773 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
774 return ChargingStationConfigurationUtils
.getConfigurationKey(
776 StandardParametersKey
.SupportedFeatureProfiles
777 )?.value
?.includes(featureProfile
);
780 public bufferMessage(message
: string): void {
781 this.messageBuffer
.add(message
);
784 public openWSConnection(
785 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
786 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
788 terminateOpened
: false,
791 options
= { handshakeTimeout
: this.getConnectionTimeout() * 1000, ...options
};
792 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
793 if (this.started
=== false && this.starting
=== false) {
795 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()}
796 on stopped charging station`
801 !isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
802 !isNullOrUndefined(this.stationInfo
.supervisionPassword
)
804 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
806 if (params
?.closeOpened
) {
807 this.closeWSConnection();
809 if (params
?.terminateOpened
) {
810 this.terminateWSConnection();
813 if (this.isWebSocketConnectionOpened() === true) {
815 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()}
822 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
825 this.wsConnection
= new WebSocket(
826 this.wsConnectionUrl
,
827 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
831 // Handle WebSocket message
832 this.wsConnection
.on(
834 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
836 // Handle WebSocket error
837 this.wsConnection
.on(
839 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
841 // Handle WebSocket close
842 this.wsConnection
.on(
844 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
846 // Handle WebSocket open
847 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
848 // Handle WebSocket ping
849 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
850 // Handle WebSocket pong
851 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
854 public closeWSConnection(): void {
855 if (this.isWebSocketConnectionOpened() === true) {
856 this.wsConnection
?.close();
857 this.wsConnection
= null;
861 public getAutomaticTransactionGeneratorConfiguration():
862 | AutomaticTransactionGeneratorConfiguration
864 let automaticTransactionGeneratorConfiguration
:
865 | AutomaticTransactionGeneratorConfiguration
867 const automaticTransactionGeneratorConfigurationFromFile
=
868 this.getConfigurationFromFile()?.automaticTransactionGenerator
;
870 this.getAutomaticTransactionGeneratorPersistentConfiguration() &&
871 automaticTransactionGeneratorConfigurationFromFile
873 automaticTransactionGeneratorConfiguration
=
874 automaticTransactionGeneratorConfigurationFromFile
;
876 automaticTransactionGeneratorConfiguration
=
877 this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
880 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
881 ...automaticTransactionGeneratorConfiguration
,
885 public getAutomaticTransactionGeneratorStatuses(): Status
[] | undefined {
886 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
;
889 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
890 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
891 if (isNotEmptyArray(connectorIds
)) {
892 for (const connectorId
of connectorIds
) {
893 this.automaticTransactionGenerator
?.startConnector(connectorId
);
896 this.automaticTransactionGenerator
?.start();
898 this.saveAutomaticTransactionGeneratorConfiguration();
899 parentPort
?.postMessage(buildUpdatedMessage(this));
902 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
903 if (isNotEmptyArray(connectorIds
)) {
904 for (const connectorId
of connectorIds
) {
905 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
908 this.automaticTransactionGenerator
?.stop();
910 this.saveAutomaticTransactionGeneratorConfiguration();
911 parentPort
?.postMessage(buildUpdatedMessage(this));
914 public async stopTransactionOnConnector(
916 reason
= StopTransactionReason
.NONE
917 ): Promise
<StopTransactionResponse
> {
918 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
920 this.getBeginEndMeterValues() === true &&
921 this.getOcppStrictCompliance() === true &&
922 this.getOutOfOrderEndMeterValues() === false
924 // FIXME: Implement OCPP version agnostic helpers
925 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
928 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
930 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
932 RequestCommand
.METER_VALUES
,
936 meterValue
: [transactionEndMeterValue
],
940 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
942 RequestCommand
.STOP_TRANSACTION
,
945 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
951 public getReservationOnConnectorId0Enabled(): boolean {
952 return convertToBoolean(
953 ChargingStationConfigurationUtils
.getConfigurationKey(
955 StandardParametersKey
.ReserveConnectorZeroSupported
960 public async addReservation(reservation
: Reservation
): Promise
<void> {
961 const [exists
, reservationFound
] = this.doesReservationExists(reservation
);
963 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
);
965 this.getConnectorStatus(reservation
.connectorId
).reservation
= reservation
;
966 await OCPPServiceUtils
.sendAndSetConnectorStatus(
968 reservation
.connectorId
,
969 ConnectorStatusEnum
.Reserved
,
971 { send
: reservation
.connectorId
!== 0 }
975 public async removeReservation(
976 reservation
: Reservation
,
977 reason
?: ReservationTerminationReason
979 const connector
= this.getConnectorStatus(reservation
.connectorId
);
981 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
982 delete connector
.reservation
;
984 case ReservationTerminationReason
.TRANSACTION_STARTED
:
985 delete connector
.reservation
;
987 case ReservationTerminationReason
.RESERVATION_CANCELED
:
988 case ReservationTerminationReason
.REPLACE_EXISTING
:
989 case ReservationTerminationReason
.EXPIRED
:
990 await OCPPServiceUtils
.sendAndSetConnectorStatus(
992 reservation
.connectorId
,
993 ConnectorStatusEnum
.Available
,
995 { send
: reservation
.connectorId
!== 0 }
997 delete connector
.reservation
;
1004 public getReservationBy(
1005 filterKey
: ReservationFilterKey
,
1006 value
: number | string
1007 ): Reservation
| undefined {
1008 if (this.hasEvses
) {
1009 for (const evseStatus
of this.evses
.values()) {
1010 for (const connectorStatus
of evseStatus
.connectors
.values()) {
1011 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
1012 return connectorStatus
.reservation
;
1017 for (const connectorStatus
of this.connectors
.values()) {
1018 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
1019 return connectorStatus
.reservation
;
1025 public doesReservationExists(reservation
: Partial
<Reservation
>): [boolean, Reservation
] {
1026 const foundReservation
= this.getReservationBy(
1027 ReservationFilterKey
.RESERVATION_ID
,
1030 return isUndefined(foundReservation
) ? [false, null] : [true, foundReservation
];
1033 public startReservationExpirationSetInterval(customInterval
?: number): void {
1035 customInterval
?? Constants
.DEFAULT_RESERVATION_EXPIRATION_OBSERVATION_INTERVAL
;
1037 `${this.logPrefix()} Reservation expiration date interval is set to ${interval}
1038 and starts on charging station now`
1040 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1041 this.reservationExpirationSetInterval
= setInterval(async (): Promise
<void> => {
1042 const now
= new Date();
1043 if (this.hasEvses
) {
1044 for (const evseStatus
of this.evses
.values()) {
1045 for (const connectorStatus
of evseStatus
.connectors
.values()) {
1046 if (connectorStatus
?.reservation
?.expiryDate
< now
) {
1047 await this.removeReservation(
1048 connectorStatus
.reservation
,
1049 ReservationTerminationReason
.EXPIRED
1055 for (const connectorStatus
of this.connectors
.values()) {
1056 if (connectorStatus
?.reservation
?.expiryDate
< now
) {
1057 await this.removeReservation(
1058 connectorStatus
.reservation
,
1059 ReservationTerminationReason
.EXPIRED
1067 public restartReservationExpiryDateSetInterval(): void {
1068 this.stopReservationExpirationSetInterval();
1069 this.startReservationExpirationSetInterval();
1072 public validateIncomingRequestWithReservation(connectorId
: number, idTag
: string): boolean {
1073 return this.getReservationBy(ReservationFilterKey
.CONNECTOR_ID
, connectorId
)?.idTag
=== idTag
;
1076 public isConnectorReservable(
1077 reservationId
: number,
1079 connectorId
?: number
1081 const [alreadyExists
] = this.doesReservationExists({ id
: reservationId
});
1082 if (alreadyExists
) {
1083 return alreadyExists
;
1085 const userReservedAlready
= isUndefined(
1086 this.getReservationBy(ReservationFilterKey
.ID_TAG
, idTag
)
1090 const notConnectorZero
= isUndefined(connectorId
) ? true : connectorId
> 0;
1091 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0;
1092 return !alreadyExists
&& !userReservedAlready
&& notConnectorZero
&& freeConnectorsAvailable
;
1095 private getNumberOfReservableConnectors(): number {
1096 let reservableConnectors
= 0;
1097 if (this.hasEvses
) {
1098 for (const evseStatus
of this.evses
.values()) {
1099 reservableConnectors
+= countReservableConnectors(evseStatus
.connectors
);
1102 reservableConnectors
= countReservableConnectors(this.connectors
);
1104 return reservableConnectors
- this.getNumberOfReservationsOnConnectorZero();
1107 private getNumberOfReservationsOnConnectorZero(): number {
1108 let numberOfReservations
= 0;
1109 if (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
) {
1110 ++numberOfReservations
;
1111 } else if (this.connectors
.get(0)?.reservation
) {
1112 ++numberOfReservations
;
1114 return numberOfReservations
;
1117 private flushMessageBuffer(): void {
1118 if (this.messageBuffer
.size
> 0) {
1119 for (const message
of this.messageBuffer
.values()) {
1120 let beginId
: string;
1121 let commandName
: RequestCommand
;
1122 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
1123 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
1125 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
1126 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
1128 this.wsConnection
?.send(message
);
1129 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
1131 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
1133 )} payload sent: ${message}`
1135 this.messageBuffer
.delete(message
);
1140 private getSupervisionUrlOcppConfiguration(): boolean {
1141 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
1144 private stopReservationExpirationSetInterval(): void {
1145 if (this.reservationExpirationSetInterval
) {
1146 clearInterval(this.reservationExpirationSetInterval
);
1150 private getSupervisionUrlOcppKey(): string {
1151 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
1154 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
1155 let template
: ChargingStationTemplate
;
1157 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1158 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
1160 const measureId
= `${FileType.ChargingStationTemplate} read`;
1161 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1162 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
1163 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1164 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1165 .update(JSON
.stringify(template
))
1167 this.sharedLRUCache
.setChargingStationTemplate(template
);
1168 this.templateFileHash
= template
.templateHash
;
1171 handleFileException(
1173 FileType
.ChargingStationTemplate
,
1174 error
as NodeJS
.ErrnoException
,
1181 private getStationInfoFromTemplate(): ChargingStationInfo
{
1182 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
1183 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1184 warnTemplateKeysDeprecation(stationTemplate
, this.logPrefix(), this.templateFile
);
1185 if (stationTemplate
?.Connectors
) {
1186 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1188 const stationInfo
: ChargingStationInfo
= stationTemplateToStationInfo(stationTemplate
);
1189 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
);
1190 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
);
1191 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
1192 createSerialNumber(stationTemplate
, stationInfo
);
1193 if (isNotEmptyArray(stationTemplate
?.power
)) {
1194 stationTemplate
.power
= stationTemplate
.power
as number[];
1195 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
);
1196 stationInfo
.maximumPower
=
1197 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1198 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1199 : stationTemplate
.power
[powerArrayRandomIndex
];
1201 stationTemplate
.power
= stationTemplate
?.power
as number;
1202 stationInfo
.maximumPower
=
1203 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1204 ? stationTemplate
.power
* 1000
1205 : stationTemplate
.power
;
1207 stationInfo
.firmwareVersionPattern
=
1208 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
1210 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1211 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
1214 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1216 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1219 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1226 stationTemplate
?.firmwareUpgrade
?? {}
1228 stationInfo
.resetTime
= !isNullOrUndefined(stationTemplate
?.resetTime
)
1229 ? stationTemplate
.resetTime
* 1000
1230 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1231 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1235 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
1236 let stationInfo
: ChargingStationInfo
| undefined;
1237 if (this.getStationInfoPersistentConfiguration()) {
1238 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1240 delete stationInfo
?.infoHash
;
1246 private getStationInfo(): ChargingStationInfo
{
1247 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1248 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
1250 // 1. charging station info from template
1251 // 2. charging station info from configuration file
1252 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1253 return stationInfoFromFile
;
1255 stationInfoFromFile
&&
1256 propagateSerialNumber(
1257 this.getTemplateFromFile(),
1258 stationInfoFromFile
,
1259 stationInfoFromTemplate
1261 return stationInfoFromTemplate
;
1264 private saveStationInfo(): void {
1265 if (this.getStationInfoPersistentConfiguration()) {
1266 this.saveConfiguration();
1270 private getOcppPersistentConfiguration(): boolean {
1271 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1274 private getStationInfoPersistentConfiguration(): boolean {
1275 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1278 private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean {
1279 return this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
?? true;
1282 private handleUnsupportedVersion(version
: OCPPVersion
) {
1283 const errorMsg
= `Unsupported protocol version '${version}' configured
1284 in template file ${this.templateFile}`;
1285 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1286 throw new BaseError(errorMsg
);
1289 private initialize(): void {
1290 const stationTemplate
= this.getTemplateFromFile();
1291 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1292 this.configurationFile
= join(
1293 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1294 `${getHashId(this.index, stationTemplate)}.json`
1296 const chargingStationConfiguration
= this.getConfigurationFromFile();
1298 chargingStationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
1299 (chargingStationConfiguration
?.connectorsStatus
|| chargingStationConfiguration
?.evsesStatus
)
1301 this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration
);
1303 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1305 this.stationInfo
= this.getStationInfo();
1307 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1308 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1309 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1311 const patternGroup
: number | undefined =
1312 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1313 this.stationInfo
.firmwareVersion
?.split('.').length
;
1314 const match
= this.stationInfo
?.firmwareVersion
1315 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1316 ?.slice(1, patternGroup
+ 1);
1317 const patchLevelIndex
= match
.length
- 1;
1318 match
[patchLevelIndex
] = (
1319 convertToInt(match
[patchLevelIndex
]) +
1320 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1322 this.stationInfo
.firmwareVersion
= match
?.join('.');
1324 this.saveStationInfo();
1325 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1326 if (this.getEnableStatistics() === true) {
1327 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1328 this.stationInfo
.hashId
,
1329 this.stationInfo
.chargingStationId
,
1330 this.configuredSupervisionUrl
1333 this.bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
);
1334 this.powerDivider
= this.getPowerDivider();
1335 // OCPP configuration
1336 this.ocppConfiguration
= this.getOcppConfiguration();
1337 this.initializeOcppConfiguration();
1338 this.initializeOcppServices();
1339 if (this.stationInfo
?.autoRegister
=== true) {
1340 this.bootNotificationResponse
= {
1341 currentTime
: new Date(),
1342 interval
: this.getHeartbeatInterval() / 1000,
1343 status: RegistrationStatusEnumType
.ACCEPTED
,
1348 private initializeOcppServices(): void {
1349 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1350 switch (ocppVersion
) {
1351 case OCPPVersion
.VERSION_16
:
1352 this.ocppIncomingRequestService
=
1353 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1354 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1355 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1358 case OCPPVersion
.VERSION_20
:
1359 case OCPPVersion
.VERSION_201
:
1360 this.ocppIncomingRequestService
=
1361 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1362 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1363 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1367 this.handleUnsupportedVersion(ocppVersion
);
1372 private initializeOcppConfiguration(): void {
1374 !ChargingStationConfigurationUtils
.getConfigurationKey(
1376 StandardParametersKey
.HeartbeatInterval
1379 ChargingStationConfigurationUtils
.addConfigurationKey(
1381 StandardParametersKey
.HeartbeatInterval
,
1386 !ChargingStationConfigurationUtils
.getConfigurationKey(
1388 StandardParametersKey
.HeartBeatInterval
1391 ChargingStationConfigurationUtils
.addConfigurationKey(
1393 StandardParametersKey
.HeartBeatInterval
,
1399 this.getSupervisionUrlOcppConfiguration() &&
1400 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1401 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1403 ChargingStationConfigurationUtils
.addConfigurationKey(
1405 this.getSupervisionUrlOcppKey(),
1406 this.configuredSupervisionUrl
.href
,
1410 !this.getSupervisionUrlOcppConfiguration() &&
1411 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1412 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1414 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1416 this.getSupervisionUrlOcppKey(),
1421 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1422 !ChargingStationConfigurationUtils
.getConfigurationKey(
1424 this.stationInfo
.amperageLimitationOcppKey
1427 ChargingStationConfigurationUtils
.addConfigurationKey(
1429 this.stationInfo
.amperageLimitationOcppKey
,
1431 this.stationInfo
.maximumAmperage
* getAmperageLimitationUnitDivider(this.stationInfo
)
1436 !ChargingStationConfigurationUtils
.getConfigurationKey(
1438 StandardParametersKey
.SupportedFeatureProfiles
1441 ChargingStationConfigurationUtils
.addConfigurationKey(
1443 StandardParametersKey
.SupportedFeatureProfiles
,
1444 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1447 ChargingStationConfigurationUtils
.addConfigurationKey(
1449 StandardParametersKey
.NumberOfConnectors
,
1450 this.getNumberOfConnectors().toString(),
1455 !ChargingStationConfigurationUtils
.getConfigurationKey(
1457 StandardParametersKey
.MeterValuesSampledData
1460 ChargingStationConfigurationUtils
.addConfigurationKey(
1462 StandardParametersKey
.MeterValuesSampledData
,
1463 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1467 !ChargingStationConfigurationUtils
.getConfigurationKey(
1469 StandardParametersKey
.ConnectorPhaseRotation
1472 const connectorsPhaseRotation
: string[] = [];
1473 if (this.hasEvses
) {
1474 for (const evseStatus
of this.evses
.values()) {
1475 for (const connectorId
of evseStatus
.connectors
.keys()) {
1476 connectorsPhaseRotation
.push(
1477 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1482 for (const connectorId
of this.connectors
.keys()) {
1483 connectorsPhaseRotation
.push(
1484 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1488 ChargingStationConfigurationUtils
.addConfigurationKey(
1490 StandardParametersKey
.ConnectorPhaseRotation
,
1491 connectorsPhaseRotation
.toString()
1495 !ChargingStationConfigurationUtils
.getConfigurationKey(
1497 StandardParametersKey
.AuthorizeRemoteTxRequests
1500 ChargingStationConfigurationUtils
.addConfigurationKey(
1502 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1507 !ChargingStationConfigurationUtils
.getConfigurationKey(
1509 StandardParametersKey
.LocalAuthListEnabled
1511 ChargingStationConfigurationUtils
.getConfigurationKey(
1513 StandardParametersKey
.SupportedFeatureProfiles
1514 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1516 ChargingStationConfigurationUtils
.addConfigurationKey(
1518 StandardParametersKey
.LocalAuthListEnabled
,
1523 !ChargingStationConfigurationUtils
.getConfigurationKey(
1525 StandardParametersKey
.ConnectionTimeOut
1528 ChargingStationConfigurationUtils
.addConfigurationKey(
1530 StandardParametersKey
.ConnectionTimeOut
,
1531 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1534 this.saveOcppConfiguration();
1537 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1538 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1539 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1540 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1542 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1543 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1544 const evseStatus
= cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1545 delete evseStatus
.connectorsStatus
;
1546 this.evses
.set(evseId
, {
1547 ...(evseStatus
as EvseStatus
),
1548 connectors
: new Map
<number, ConnectorStatus
>(
1549 evseStatusConfiguration
.connectorsStatus
.map((connectorStatus
, connectorId
) => [
1556 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1557 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1558 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1559 throw new BaseError(errorMsg
);
1561 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1562 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1563 throw new BaseError(errorMsg
);
1567 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1568 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1569 this.initializeConnectorsFromTemplate(stationTemplate
);
1570 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1571 this.initializeEvsesFromTemplate(stationTemplate
);
1572 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1573 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1574 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1575 throw new BaseError(errorMsg
);
1577 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1578 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1579 throw new BaseError(errorMsg
);
1583 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1584 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1585 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1586 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1587 throw new BaseError(errorMsg
);
1589 if (!stationTemplate
?.Connectors
[0]) {
1591 `${this.logPrefix()} Charging station information from template ${
1593 } with no connector id 0 configuration`
1596 if (stationTemplate
?.Connectors
) {
1597 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1598 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1599 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1601 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`
1604 const connectorsConfigChanged
=
1605 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1606 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1607 connectorsConfigChanged
&& this.connectors
.clear();
1608 this.connectorsConfigurationHash
= connectorsConfigHash
;
1609 if (templateMaxConnectors
> 0) {
1610 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1612 connectorId
=== 0 &&
1613 (!stationTemplate
?.Connectors
[connectorId
] ||
1614 this.getUseConnectorId0(stationTemplate
) === false)
1618 const templateConnectorId
=
1619 connectorId
> 0 && stationTemplate
?.randomConnectors
1620 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1622 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1623 checkStationInfoConnectorStatus(
1624 templateConnectorId
,
1629 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1631 initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1632 this.saveConnectorsStatus();
1635 `${this.logPrefix()} Charging station information from template ${
1637 } with no connectors configuration defined, cannot create connectors`
1643 `${this.logPrefix()} Charging station information from template ${
1645 } with no connectors configuration defined, using already defined connectors`
1650 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1651 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1652 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1653 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1654 throw new BaseError(errorMsg
);
1656 if (!stationTemplate
?.Evses
[0]) {
1658 `${this.logPrefix()} Charging station information from template ${
1660 } with no evse id 0 configuration`
1663 if (!stationTemplate
?.Evses
[0]?.Connectors
[0]) {
1665 `${this.logPrefix()} Charging station information from template ${
1667 } with evse id 0 with no connector id 0 configuration`
1670 if (stationTemplate
?.Evses
) {
1671 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1672 .update(JSON
.stringify(stationTemplate
?.Evses
))
1674 const evsesConfigChanged
=
1675 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1676 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1677 evsesConfigChanged
&& this.evses
.clear();
1678 this.evsesConfigurationHash
= evsesConfigHash
;
1679 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
?.Evses
);
1680 if (templateMaxEvses
> 0) {
1681 for (const evse
in stationTemplate
.Evses
) {
1682 const evseId
= convertToInt(evse
);
1683 this.evses
.set(evseId
, {
1684 connectors
: buildConnectorsMap(
1685 stationTemplate
?.Evses
[evse
]?.Connectors
,
1689 availability
: AvailabilityType
.Operative
,
1691 initializeConnectorsMapStatus(this.evses
.get(evseId
)?.connectors
, this.logPrefix());
1693 this.saveEvsesStatus();
1696 `${this.logPrefix()} Charging station information from template ${
1698 } with no evses configuration defined, cannot create evses`
1704 `${this.logPrefix()} Charging station information from template ${
1706 } with no evses configuration defined, using already defined evses`
1711 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1712 let configuration
: ChargingStationConfiguration
| undefined;
1713 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1715 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1716 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1717 this.configurationFileHash
1720 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1721 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1722 configuration
= JSON
.parse(
1723 readFileSync(this.configurationFile
, 'utf8')
1724 ) as ChargingStationConfiguration
;
1725 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1726 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1727 this.configurationFileHash
= configuration
.configurationHash
;
1730 handleFileException(
1731 this.configurationFile
,
1732 FileType
.ChargingStationConfiguration
,
1733 error
as NodeJS
.ErrnoException
,
1738 return configuration
;
1741 private saveAutomaticTransactionGeneratorConfiguration(): void {
1742 if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) {
1743 this.saveConfiguration();
1747 private saveConnectorsStatus() {
1748 this.saveConfiguration();
1751 private saveEvsesStatus() {
1752 this.saveConfiguration();
1755 private saveConfiguration(): void {
1756 if (isNotEmptyString(this.configurationFile
)) {
1758 if (!existsSync(dirname(this.configurationFile
))) {
1759 mkdirSync(dirname(this.configurationFile
), { recursive
: true });
1761 let configurationData
: ChargingStationConfiguration
=
1762 cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()) ?? {};
1763 if (this.getStationInfoPersistentConfiguration() && this.stationInfo
) {
1764 configurationData
.stationInfo
= this.stationInfo
;
1766 delete configurationData
.stationInfo
;
1768 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration
?.configurationKey
) {
1769 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1771 delete configurationData
.configurationKey
;
1773 configurationData
= merge
<ChargingStationConfiguration
>(
1775 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1778 !this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
1779 !this.getAutomaticTransactionGeneratorConfiguration()
1781 delete configurationData
.automaticTransactionGenerator
;
1783 if (this.connectors
.size
> 0) {
1784 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1786 delete configurationData
.connectorsStatus
;
1788 if (this.evses
.size
> 0) {
1789 configurationData
.evsesStatus
= buildEvsesStatus(this);
1791 delete configurationData
.evsesStatus
;
1793 delete configurationData
.configurationHash
;
1794 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1797 stationInfo
: configurationData
.stationInfo
,
1798 configurationKey
: configurationData
.configurationKey
,
1799 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1800 } as ChargingStationConfiguration
)
1803 if (this.configurationFileHash
!== configurationHash
) {
1804 AsyncLock
.acquire(AsyncLockType
.configuration
)
1806 configurationData
.configurationHash
= configurationHash
;
1807 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1808 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1809 const fileDescriptor
= openSync(this.configurationFile
, 'w');
1810 writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1811 closeSync(fileDescriptor
);
1812 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1813 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1814 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1815 this.configurationFileHash
= configurationHash
;
1818 handleFileException(
1819 this.configurationFile
,
1820 FileType
.ChargingStationConfiguration
,
1821 error
as NodeJS
.ErrnoException
,
1826 AsyncLock
.release(AsyncLockType
.configuration
).catch(Constants
.EMPTY_FUNCTION
);
1830 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1831 this.configurationFile
1836 handleFileException(
1837 this.configurationFile
,
1838 FileType
.ChargingStationConfiguration
,
1839 error
as NodeJS
.ErrnoException
,
1845 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1850 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1851 return this.getTemplateFromFile()?.Configuration
;
1854 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1855 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1856 if (this.getOcppPersistentConfiguration() === true && configurationKey
) {
1857 return { configurationKey
};
1862 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1863 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1864 this.getOcppConfigurationFromFile();
1865 if (!ocppConfiguration
) {
1866 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1868 return ocppConfiguration
;
1871 private async onOpen(): Promise
<void> {
1872 if (this.isWebSocketConnectionOpened() === true) {
1874 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1876 if (this.isRegistered() === false) {
1877 // Send BootNotification
1878 let registrationRetryCount
= 0;
1880 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1881 BootNotificationRequest
,
1882 BootNotificationResponse
1883 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1884 skipBufferingOnError
: true,
1886 if (this.isRegistered() === false) {
1887 this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount
;
1889 this?.bootNotificationResponse
?.interval
1890 ? this.bootNotificationResponse
.interval
* 1000
1891 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1895 this.isRegistered() === false &&
1896 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1897 this.getRegistrationMaxRetries() === -1)
1900 if (this.isRegistered() === true) {
1901 if (this.inAcceptedState() === true) {
1902 await this.startMessageSequence();
1906 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1909 this.wsConnectionRestarted
= false;
1910 this.autoReconnectRetryCount
= 0;
1911 parentPort
?.postMessage(buildUpdatedMessage(this));
1914 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1919 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1922 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1923 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1925 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1927 )}' and reason '${reason.toString()}'`
1929 this.autoReconnectRetryCount
= 0;
1934 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1936 )}' and reason '${reason.toString()}'`
1938 this.started
=== true && (await this.reconnect());
1941 parentPort
?.postMessage(buildUpdatedMessage(this));
1944 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1945 const cachedRequest
= this.requests
.get(messageId
);
1946 if (Array.isArray(cachedRequest
) === true) {
1947 return cachedRequest
;
1949 throw new OCPPError(
1950 ErrorType
.PROTOCOL_ERROR
,
1951 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1953 )} is not an array`,
1955 cachedRequest
as JsonType
1959 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1960 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1961 if (this.getEnableStatistics() === true) {
1962 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1965 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1969 // Process the message
1970 await this.ocppIncomingRequestService
.incomingRequestHandler(
1978 private handleResponseMessage(response
: Response
): void {
1979 const [messageType
, messageId
, commandPayload
] = response
;
1980 if (this.requests
.has(messageId
) === false) {
1982 throw new OCPPError(
1983 ErrorType
.INTERNAL_ERROR
,
1984 `Response for unknown message id ${messageId}`,
1990 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1995 `${this.logPrefix()} << Command '${
1996 requestCommandName ?? Constants.UNKNOWN_COMMAND
1997 }' received response payload: ${JSON.stringify(response)}`
1999 responseCallback(commandPayload
, requestPayload
);
2002 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
2003 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
2004 if (this.requests
.has(messageId
) === false) {
2006 throw new OCPPError(
2007 ErrorType
.INTERNAL_ERROR
,
2008 `Error response for unknown message id ${messageId}`,
2010 { errorType
, errorMessage
, errorDetails
}
2013 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
2015 `${this.logPrefix()} << Command '${
2016 requestCommandName ?? Constants.UNKNOWN_COMMAND
2017 }' received error response payload: ${JSON.stringify(errorResponse)}`
2019 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
2022 private async onMessage(data
: RawData
): Promise
<void> {
2023 let request
: IncomingRequest
| Response
| ErrorResponse
;
2024 let messageType
: number;
2025 let errorMsg
: string;
2027 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
2028 if (Array.isArray(request
) === true) {
2029 [messageType
] = request
;
2030 // Check the type of message
2031 switch (messageType
) {
2033 case MessageType
.CALL_MESSAGE
:
2034 await this.handleIncomingMessage(request
as IncomingRequest
);
2037 case MessageType
.CALL_RESULT_MESSAGE
:
2038 this.handleResponseMessage(request
as Response
);
2041 case MessageType
.CALL_ERROR_MESSAGE
:
2042 this.handleErrorMessage(request
as ErrorResponse
);
2046 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2047 errorMsg
= `Wrong message type ${messageType}`;
2048 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2049 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
2051 parentPort
?.postMessage(buildUpdatedMessage(this));
2053 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
2058 let commandName
: IncomingRequestCommand
;
2059 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
2060 let errorCallback
: ErrorCallback
;
2061 const [, messageId
] = request
;
2062 switch (messageType
) {
2063 case MessageType
.CALL_MESSAGE
:
2064 [, , commandName
] = request
as IncomingRequest
;
2066 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
2068 case MessageType
.CALL_RESULT_MESSAGE
:
2069 case MessageType
.CALL_ERROR_MESSAGE
:
2070 if (this.requests
.has(messageId
) === true) {
2071 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
2072 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
2073 errorCallback(error
as OCPPError
, false);
2075 // Remove the request from the cache in case of error at response handling
2076 this.requests
.delete(messageId
);
2080 if (error
instanceof OCPPError
=== false) {
2082 `${this.logPrefix()} Error thrown at incoming OCPP command '${
2083 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2084 }' message '${data.toString()}' handling is not an OCPPError:`,
2089 `${this.logPrefix()} Incoming OCPP command '${
2090 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2091 }' message '${data.toString()}'${
2092 messageType !== MessageType.CALL_MESSAGE
2093 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
2095 } processing error:`,
2101 private onPing(): void {
2102 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
2105 private onPong(): void {
2106 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
2109 private onError(error
: WSError
): void {
2110 this.closeWSConnection();
2111 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
2114 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
2115 if (this.getMeteringPerTransaction() === true) {
2118 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
2119 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2124 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
2125 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2129 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
2130 return stationTemplate
?.useConnectorId0
?? true;
2133 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
2134 if (this.hasEvses
) {
2135 for (const [evseId
, evseStatus
] of this.evses
) {
2139 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2140 if (connectorStatus
.transactionStarted
=== true) {
2141 await this.stopTransactionOnConnector(connectorId
, reason
);
2146 for (const connectorId
of this.connectors
.keys()) {
2147 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2148 await this.stopTransactionOnConnector(connectorId
, reason
);
2155 private getConnectionTimeout(): number {
2157 ChargingStationConfigurationUtils
.getConfigurationKey(
2159 StandardParametersKey
.ConnectionTimeOut
2164 ChargingStationConfigurationUtils
.getConfigurationKey(
2166 StandardParametersKey
.ConnectionTimeOut
2168 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
2171 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
2174 // -1 for unlimited, 0 for disabling
2175 private getAutoReconnectMaxRetries(): number | undefined {
2177 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
2182 private getRegistrationMaxRetries(): number | undefined {
2183 return this.stationInfo
.registrationMaxRetries
?? -1;
2186 private getPowerDivider(): number {
2187 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
2188 if (this.stationInfo
?.powerSharedByConnectors
) {
2189 powerDivider
= this.getNumberOfRunningTransactions();
2191 return powerDivider
;
2194 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
2195 const maximumPower
= this.getMaximumPower(stationInfo
);
2196 switch (this.getCurrentOutType(stationInfo
)) {
2197 case CurrentType
.AC
:
2198 return ACElectricUtils
.amperagePerPhaseFromPower(
2199 this.getNumberOfPhases(stationInfo
),
2200 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2201 this.getVoltageOut(stationInfo
)
2203 case CurrentType
.DC
:
2204 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
2208 private getAmperageLimitation(): number | undefined {
2210 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2211 ChargingStationConfigurationUtils
.getConfigurationKey(
2213 this.stationInfo
.amperageLimitationOcppKey
2218 ChargingStationConfigurationUtils
.getConfigurationKey(
2220 this.stationInfo
.amperageLimitationOcppKey
2222 ) / getAmperageLimitationUnitDivider(this.stationInfo
)
2227 private async startMessageSequence(): Promise
<void> {
2228 if (this.stationInfo
?.autoRegister
=== true) {
2229 await this.ocppRequestService
.requestHandler
<
2230 BootNotificationRequest
,
2231 BootNotificationResponse
2232 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2233 skipBufferingOnError
: true,
2236 // Start WebSocket ping
2237 this.startWebSocketPing();
2239 this.startHeartbeat();
2240 // Initialize connectors status
2241 if (this.hasEvses
) {
2242 for (const [evseId
, evseStatus
] of this.evses
) {
2244 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2245 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
);
2246 await OCPPServiceUtils
.sendAndSetConnectorStatus(
2249 connectorBootStatus
,
2256 for (const connectorId
of this.connectors
.keys()) {
2257 if (connectorId
> 0) {
2258 const connectorBootStatus
= getBootConnectorStatus(
2261 this.getConnectorStatus(connectorId
)
2263 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2267 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2268 await this.ocppRequestService
.requestHandler
<
2269 FirmwareStatusNotificationRequest
,
2270 FirmwareStatusNotificationResponse
2271 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2272 status: FirmwareStatus
.Installed
,
2274 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2278 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2279 this.startAutomaticTransactionGenerator();
2281 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2284 private async stopMessageSequence(
2285 reason
: StopTransactionReason
= StopTransactionReason
.NONE
2287 // Stop WebSocket ping
2288 this.stopWebSocketPing();
2290 this.stopHeartbeat();
2291 // Stop ongoing transactions
2292 if (this.automaticTransactionGenerator
?.started
=== true) {
2293 this.stopAutomaticTransactionGenerator();
2295 await this.stopRunningTransactions(reason
);
2297 if (this.hasEvses
) {
2298 for (const [evseId
, evseStatus
] of this.evses
) {
2300 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2301 await this.ocppRequestService
.requestHandler
<
2302 StatusNotificationRequest
,
2303 StatusNotificationResponse
2306 RequestCommand
.STATUS_NOTIFICATION
,
2307 OCPPServiceUtils
.buildStatusNotificationRequest(
2310 ConnectorStatusEnum
.Unavailable
,
2314 delete connectorStatus
?.status;
2319 for (const connectorId
of this.connectors
.keys()) {
2320 if (connectorId
> 0) {
2321 await this.ocppRequestService
.requestHandler
<
2322 StatusNotificationRequest
,
2323 StatusNotificationResponse
2326 RequestCommand
.STATUS_NOTIFICATION
,
2327 OCPPServiceUtils
.buildStatusNotificationRequest(
2330 ConnectorStatusEnum
.Unavailable
2333 delete this.getConnectorStatus(connectorId
)?.status;
2339 private startWebSocketPing(): void {
2340 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
2342 StandardParametersKey
.WebSocketPingInterval
2345 ChargingStationConfigurationUtils
.getConfigurationKey(
2347 StandardParametersKey
.WebSocketPingInterval
2351 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2352 this.webSocketPingSetInterval
= setInterval(() => {
2353 if (this.isWebSocketConnectionOpened() === true) {
2354 this.wsConnection
?.ping();
2356 }, webSocketPingInterval
* 1000);
2358 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2359 webSocketPingInterval
2362 } else if (this.webSocketPingSetInterval
) {
2364 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2365 webSocketPingInterval
2370 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2375 private stopWebSocketPing(): void {
2376 if (this.webSocketPingSetInterval
) {
2377 clearInterval(this.webSocketPingSetInterval
);
2378 delete this.webSocketPingSetInterval
;
2382 private getConfiguredSupervisionUrl(): URL
{
2383 let configuredSupervisionUrl
: string;
2384 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2385 if (isNotEmptyArray(supervisionUrls
)) {
2386 let configuredSupervisionUrlIndex
: number;
2387 switch (Configuration
.getSupervisionUrlDistribution()) {
2388 case SupervisionUrlDistribution
.RANDOM
:
2389 configuredSupervisionUrlIndex
= Math.floor(secureRandom() * supervisionUrls
.length
);
2391 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2392 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2394 Object.values(SupervisionUrlDistribution
).includes(
2395 Configuration
.getSupervisionUrlDistribution()
2398 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2399 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2402 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2405 configuredSupervisionUrl
= supervisionUrls
[configuredSupervisionUrlIndex
];
2407 configuredSupervisionUrl
= supervisionUrls
as string;
2409 if (isNotEmptyString(configuredSupervisionUrl
)) {
2410 return new URL(configuredSupervisionUrl
);
2412 const errorMsg
= 'No supervision url(s) configured';
2413 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2414 throw new BaseError(`${errorMsg}`);
2417 private stopHeartbeat(): void {
2418 if (this.heartbeatSetInterval
) {
2419 clearInterval(this.heartbeatSetInterval
);
2420 delete this.heartbeatSetInterval
;
2424 private terminateWSConnection(): void {
2425 if (this.isWebSocketConnectionOpened() === true) {
2426 this.wsConnection
?.terminate();
2427 this.wsConnection
= null;
2431 private getReconnectExponentialDelay(): boolean {
2432 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2435 private async reconnect(): Promise
<void> {
2436 // Stop WebSocket ping
2437 this.stopWebSocketPing();
2439 this.stopHeartbeat();
2440 // Stop the ATG if needed
2441 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
=== true) {
2442 this.stopAutomaticTransactionGenerator();
2445 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2446 this.getAutoReconnectMaxRetries() === -1
2448 ++this.autoReconnectRetryCount
;
2449 const reconnectDelay
= this.getReconnectExponentialDelay()
2450 ? exponentialDelay(this.autoReconnectRetryCount
)
2451 : this.getConnectionTimeout() * 1000;
2452 const reconnectDelayWithdraw
= 1000;
2453 const reconnectTimeout
=
2454 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2455 ? reconnectDelay
- reconnectDelayWithdraw
2458 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2461 )}ms, timeout ${reconnectTimeout}ms`
2463 await sleep(reconnectDelay
);
2465 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2467 this.openWSConnection(
2469 ...(this.stationInfo
?.wsOptions
?? {}),
2470 handshakeTimeout
: reconnectTimeout
,
2472 { closeOpened
: true }
2474 this.wsConnectionRestarted
= true;
2475 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2477 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2478 this.autoReconnectRetryCount
2479 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`