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';
24 deleteConfigurationKey
,
26 setConfigurationKeyValue
,
27 } from
'./ChargingStationConfigurationUtils';
30 checkConnectorsConfiguration
,
31 checkStationInfoConnectorStatus
,
33 countReservableConnectors
,
34 createBootNotificationRequest
,
36 getAmperageLimitationUnitDivider
,
37 getBootConnectorStatus
,
38 getChargingStationConnectorChargingProfilesPowerLimit
,
44 getPhaseRotationValue
,
45 initializeConnectorsMapStatus
,
46 propagateSerialNumber
,
47 stationTemplateToStationInfo
,
48 warnTemplateKeysDeprecation
,
49 } from
'./ChargingStationUtils';
50 import { IdTagsCache
} from
'./IdTagsCache';
52 OCPP16IncomingRequestService
,
54 OCPP16ResponseService
,
56 OCPP20IncomingRequestService
,
58 OCPP20ResponseService
,
59 type OCPPIncomingRequestService
,
60 type OCPPRequestService
,
63 import { SharedLRUCache
} from
'./SharedLRUCache';
64 import { BaseError
, OCPPError
} from
'../exception';
65 import { PerformanceStatistics
} from
'../performance';
67 type AutomaticTransactionGeneratorConfiguration
,
69 type BootNotificationRequest
,
70 type BootNotificationResponse
,
72 type ChargingStationConfiguration
,
73 type ChargingStationInfo
,
74 type ChargingStationOcppConfiguration
,
75 type ChargingStationTemplate
,
83 type EvseStatusConfiguration
,
86 type FirmwareStatusNotificationRequest
,
87 type FirmwareStatusNotificationResponse
,
89 type HeartbeatRequest
,
90 type HeartbeatResponse
,
92 type IncomingRequestCommand
,
97 type MeterValuesRequest
,
98 type MeterValuesResponse
,
100 type OutgoingRequest
,
102 RegistrationStatusEnumType
,
105 ReservationFilterKey
,
106 ReservationTerminationReason
,
108 StandardParametersKey
,
110 type StatusNotificationRequest
,
111 type StatusNotificationResponse
,
112 StopTransactionReason
,
113 type StopTransactionRequest
,
114 type StopTransactionResponse
,
115 SupervisionUrlDistribution
,
116 SupportedFeatureProfiles
,
119 WebSocketCloseEventStatusCode
,
129 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
130 buildConnectorsStatus
,
139 formatDurationMilliSeconds
,
140 formatDurationSeconds
,
142 getWebSocketCloseEventStatusString
,
156 export class ChargingStation
{
157 public readonly index
: number;
158 public readonly templateFile
: string;
159 public stationInfo
!: ChargingStationInfo
;
160 public started
: boolean;
161 public starting
: boolean;
162 public idTagsCache
: IdTagsCache
;
163 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
164 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
165 public wsConnection
!: WebSocket
| null;
166 public readonly connectors
: Map
<number, ConnectorStatus
>;
167 public readonly evses
: Map
<number, EvseStatus
>;
168 public readonly requests
: Map
<string, CachedRequest
>;
169 public performanceStatistics
!: PerformanceStatistics
| undefined;
170 public heartbeatSetInterval
?: NodeJS
.Timeout
;
171 public ocppRequestService
!: OCPPRequestService
;
172 public bootNotificationRequest
!: BootNotificationRequest
;
173 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
174 public powerDivider
!: number;
175 private stopping
: boolean;
176 private configurationFile
!: string;
177 private configurationFileHash
!: string;
178 private connectorsConfigurationHash
!: string;
179 private evsesConfigurationHash
!: string;
180 private automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
;
181 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
182 private readonly messageBuffer
: Set
<string>;
183 private configuredSupervisionUrl
!: URL
;
184 private wsConnectionRestarted
: boolean;
185 private autoReconnectRetryCount
: number;
186 private templateFileWatcher
!: FSWatcher
| undefined;
187 private templateFileHash
!: string;
188 private readonly sharedLRUCache
: SharedLRUCache
;
189 private webSocketPingSetInterval
?: NodeJS
.Timeout
;
190 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
191 private reservationExpirationSetInterval
?: NodeJS
.Timeout
;
193 constructor(index
: number, templateFile
: string) {
194 this.started
= false;
195 this.starting
= false;
196 this.stopping
= false;
197 this.wsConnectionRestarted
= false;
198 this.autoReconnectRetryCount
= 0;
200 this.templateFile
= templateFile
;
201 this.connectors
= new Map
<number, ConnectorStatus
>();
202 this.evses
= new Map
<number, EvseStatus
>();
203 this.requests
= new Map
<string, CachedRequest
>();
204 this.messageBuffer
= new Set
<string>();
205 this.sharedLRUCache
= SharedLRUCache
.getInstance();
206 this.idTagsCache
= IdTagsCache
.getInstance();
207 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
212 public get
hasEvses(): boolean {
213 return this.connectors
.size
=== 0 && this.evses
.size
> 0;
216 private get
wsConnectionUrl(): URL
{
219 this.getSupervisionUrlOcppConfiguration() &&
220 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
221 isNotEmptyString(getConfigurationKey(this, this.getSupervisionUrlOcppKey())?.value)
222 ? getConfigurationKey(this, this.getSupervisionUrlOcppKey())!.value
223 : this.configuredSupervisionUrl.href
224 }/${this.stationInfo.chargingStationId}`,
228 public logPrefix
= (): string => {
231 (isNotEmptyString(this?.stationInfo?.chargingStationId)
232 ? this?.stationInfo?.chargingStationId
233 : getChargingStationId(this.index, this.getTemplateFromFile()!)) ??
234 'Error at building log prefix'
239 public hasIdTags(): boolean {
240 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
)!));
243 public getEnableStatistics(): boolean {
244 return this.stationInfo
.enableStatistics
?? false;
247 public getMustAuthorizeAtRemoteStart(): boolean {
248 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
251 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number {
252 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
253 switch (this.getCurrentOutType(stationInfo
)) {
255 return !isUndefined(localStationInfo
.numberOfPhases
) ? localStationInfo
.numberOfPhases
! : 3;
261 public isWebSocketConnectionOpened(): boolean {
262 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
265 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
266 return this?.bootNotificationResponse
?.status;
269 public inUnknownState(): boolean {
270 return isNullOrUndefined(this?.bootNotificationResponse
?.status);
273 public inPendingState(): boolean {
274 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
277 public inAcceptedState(): boolean {
278 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
281 public inRejectedState(): boolean {
282 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
285 public isRegistered(): boolean {
287 this.inUnknownState() === false &&
288 (this.inAcceptedState() === true || this.inPendingState() === true)
292 public isChargingStationAvailable(): boolean {
293 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
296 public hasConnector(connectorId
: number): boolean {
298 for (const evseStatus
of this.evses
.values()) {
299 if (evseStatus
.connectors
.has(connectorId
)) {
305 return this.connectors
.has(connectorId
);
308 public isConnectorAvailable(connectorId
: number): boolean {
311 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
315 public getNumberOfConnectors(): number {
317 let numberOfConnectors
= 0;
318 for (const [evseId
, evseStatus
] of this.evses
) {
320 numberOfConnectors
+= evseStatus
.connectors
.size
;
323 return numberOfConnectors
;
325 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
328 public getNumberOfEvses(): number {
329 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
332 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
334 for (const evseStatus
of this.evses
.values()) {
335 if (evseStatus
.connectors
.has(connectorId
)) {
336 return evseStatus
.connectors
.get(connectorId
);
341 return this.connectors
.get(connectorId
);
344 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
345 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
348 public getOcppStrictCompliance(): boolean {
349 return this.stationInfo
?.ocppStrictCompliance
?? true;
352 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number {
353 const defaultVoltageOut
= getDefaultVoltageOut(
354 this.getCurrentOutType(stationInfo
),
358 return (stationInfo
?? this.stationInfo
).voltageOut
?? defaultVoltageOut
;
361 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
362 const localStationInfo
= stationInfo
?? this.stationInfo
;
363 // eslint-disable-next-line @typescript-eslint/dot-notation
365 (localStationInfo
['maxPower' as keyof ChargingStationInfo
] as number) ??
366 localStationInfo
.maximumPower
370 public getConnectorMaximumAvailablePower(connectorId
: number): number {
371 let connectorAmperageLimitationPowerLimit
: number | undefined;
373 !isNullOrUndefined(this.getAmperageLimitation()) &&
374 this.getAmperageLimitation()! < this.stationInfo
.maximumAmperage
!
376 connectorAmperageLimitationPowerLimit
=
377 (this.getCurrentOutType() === CurrentType
.AC
378 ? ACElectricUtils
.powerTotal(
379 this.getNumberOfPhases(),
380 this.getVoltageOut(),
381 this.getAmperageLimitation()! *
382 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
384 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation()!)) /
387 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
388 const connectorChargingProfilesPowerLimit
=
389 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
391 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
392 isNaN(connectorAmperageLimitationPowerLimit
!)
394 : connectorAmperageLimitationPowerLimit
!,
395 isNaN(connectorChargingProfilesPowerLimit
!) ? Infinity : connectorChargingProfilesPowerLimit
!,
399 public getTransactionIdTag(transactionId
: number): string | undefined {
401 for (const evseStatus
of this.evses
.values()) {
402 for (const connectorStatus
of evseStatus
.connectors
.values()) {
403 if (connectorStatus
.transactionId
=== transactionId
) {
404 return connectorStatus
.transactionIdTag
;
409 for (const connectorId
of this.connectors
.keys()) {
410 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
411 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
417 public getNumberOfRunningTransactions(): number {
420 for (const [evseId
, evseStatus
] of this.evses
) {
424 for (const connectorStatus
of evseStatus
.connectors
.values()) {
425 if (connectorStatus
.transactionStarted
=== true) {
431 for (const connectorId
of this.connectors
.keys()) {
432 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
440 public getOutOfOrderEndMeterValues(): boolean {
441 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
444 public getBeginEndMeterValues(): boolean {
445 return this.stationInfo
?.beginEndMeterValues
?? false;
448 public getMeteringPerTransaction(): boolean {
449 return this.stationInfo
?.meteringPerTransaction
?? true;
452 public getTransactionDataMeterValues(): boolean {
453 return this.stationInfo
?.transactionDataMeterValues
?? false;
456 public getMainVoltageMeterValues(): boolean {
457 return this.stationInfo
?.mainVoltageMeterValues
?? true;
460 public getPhaseLineToLineVoltageMeterValues(): boolean {
461 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
464 public getCustomValueLimitationMeterValues(): boolean {
465 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
468 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
470 for (const evseStatus
of this.evses
.values()) {
471 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
472 if (connectorStatus
.transactionId
=== transactionId
) {
478 for (const connectorId
of this.connectors
.keys()) {
479 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
486 public getEnergyActiveImportRegisterByTransactionId(
487 transactionId
: number,
490 return this.getEnergyActiveImportRegister(
491 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!)!,
496 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
497 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
)!, rounded
);
500 public getAuthorizeRemoteTxRequests(): boolean {
501 const authorizeRemoteTxRequests
= getConfigurationKey(
503 StandardParametersKey
.AuthorizeRemoteTxRequests
,
505 return authorizeRemoteTxRequests
? convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
508 public getLocalAuthListEnabled(): boolean {
509 const localAuthListEnabled
= getConfigurationKey(
511 StandardParametersKey
.LocalAuthListEnabled
,
513 return localAuthListEnabled
? convertToBoolean(localAuthListEnabled
.value
) : false;
516 public getHeartbeatInterval(): number {
517 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
);
518 if (HeartbeatInterval
) {
519 return convertToInt(HeartbeatInterval
.value
) * 1000;
521 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
);
522 if (HeartBeatInterval
) {
523 return convertToInt(HeartBeatInterval
.value
) * 1000;
525 this.stationInfo
?.autoRegister
=== false &&
527 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
528 Constants.DEFAULT_HEARTBEAT_INTERVAL
531 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
534 public setSupervisionUrl(url
: string): void {
536 this.getSupervisionUrlOcppConfiguration() &&
537 isNotEmptyString(this.getSupervisionUrlOcppKey())
539 setConfigurationKeyValue(this, this.getSupervisionUrlOcppKey(), url
);
541 this.stationInfo
.supervisionUrls
= url
;
542 this.saveStationInfo();
543 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
547 public startHeartbeat(): void {
548 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
549 this.heartbeatSetInterval
= setInterval(() => {
550 this.ocppRequestService
551 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
554 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
558 }, this.getHeartbeatInterval());
560 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
561 this.getHeartbeatInterval(),
564 } else if (this.heartbeatSetInterval
) {
566 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
567 this.getHeartbeatInterval(),
572 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()},
573 not starting the heartbeat`,
578 public restartHeartbeat(): void {
580 this.stopHeartbeat();
582 this.startHeartbeat();
585 public restartWebSocketPing(): void {
586 // Stop WebSocket ping
587 this.stopWebSocketPing();
588 // Start WebSocket ping
589 this.startWebSocketPing();
592 public startMeterValues(connectorId
: number, interval
: number): void {
593 if (connectorId
=== 0) {
595 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`,
599 if (!this.getConnectorStatus(connectorId
)) {
601 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
602 ${connectorId.toString()}`,
606 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
608 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
609 with no transaction started`,
613 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
614 isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
617 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
618 with no transaction id`,
623 this.getConnectorStatus(connectorId
)!.transactionSetInterval
= setInterval(() => {
624 // FIXME: Implement OCPP version agnostic helpers
625 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
628 this.getConnectorStatus(connectorId
)!.transactionId
!,
631 this.ocppRequestService
632 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
634 RequestCommand
.METER_VALUES
,
637 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
638 meterValue
: [meterValue
],
643 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
650 `${this.logPrefix()} Charging station ${
651 StandardParametersKey.MeterValueSampleInterval
652 } configuration set to ${interval}, not sending MeterValues`,
657 public stopMeterValues(connectorId
: number) {
658 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
659 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
663 public start(): void {
664 if (this.started
=== false) {
665 if (this.starting
=== false) {
666 this.starting
= true;
667 if (this.getEnableStatistics() === true) {
668 this.performanceStatistics
?.start();
670 if (this.hasFeatureProfile(SupportedFeatureProfiles
.Reservation
)) {
671 this.startReservationExpirationSetInterval();
673 this.openWSConnection();
674 // Monitor charging station template file
675 this.templateFileWatcher
= watchJsonFile(
677 FileType
.ChargingStationTemplate
,
680 (event
, filename
): void => {
681 if (isNotEmptyString(filename
) && event
=== 'change') {
684 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
686 } file have changed, reload`,
688 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
691 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
)!);
693 this.stopAutomaticTransactionGenerator();
694 delete this.automaticTransactionGeneratorConfiguration
;
695 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
696 this.startAutomaticTransactionGenerator();
698 if (this.getEnableStatistics() === true) {
699 this.performanceStatistics
?.restart();
701 this.performanceStatistics
?.stop();
703 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
706 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
714 parentPort
?.postMessage(buildStartedMessage(this));
715 this.starting
= false;
717 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
720 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
724 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
725 if (this.started
=== true) {
726 if (this.stopping
=== false) {
727 this.stopping
= true;
728 await this.stopMessageSequence(reason
);
729 this.closeWSConnection();
730 if (this.getEnableStatistics() === true) {
731 this.performanceStatistics
?.stop();
733 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
734 this.templateFileWatcher
?.close();
735 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
736 delete this.bootNotificationResponse
;
737 this.started
= false;
738 this.saveConfiguration();
739 parentPort
?.postMessage(buildStoppedMessage(this));
740 this.stopping
= false;
742 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
745 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
749 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
750 await this.stop(reason
);
751 await sleep(this.stationInfo
.resetTime
!);
756 public saveOcppConfiguration(): void {
757 if (this.getOcppPersistentConfiguration()) {
758 this.saveConfiguration();
762 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
763 return getConfigurationKey(
765 StandardParametersKey
.SupportedFeatureProfiles
,
766 )?.value
?.includes(featureProfile
);
769 public bufferMessage(message
: string): void {
770 this.messageBuffer
.add(message
);
773 public openWSConnection(
774 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
775 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
777 terminateOpened
: false,
780 options
= { handshakeTimeout
: this.getConnectionTimeout() * 1000, ...options
};
781 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
782 if (this.started
=== false && this.starting
=== false) {
784 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()}
785 on stopped charging station`,
790 !isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
791 !isNullOrUndefined(this.stationInfo
.supervisionPassword
)
793 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
795 if (params
?.closeOpened
) {
796 this.closeWSConnection();
798 if (params
?.terminateOpened
) {
799 this.terminateWSConnection();
802 if (this.isWebSocketConnectionOpened() === true) {
804 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()}
811 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`,
814 this.wsConnection
= new WebSocket(
815 this.wsConnectionUrl
,
816 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
820 // Handle WebSocket message
821 this.wsConnection
.on(
823 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void,
825 // Handle WebSocket error
826 this.wsConnection
.on(
828 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void,
830 // Handle WebSocket close
831 this.wsConnection
.on(
833 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void,
835 // Handle WebSocket open
836 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
837 // Handle WebSocket ping
838 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
839 // Handle WebSocket pong
840 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
843 public closeWSConnection(): void {
844 if (this.isWebSocketConnectionOpened() === true) {
845 this.wsConnection
?.close();
846 this.wsConnection
= null;
850 public getAutomaticTransactionGeneratorConfiguration(): AutomaticTransactionGeneratorConfiguration
{
851 if (isNullOrUndefined(this.automaticTransactionGeneratorConfiguration
)) {
852 let automaticTransactionGeneratorConfiguration
:
853 | AutomaticTransactionGeneratorConfiguration
855 const automaticTransactionGeneratorConfigurationFromFile
=
856 this.getConfigurationFromFile()?.automaticTransactionGenerator
;
858 this.getAutomaticTransactionGeneratorPersistentConfiguration() &&
859 automaticTransactionGeneratorConfigurationFromFile
861 automaticTransactionGeneratorConfiguration
=
862 automaticTransactionGeneratorConfigurationFromFile
;
864 automaticTransactionGeneratorConfiguration
=
865 this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
867 this.automaticTransactionGeneratorConfiguration
= {
868 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
869 ...automaticTransactionGeneratorConfiguration
,
872 return this.automaticTransactionGeneratorConfiguration
!;
875 public getAutomaticTransactionGeneratorStatuses(): Status
[] | undefined {
876 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
;
879 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
880 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
881 if (isNotEmptyArray(connectorIds
)) {
882 for (const connectorId
of connectorIds
!) {
883 this.automaticTransactionGenerator
?.startConnector(connectorId
);
886 this.automaticTransactionGenerator
?.start();
888 this.saveAutomaticTransactionGeneratorConfiguration();
889 parentPort
?.postMessage(buildUpdatedMessage(this));
892 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
893 if (isNotEmptyArray(connectorIds
)) {
894 for (const connectorId
of connectorIds
!) {
895 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
898 this.automaticTransactionGenerator
?.stop();
900 this.saveAutomaticTransactionGeneratorConfiguration();
901 parentPort
?.postMessage(buildUpdatedMessage(this));
904 public async stopTransactionOnConnector(
906 reason
= StopTransactionReason
.NONE
,
907 ): Promise
<StopTransactionResponse
> {
908 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
910 this.getBeginEndMeterValues() === true &&
911 this.getOcppStrictCompliance() === true &&
912 this.getOutOfOrderEndMeterValues() === false
914 // FIXME: Implement OCPP version agnostic helpers
915 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
918 this.getEnergyActiveImportRegisterByTransactionId(transactionId
!),
920 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
922 RequestCommand
.METER_VALUES
,
926 meterValue
: [transactionEndMeterValue
],
930 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
932 RequestCommand
.STOP_TRANSACTION
,
935 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
!, true),
941 public getReservationOnConnectorId0Enabled(): boolean {
942 return convertToBoolean(
943 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
,
947 public async addReservation(reservation
: Reservation
): Promise
<void> {
948 const [exists
, reservationFound
] = this.doesReservationExists(reservation
);
950 await this.removeReservation(
952 ReservationTerminationReason
.REPLACE_EXISTING
,
955 this.getConnectorStatus(reservation
.connectorId
)!.reservation
= reservation
;
956 await OCPPServiceUtils
.sendAndSetConnectorStatus(
958 reservation
.connectorId
,
959 ConnectorStatusEnum
.Reserved
,
961 { send
: reservation
.connectorId
!== 0 },
965 public async removeReservation(
966 reservation
: Reservation
,
967 reason
?: ReservationTerminationReason
,
969 const connector
= this.getConnectorStatus(reservation
.connectorId
)!;
971 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
972 delete connector
.reservation
;
974 case ReservationTerminationReason
.TRANSACTION_STARTED
:
975 delete connector
.reservation
;
977 case ReservationTerminationReason
.RESERVATION_CANCELED
:
978 case ReservationTerminationReason
.REPLACE_EXISTING
:
979 case ReservationTerminationReason
.EXPIRED
:
980 await OCPPServiceUtils
.sendAndSetConnectorStatus(
982 reservation
.connectorId
,
983 ConnectorStatusEnum
.Available
,
985 { send
: reservation
.connectorId
!== 0 },
987 delete connector
.reservation
;
994 public getReservationBy(
995 filterKey
: ReservationFilterKey
,
996 value
: number | string,
997 ): Reservation
| undefined {
999 for (const evseStatus
of this.evses
.values()) {
1000 for (const connectorStatus
of evseStatus
.connectors
.values()) {
1001 if (connectorStatus
?.reservation
?.[filterKey
as keyof Reservation
] === value
) {
1002 return connectorStatus
.reservation
;
1007 for (const connectorStatus
of this.connectors
.values()) {
1008 if (connectorStatus
?.reservation
?.[filterKey
as keyof Reservation
] === value
) {
1009 return connectorStatus
.reservation
;
1015 public doesReservationExists(
1016 reservation
: Partial
<Reservation
>,
1017 ): [boolean, Reservation
| undefined] {
1018 const foundReservation
= this.getReservationBy(
1019 ReservationFilterKey
.RESERVATION_ID
,
1022 return isUndefined(foundReservation
) ? [false, undefined] : [true, foundReservation
];
1025 public startReservationExpirationSetInterval(customInterval
?: number): void {
1027 customInterval
?? Constants
.DEFAULT_RESERVATION_EXPIRATION_OBSERVATION_INTERVAL
;
1029 `${this.logPrefix()} Reservation expiration date interval is set to ${interval}
1030 and starts on charging station now`,
1033 this.reservationExpirationSetInterval
= setInterval((): void => {
1034 const currentDate
= new Date();
1035 if (this.hasEvses
) {
1036 for (const evseStatus
of this.evses
.values()) {
1037 for (const connectorStatus
of evseStatus
.connectors
.values()) {
1039 connectorStatus
.reservation
&&
1040 connectorStatus
.reservation
.expiryDate
< currentDate
1042 this.removeReservation(
1043 connectorStatus
.reservation
,
1044 ReservationTerminationReason
.EXPIRED
,
1045 ).catch(Constants
.EMPTY_FUNCTION
);
1050 for (const connectorStatus
of this.connectors
.values()) {
1052 connectorStatus
.reservation
&&
1053 connectorStatus
.reservation
.expiryDate
< currentDate
1055 this.removeReservation(
1056 connectorStatus
.reservation
,
1057 ReservationTerminationReason
.EXPIRED
,
1058 ).catch(Constants
.EMPTY_FUNCTION
);
1066 public restartReservationExpiryDateSetInterval(): void {
1067 this.stopReservationExpirationSetInterval();
1068 this.startReservationExpirationSetInterval();
1071 public validateIncomingRequestWithReservation(connectorId
: number, idTag
: string): boolean {
1072 return this.getReservationBy(ReservationFilterKey
.CONNECTOR_ID
, connectorId
)?.idTag
=== idTag
;
1075 public isConnectorReservable(
1076 reservationId
: number,
1078 connectorId
?: number,
1080 const [alreadyExists
] = this.doesReservationExists({ id
: reservationId
});
1081 if (alreadyExists
) {
1082 return alreadyExists
;
1084 const userReservedAlready
= isUndefined(
1085 this.getReservationBy(ReservationFilterKey
.ID_TAG
, idTag
!),
1089 const notConnectorZero
= isUndefined(connectorId
) ? true : connectorId
! > 0;
1090 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0;
1091 return !alreadyExists
&& !userReservedAlready
&& notConnectorZero
&& freeConnectorsAvailable
;
1094 private getNumberOfReservableConnectors(): number {
1095 let reservableConnectors
= 0;
1096 if (this.hasEvses
) {
1097 for (const evseStatus
of this.evses
.values()) {
1098 reservableConnectors
+= countReservableConnectors(evseStatus
.connectors
);
1101 reservableConnectors
= countReservableConnectors(this.connectors
);
1103 return reservableConnectors
- this.getNumberOfReservationsOnConnectorZero();
1106 private getNumberOfReservationsOnConnectorZero(): number {
1107 let numberOfReservations
= 0;
1108 if (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
) {
1109 ++numberOfReservations
;
1110 } else if (this.connectors
.get(0)?.reservation
) {
1111 ++numberOfReservations
;
1113 return numberOfReservations
;
1116 private flushMessageBuffer(): void {
1117 if (this.messageBuffer
.size
> 0) {
1118 for (const message
of this.messageBuffer
.values()) {
1119 let beginId
: string | undefined;
1120 let commandName
: RequestCommand
| undefined;
1121 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
1122 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
1124 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
1125 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
1127 this.wsConnection
?.send(message
);
1128 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!);
1130 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
1132 )} payload sent: ${message}`,
1134 this.messageBuffer
.delete(message
);
1139 private getSupervisionUrlOcppConfiguration(): boolean {
1140 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
1143 private stopReservationExpirationSetInterval(): void {
1144 if (this.reservationExpirationSetInterval
) {
1145 clearInterval(this.reservationExpirationSetInterval
);
1149 private getSupervisionUrlOcppKey(): string {
1150 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
1153 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
1154 let template
: ChargingStationTemplate
| undefined;
1156 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1157 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
1159 const measureId
= `${FileType.ChargingStationTemplate} read`;
1160 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1161 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
1162 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1163 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1164 .update(JSON
.stringify(template
))
1166 this.sharedLRUCache
.setChargingStationTemplate(template
);
1167 this.templateFileHash
= template
.templateHash
;
1170 handleFileException(
1172 FileType
.ChargingStationTemplate
,
1173 error
as NodeJS
.ErrnoException
,
1180 private getStationInfoFromTemplate(): ChargingStationInfo
{
1181 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile()!;
1182 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1183 warnTemplateKeysDeprecation(stationTemplate
, this.logPrefix(), this.templateFile
);
1184 if (stationTemplate
?.Connectors
) {
1185 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1187 const stationInfo
: ChargingStationInfo
= stationTemplateToStationInfo(stationTemplate
);
1188 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
);
1189 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
);
1190 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
1191 createSerialNumber(stationTemplate
, stationInfo
);
1192 if (isNotEmptyArray(stationTemplate
?.power
)) {
1193 stationTemplate
.power
= stationTemplate
.power
as number[];
1194 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
);
1195 stationInfo
.maximumPower
=
1196 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1197 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1198 : stationTemplate
.power
[powerArrayRandomIndex
];
1200 stationTemplate
.power
= stationTemplate
?.power
as number;
1201 stationInfo
.maximumPower
=
1202 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1203 ? stationTemplate
.power
* 1000
1204 : stationTemplate
.power
;
1206 stationInfo
.firmwareVersionPattern
=
1207 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
1209 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1210 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
!) === false
1213 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1215 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`,
1218 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1225 stationTemplate
?.firmwareUpgrade
?? {},
1227 stationInfo
.resetTime
= !isNullOrUndefined(stationTemplate
?.resetTime
)
1228 ? stationTemplate
.resetTime
! * 1000
1229 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1230 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1234 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
1235 let stationInfo
: ChargingStationInfo
| undefined;
1236 if (this.getStationInfoPersistentConfiguration()) {
1237 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1239 delete stationInfo
?.infoHash
;
1245 private getStationInfo(): ChargingStationInfo
{
1246 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1247 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
1249 // 1. charging station info from template
1250 // 2. charging station info from configuration file
1251 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1252 return stationInfoFromFile
!;
1254 stationInfoFromFile
&&
1255 propagateSerialNumber(
1256 this.getTemplateFromFile()!,
1257 stationInfoFromFile
,
1258 stationInfoFromTemplate
,
1260 return stationInfoFromTemplate
;
1263 private saveStationInfo(): void {
1264 if (this.getStationInfoPersistentConfiguration()) {
1265 this.saveConfiguration();
1269 private getOcppPersistentConfiguration(): boolean {
1270 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1273 private getStationInfoPersistentConfiguration(): boolean {
1274 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1277 private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean {
1278 return this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
?? true;
1281 private handleUnsupportedVersion(version
: OCPPVersion
) {
1282 const errorMsg
= `Unsupported protocol version '${version}' configured
1283 in template file ${this.templateFile}`;
1284 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1285 throw new BaseError(errorMsg
);
1288 private initialize(): void {
1289 const stationTemplate
= this.getTemplateFromFile()!;
1290 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1291 this.configurationFile
= join(
1292 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1293 `${getHashId(this.index, stationTemplate)}.json`,
1295 const chargingStationConfiguration
= this.getConfigurationFromFile();
1297 chargingStationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
1298 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
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
1315 .firmwareVersion
!.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 {
1373 if (!getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
)) {
1374 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0');
1376 if (!getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
)) {
1377 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false });
1380 this.getSupervisionUrlOcppConfiguration() &&
1381 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1382 !getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1384 addConfigurationKey(
1386 this.getSupervisionUrlOcppKey(),
1387 this.configuredSupervisionUrl
.href
,
1391 !this.getSupervisionUrlOcppConfiguration() &&
1392 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1393 getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1395 deleteConfigurationKey(this, this.getSupervisionUrlOcppKey(), { save
: false });
1398 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1399 !getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)
1401 addConfigurationKey(
1403 this.stationInfo
.amperageLimitationOcppKey
!,
1405 this.stationInfo
.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)
1409 if (!getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
)) {
1410 addConfigurationKey(
1412 StandardParametersKey
.SupportedFeatureProfiles
,
1413 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`,
1416 addConfigurationKey(
1418 StandardParametersKey
.NumberOfConnectors
,
1419 this.getNumberOfConnectors().toString(),
1421 { overwrite
: true },
1423 if (!getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
)) {
1424 addConfigurationKey(
1426 StandardParametersKey
.MeterValuesSampledData
,
1427 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
1430 if (!getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
)) {
1431 const connectorsPhaseRotation
: string[] = [];
1432 if (this.hasEvses
) {
1433 for (const evseStatus
of this.evses
.values()) {
1434 for (const connectorId
of evseStatus
.connectors
.keys()) {
1435 connectorsPhaseRotation
.push(
1436 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1441 for (const connectorId
of this.connectors
.keys()) {
1442 connectorsPhaseRotation
.push(
1443 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1447 addConfigurationKey(
1449 StandardParametersKey
.ConnectorPhaseRotation
,
1450 connectorsPhaseRotation
.toString(),
1453 if (!getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
1454 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1457 !getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
) &&
1458 getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
)?.value
?.includes(
1459 SupportedFeatureProfiles
.LocalAuthListManagement
,
1462 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false');
1464 if (!getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)) {
1465 addConfigurationKey(
1467 StandardParametersKey
.ConnectionTimeOut
,
1468 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString(),
1471 this.saveOcppConfiguration();
1474 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1475 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1476 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1477 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1479 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1480 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1481 const evseStatus
= cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1482 delete evseStatus
.connectorsStatus
;
1483 this.evses
.set(evseId
, {
1484 ...(evseStatus
as EvseStatus
),
1485 connectors
: new Map
<number, ConnectorStatus
>(
1486 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1493 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1494 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1495 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1496 throw new BaseError(errorMsg
);
1498 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1499 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1500 throw new BaseError(errorMsg
);
1504 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1505 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1506 this.initializeConnectorsFromTemplate(stationTemplate
);
1507 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1508 this.initializeEvsesFromTemplate(stationTemplate
);
1509 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1510 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1511 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1512 throw new BaseError(errorMsg
);
1514 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1515 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1516 throw new BaseError(errorMsg
);
1520 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1521 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1522 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1523 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1524 throw new BaseError(errorMsg
);
1526 if (!stationTemplate
?.Connectors
?.[0]) {
1528 `${this.logPrefix()} Charging station information from template ${
1530 } with no connector id 0 configuration`,
1533 if (stationTemplate
?.Connectors
) {
1534 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1535 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1536 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1538 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`,
1541 const connectorsConfigChanged
=
1542 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1543 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1544 connectorsConfigChanged
&& this.connectors
.clear();
1545 this.connectorsConfigurationHash
= connectorsConfigHash
;
1546 if (templateMaxConnectors
> 0) {
1547 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1549 connectorId
=== 0 &&
1550 (!stationTemplate
?.Connectors
[connectorId
] ||
1551 this.getUseConnectorId0(stationTemplate
) === false)
1555 const templateConnectorId
=
1556 connectorId
> 0 && stationTemplate
?.randomConnectors
1557 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1559 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1560 checkStationInfoConnectorStatus(
1561 templateConnectorId
,
1566 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1568 initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1569 this.saveConnectorsStatus();
1572 `${this.logPrefix()} Charging station information from template ${
1574 } with no connectors configuration defined, cannot create connectors`,
1580 `${this.logPrefix()} Charging station information from template ${
1582 } with no connectors configuration defined, using already defined connectors`,
1587 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1588 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1589 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1590 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1591 throw new BaseError(errorMsg
);
1593 if (!stationTemplate
?.Evses
?.[0]) {
1595 `${this.logPrefix()} Charging station information from template ${
1597 } with no evse id 0 configuration`,
1600 if (!stationTemplate
?.Evses
?.[0]?.Connectors
?.[0]) {
1602 `${this.logPrefix()} Charging station information from template ${
1604 } with evse id 0 with no connector id 0 configuration`,
1607 if (stationTemplate
?.Evses
) {
1608 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1609 .update(JSON
.stringify(stationTemplate
?.Evses
))
1611 const evsesConfigChanged
=
1612 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1613 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1614 evsesConfigChanged
&& this.evses
.clear();
1615 this.evsesConfigurationHash
= evsesConfigHash
;
1616 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
?.Evses
);
1617 if (templateMaxEvses
> 0) {
1618 for (const evse
in stationTemplate
.Evses
) {
1619 const evseId
= convertToInt(evse
);
1620 this.evses
.set(evseId
, {
1621 connectors
: buildConnectorsMap(
1622 stationTemplate
?.Evses
[evse
]?.Connectors
,
1626 availability
: AvailabilityType
.Operative
,
1628 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix());
1630 this.saveEvsesStatus();
1633 `${this.logPrefix()} Charging station information from template ${
1635 } with no evses configuration defined, cannot create evses`,
1641 `${this.logPrefix()} Charging station information from template ${
1643 } with no evses configuration defined, using already defined evses`,
1648 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1649 let configuration
: ChargingStationConfiguration
| undefined;
1650 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1652 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1653 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1654 this.configurationFileHash
,
1657 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1658 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1659 configuration
= JSON
.parse(
1660 readFileSync(this.configurationFile
, 'utf8'),
1661 ) as ChargingStationConfiguration
;
1662 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1663 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1664 this.configurationFileHash
= configuration
.configurationHash
!;
1667 handleFileException(
1668 this.configurationFile
,
1669 FileType
.ChargingStationConfiguration
,
1670 error
as NodeJS
.ErrnoException
,
1675 return configuration
;
1678 private saveAutomaticTransactionGeneratorConfiguration(): void {
1679 if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) {
1680 this.saveConfiguration();
1684 private saveConnectorsStatus() {
1685 this.saveConfiguration();
1688 private saveEvsesStatus() {
1689 this.saveConfiguration();
1692 private saveConfiguration(): void {
1693 if (isNotEmptyString(this.configurationFile
)) {
1695 if (!existsSync(dirname(this.configurationFile
))) {
1696 mkdirSync(dirname(this.configurationFile
), { recursive
: true });
1698 let configurationData
: ChargingStationConfiguration
= this.getConfigurationFromFile()
1699 ? cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()!)
1701 if (this.getStationInfoPersistentConfiguration() && this.stationInfo
) {
1702 configurationData
.stationInfo
= this.stationInfo
;
1704 delete configurationData
.stationInfo
;
1706 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration
?.configurationKey
) {
1707 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1709 delete configurationData
.configurationKey
;
1711 configurationData
= merge
<ChargingStationConfiguration
>(
1713 buildChargingStationAutomaticTransactionGeneratorConfiguration(this),
1716 !this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
1717 !this.getAutomaticTransactionGeneratorConfiguration()
1719 delete configurationData
.automaticTransactionGenerator
;
1721 if (this.connectors
.size
> 0) {
1722 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1724 delete configurationData
.connectorsStatus
;
1726 if (this.evses
.size
> 0) {
1727 configurationData
.evsesStatus
= buildEvsesStatus(this);
1729 delete configurationData
.evsesStatus
;
1731 delete configurationData
.configurationHash
;
1732 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1735 stationInfo
: configurationData
.stationInfo
,
1736 configurationKey
: configurationData
.configurationKey
,
1737 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1738 } as ChargingStationConfiguration
),
1741 if (this.configurationFileHash
!== configurationHash
) {
1742 AsyncLock
.acquire(AsyncLockType
.configuration
)
1744 configurationData
.configurationHash
= configurationHash
;
1745 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1746 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1747 const fileDescriptor
= openSync(this.configurationFile
, 'w');
1748 writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1749 closeSync(fileDescriptor
);
1750 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1751 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1752 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1753 this.configurationFileHash
= configurationHash
;
1756 handleFileException(
1757 this.configurationFile
,
1758 FileType
.ChargingStationConfiguration
,
1759 error
as NodeJS
.ErrnoException
,
1764 AsyncLock
.release(AsyncLockType
.configuration
).catch(Constants
.EMPTY_FUNCTION
);
1768 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1769 this.configurationFile
1774 handleFileException(
1775 this.configurationFile
,
1776 FileType
.ChargingStationConfiguration
,
1777 error
as NodeJS
.ErrnoException
,
1783 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`,
1788 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1789 return this.getTemplateFromFile()?.Configuration
;
1792 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1793 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1794 if (this.getOcppPersistentConfiguration() === true && configurationKey
) {
1795 return { configurationKey
};
1800 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1801 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1802 this.getOcppConfigurationFromFile();
1803 if (!ocppConfiguration
) {
1804 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1806 return ocppConfiguration
;
1809 private async onOpen(): Promise
<void> {
1810 if (this.isWebSocketConnectionOpened() === true) {
1812 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`,
1814 if (this.isRegistered() === false) {
1815 // Send BootNotification
1816 let registrationRetryCount
= 0;
1818 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1819 BootNotificationRequest
,
1820 BootNotificationResponse
1821 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1822 skipBufferingOnError
: true,
1824 if (this.isRegistered() === false) {
1825 this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount
;
1827 this?.bootNotificationResponse
?.interval
1828 ? this.bootNotificationResponse
.interval
* 1000
1829 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
,
1833 this.isRegistered() === false &&
1834 (registrationRetryCount
<= this.getRegistrationMaxRetries()! ||
1835 this.getRegistrationMaxRetries() === -1)
1838 if (this.isRegistered() === true) {
1839 if (this.inAcceptedState() === true) {
1840 await this.startMessageSequence();
1844 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`,
1847 this.wsConnectionRestarted
= false;
1848 this.autoReconnectRetryCount
= 0;
1849 parentPort
?.postMessage(buildUpdatedMessage(this));
1852 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`,
1857 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1860 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1861 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1863 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1865 )}' and reason '${reason.toString()}'`,
1867 this.autoReconnectRetryCount
= 0;
1872 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1874 )}' and reason '${reason.toString()}'`,
1876 this.started
=== true && (await this.reconnect());
1879 parentPort
?.postMessage(buildUpdatedMessage(this));
1882 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1883 const cachedRequest
= this.requests
.get(messageId
);
1884 if (Array.isArray(cachedRequest
) === true) {
1885 return cachedRequest
;
1887 throw new OCPPError(
1888 ErrorType
.PROTOCOL_ERROR
,
1889 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1891 )} is not an array`,
1893 cachedRequest
as JsonType
,
1897 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1898 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1899 if (this.getEnableStatistics() === true) {
1900 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1903 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1907 // Process the message
1908 await this.ocppIncomingRequestService
.incomingRequestHandler(
1916 private handleResponseMessage(response
: Response
): void {
1917 const [messageType
, messageId
, commandPayload
] = response
;
1918 if (this.requests
.has(messageId
) === false) {
1920 throw new OCPPError(
1921 ErrorType
.INTERNAL_ERROR
,
1922 `Response for unknown message id ${messageId}`,
1928 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1933 `${this.logPrefix()} << Command '${
1934 requestCommandName ?? Constants.UNKNOWN_COMMAND
1935 }' received response payload: ${JSON.stringify(response)}`,
1937 responseCallback(commandPayload
, requestPayload
);
1940 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1941 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1942 if (this.requests
.has(messageId
) === false) {
1944 throw new OCPPError(
1945 ErrorType
.INTERNAL_ERROR
,
1946 `Error response for unknown message id ${messageId}`,
1948 { errorType
, errorMessage
, errorDetails
},
1951 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
1953 `${this.logPrefix()} << Command '${
1954 requestCommandName ?? Constants.UNKNOWN_COMMAND
1955 }' received error response payload: ${JSON.stringify(errorResponse)}`,
1957 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1960 private async onMessage(data
: RawData
): Promise
<void> {
1961 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined;
1962 let messageType
: number | undefined;
1963 let errorMsg
: string;
1965 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1966 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1967 if (Array.isArray(request
) === true) {
1968 [messageType
] = request
;
1969 // Check the type of message
1970 switch (messageType
) {
1972 case MessageType
.CALL_MESSAGE
:
1973 await this.handleIncomingMessage(request
as IncomingRequest
);
1976 case MessageType
.CALL_RESULT_MESSAGE
:
1977 this.handleResponseMessage(request
as Response
);
1980 case MessageType
.CALL_ERROR_MESSAGE
:
1981 this.handleErrorMessage(request
as ErrorResponse
);
1985 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1986 errorMsg
= `Wrong message type ${messageType}`;
1987 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1988 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
1990 parentPort
?.postMessage(buildUpdatedMessage(this));
1992 throw new OCPPError(
1993 ErrorType
.PROTOCOL_ERROR
,
1994 'Incoming message is not an array',
2002 let commandName
: IncomingRequestCommand
| undefined;
2003 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined;
2004 let errorCallback
: ErrorCallback
;
2005 const [, messageId
] = request
!;
2006 switch (messageType
) {
2007 case MessageType
.CALL_MESSAGE
:
2008 [, , commandName
] = request
as IncomingRequest
;
2010 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
2012 case MessageType
.CALL_RESULT_MESSAGE
:
2013 case MessageType
.CALL_ERROR_MESSAGE
:
2014 if (this.requests
.has(messageId
) === true) {
2015 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
2016 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
2017 errorCallback(error
as OCPPError
, false);
2019 // Remove the request from the cache in case of error at response handling
2020 this.requests
.delete(messageId
);
2024 if (error
instanceof OCPPError
=== false) {
2026 `${this.logPrefix()} Error thrown at incoming OCPP command '${
2027 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2028 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2029 }' message '${data.toString()}' handling is not an OCPPError:`,
2034 `${this.logPrefix()} Incoming OCPP command '${
2035 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2036 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2037 }' message '${data.toString()}'${
2038 messageType !== MessageType.CALL_MESSAGE
2039 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
2041 } processing error:`,
2047 private onPing(): void {
2048 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
2051 private onPong(): void {
2052 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
2055 private onError(error
: WSError
): void {
2056 this.closeWSConnection();
2057 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
2060 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
2061 if (this.getMeteringPerTransaction() === true) {
2064 ? Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
!)
2065 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2070 ? Math.round(connectorStatus
.energyActiveImportRegisterValue
!)
2071 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2075 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
2076 return stationTemplate
?.useConnectorId0
?? true;
2079 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
2080 if (this.hasEvses
) {
2081 for (const [evseId
, evseStatus
] of this.evses
) {
2085 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2086 if (connectorStatus
.transactionStarted
=== true) {
2087 await this.stopTransactionOnConnector(connectorId
, reason
);
2092 for (const connectorId
of this.connectors
.keys()) {
2093 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2094 await this.stopTransactionOnConnector(connectorId
, reason
);
2101 private getConnectionTimeout(): number {
2102 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)) {
2104 parseInt(getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)!.value
!) ??
2105 Constants
.DEFAULT_CONNECTION_TIMEOUT
2108 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
2111 // -1 for unlimited, 0 for disabling
2112 private getAutoReconnectMaxRetries(): number | undefined {
2114 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
2119 private getRegistrationMaxRetries(): number | undefined {
2120 return this.stationInfo
.registrationMaxRetries
?? -1;
2123 private getPowerDivider(): number {
2124 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
2125 if (this.stationInfo
?.powerSharedByConnectors
) {
2126 powerDivider
= this.getNumberOfRunningTransactions();
2128 return powerDivider
;
2131 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
2132 const maximumPower
= this.getMaximumPower(stationInfo
);
2133 switch (this.getCurrentOutType(stationInfo
)) {
2134 case CurrentType
.AC
:
2135 return ACElectricUtils
.amperagePerPhaseFromPower(
2136 this.getNumberOfPhases(stationInfo
),
2137 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2138 this.getVoltageOut(stationInfo
),
2140 case CurrentType
.DC
:
2141 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
2145 private getAmperageLimitation(): number | undefined {
2147 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2148 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)
2152 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)?.value
,
2153 ) / getAmperageLimitationUnitDivider(this.stationInfo
)
2158 private async startMessageSequence(): Promise
<void> {
2159 if (this.stationInfo
?.autoRegister
=== true) {
2160 await this.ocppRequestService
.requestHandler
<
2161 BootNotificationRequest
,
2162 BootNotificationResponse
2163 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2164 skipBufferingOnError
: true,
2167 // Start WebSocket ping
2168 this.startWebSocketPing();
2170 this.startHeartbeat();
2171 // Initialize connectors status
2172 if (this.hasEvses
) {
2173 for (const [evseId
, evseStatus
] of this.evses
) {
2175 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2176 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
);
2177 await OCPPServiceUtils
.sendAndSetConnectorStatus(
2180 connectorBootStatus
,
2187 for (const connectorId
of this.connectors
.keys()) {
2188 if (connectorId
> 0) {
2189 const connectorBootStatus
= getBootConnectorStatus(
2192 this.getConnectorStatus(connectorId
)!,
2194 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2198 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2199 await this.ocppRequestService
.requestHandler
<
2200 FirmwareStatusNotificationRequest
,
2201 FirmwareStatusNotificationResponse
2202 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2203 status: FirmwareStatus
.Installed
,
2205 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2209 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2210 this.startAutomaticTransactionGenerator();
2212 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2215 private async stopMessageSequence(
2216 reason
: StopTransactionReason
= StopTransactionReason
.NONE
,
2218 // Stop WebSocket ping
2219 this.stopWebSocketPing();
2221 this.stopHeartbeat();
2222 // Stop ongoing transactions
2223 if (this.automaticTransactionGenerator
?.started
=== true) {
2224 this.stopAutomaticTransactionGenerator();
2226 await this.stopRunningTransactions(reason
);
2228 if (this.hasEvses
) {
2229 for (const [evseId
, evseStatus
] of this.evses
) {
2231 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2232 await this.ocppRequestService
.requestHandler
<
2233 StatusNotificationRequest
,
2234 StatusNotificationResponse
2237 RequestCommand
.STATUS_NOTIFICATION
,
2238 OCPPServiceUtils
.buildStatusNotificationRequest(
2241 ConnectorStatusEnum
.Unavailable
,
2245 delete connectorStatus
?.status;
2250 for (const connectorId
of this.connectors
.keys()) {
2251 if (connectorId
> 0) {
2252 await this.ocppRequestService
.requestHandler
<
2253 StatusNotificationRequest
,
2254 StatusNotificationResponse
2257 RequestCommand
.STATUS_NOTIFICATION
,
2258 OCPPServiceUtils
.buildStatusNotificationRequest(
2261 ConnectorStatusEnum
.Unavailable
,
2264 delete this.getConnectorStatus(connectorId
)?.status;
2270 private startWebSocketPing(): void {
2271 const webSocketPingInterval
: number = getConfigurationKey(
2273 StandardParametersKey
.WebSocketPingInterval
,
2275 ? convertToInt(getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
)?.value
)
2277 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2278 this.webSocketPingSetInterval
= setInterval(() => {
2279 if (this.isWebSocketConnectionOpened() === true) {
2280 this.wsConnection
?.ping();
2282 }, webSocketPingInterval
* 1000);
2284 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2285 webSocketPingInterval,
2288 } else if (this.webSocketPingSetInterval
) {
2290 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2291 webSocketPingInterval,
2296 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`,
2301 private stopWebSocketPing(): void {
2302 if (this.webSocketPingSetInterval
) {
2303 clearInterval(this.webSocketPingSetInterval
);
2304 delete this.webSocketPingSetInterval
;
2308 private getConfiguredSupervisionUrl(): URL
{
2309 let configuredSupervisionUrl
: string;
2310 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2311 if (isNotEmptyArray(supervisionUrls
)) {
2312 let configuredSupervisionUrlIndex
: number;
2313 switch (Configuration
.getSupervisionUrlDistribution()) {
2314 case SupervisionUrlDistribution
.RANDOM
:
2315 configuredSupervisionUrlIndex
= Math.floor(
2316 secureRandom() * (supervisionUrls
as string[]).length
,
2319 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2320 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2322 Object.values(SupervisionUrlDistribution
).includes(
2323 Configuration
.getSupervisionUrlDistribution()!,
2326 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2327 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2328 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2331 configuredSupervisionUrlIndex
= (this.index
- 1) % (supervisionUrls
as string[]).length
;
2334 configuredSupervisionUrl
= (supervisionUrls
as string[])[configuredSupervisionUrlIndex
];
2336 configuredSupervisionUrl
= supervisionUrls
as string;
2338 if (isNotEmptyString(configuredSupervisionUrl
)) {
2339 return new URL(configuredSupervisionUrl
);
2341 const errorMsg
= 'No supervision url(s) configured';
2342 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2343 throw new BaseError(`${errorMsg}`);
2346 private stopHeartbeat(): void {
2347 if (this.heartbeatSetInterval
) {
2348 clearInterval(this.heartbeatSetInterval
);
2349 delete this.heartbeatSetInterval
;
2353 private terminateWSConnection(): void {
2354 if (this.isWebSocketConnectionOpened() === true) {
2355 this.wsConnection
?.terminate();
2356 this.wsConnection
= null;
2360 private getReconnectExponentialDelay(): boolean {
2361 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2364 private async reconnect(): Promise
<void> {
2365 // Stop WebSocket ping
2366 this.stopWebSocketPing();
2368 this.stopHeartbeat();
2369 // Stop the ATG if needed
2370 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
=== true) {
2371 this.stopAutomaticTransactionGenerator();
2374 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries()! ||
2375 this.getAutoReconnectMaxRetries() === -1
2377 ++this.autoReconnectRetryCount
;
2378 const reconnectDelay
= this.getReconnectExponentialDelay()
2379 ? exponentialDelay(this.autoReconnectRetryCount
)
2380 : this.getConnectionTimeout() * 1000;
2381 const reconnectDelayWithdraw
= 1000;
2382 const reconnectTimeout
=
2383 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2384 ? reconnectDelay
- reconnectDelayWithdraw
2387 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2390 )}ms, timeout ${reconnectTimeout}ms`,
2392 await sleep(reconnectDelay
);
2394 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`,
2396 this.openWSConnection(
2398 ...(this.stationInfo
?.wsOptions
?? {}),
2399 handshakeTimeout
: reconnectTimeout
,
2401 { closeOpened
: true },
2403 this.wsConnectionRestarted
= true;
2404 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2406 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2407 this.autoReconnectRetryCount
2408 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`,