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 { millisecondsToSeconds
, secondsToMilliseconds
} from
'date-fns';
18 import merge from
'just-merge';
19 import { type RawData
, WebSocket
} from
'ws';
21 import { AutomaticTransactionGenerator
} from
'./AutomaticTransactionGenerator';
22 import { ChargingStationWorkerBroadcastChannel
} from
'./broadcast-channel/ChargingStationWorkerBroadcastChannel';
25 deleteConfigurationKey
,
27 setConfigurationKeyValue
,
28 } from
'./ConfigurationKeyUtils';
31 checkConnectorsConfiguration
,
32 checkStationInfoConnectorStatus
,
34 createBootNotificationRequest
,
36 getAmperageLimitationUnitDivider
,
37 getBootConnectorStatus
,
38 getChargingStationConnectorChargingProfilesPowerLimit
,
44 getNumberOfReservableConnectors
,
45 getPhaseRotationValue
,
47 hasReservationExpired
,
48 initializeConnectorsMapStatus
,
49 propagateSerialNumber
,
50 removeExpiredReservations
,
51 stationTemplateToStationInfo
,
52 warnTemplateKeysDeprecation
,
54 import { IdTagsCache
} from
'./IdTagsCache';
56 OCPP16IncomingRequestService
,
58 OCPP16ResponseService
,
60 OCPP20IncomingRequestService
,
62 OCPP20ResponseService
,
63 type OCPPIncomingRequestService
,
64 type OCPPRequestService
,
67 import { SharedLRUCache
} from
'./SharedLRUCache';
68 import { BaseError
, OCPPError
} from
'../exception';
69 import { PerformanceStatistics
} from
'../performance';
71 type AutomaticTransactionGeneratorConfiguration
,
73 type BootNotificationRequest
,
74 type BootNotificationResponse
,
76 type ChargingStationConfiguration
,
77 type ChargingStationInfo
,
78 type ChargingStationOcppConfiguration
,
79 type ChargingStationTemplate
,
87 type EvseStatusConfiguration
,
90 type FirmwareStatusNotificationRequest
,
91 type FirmwareStatusNotificationResponse
,
93 type HeartbeatRequest
,
94 type HeartbeatResponse
,
96 type IncomingRequestCommand
,
101 type MeterValuesRequest
,
102 type MeterValuesResponse
,
104 type OutgoingRequest
,
106 RegistrationStatusEnumType
,
110 ReservationTerminationReason
,
112 StandardParametersKey
,
114 type StatusNotificationRequest
,
115 type StatusNotificationResponse
,
116 StopTransactionReason
,
117 type StopTransactionRequest
,
118 type StopTransactionResponse
,
119 SupervisionUrlDistribution
,
120 SupportedFeatureProfiles
,
123 WebSocketCloseEventStatusCode
,
133 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
134 buildConnectorsStatus
,
143 formatDurationMilliSeconds
,
144 formatDurationSeconds
,
146 getWebSocketCloseEventStatusString
,
160 export class ChargingStation
{
161 public readonly index
: number;
162 public readonly templateFile
: string;
163 public stationInfo
!: ChargingStationInfo
;
164 public started
: boolean;
165 public starting
: boolean;
166 public idTagsCache
: IdTagsCache
;
167 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
168 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
169 public wsConnection
!: WebSocket
| null;
170 public readonly connectors
: Map
<number, ConnectorStatus
>;
171 public readonly evses
: Map
<number, EvseStatus
>;
172 public readonly requests
: Map
<string, CachedRequest
>;
173 public performanceStatistics
!: PerformanceStatistics
| undefined;
174 public heartbeatSetInterval
?: NodeJS
.Timeout
;
175 public ocppRequestService
!: OCPPRequestService
;
176 public bootNotificationRequest
!: BootNotificationRequest
;
177 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
178 public powerDivider
!: number;
179 private stopping
: boolean;
180 private configurationFile
!: string;
181 private configurationFileHash
!: string;
182 private connectorsConfigurationHash
!: string;
183 private evsesConfigurationHash
!: string;
184 private automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
;
185 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
186 private readonly messageBuffer
: Set
<string>;
187 private configuredSupervisionUrl
!: URL
;
188 private wsConnectionRestarted
: boolean;
189 private autoReconnectRetryCount
: number;
190 private templateFileWatcher
!: FSWatcher
| undefined;
191 private templateFileHash
!: string;
192 private readonly sharedLRUCache
: SharedLRUCache
;
193 private webSocketPingSetInterval
?: NodeJS
.Timeout
;
194 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
195 private reservationExpirationSetInterval
?: NodeJS
.Timeout
;
197 constructor(index
: number, templateFile
: string) {
198 this.started
= false;
199 this.starting
= false;
200 this.stopping
= false;
201 this.wsConnectionRestarted
= false;
202 this.autoReconnectRetryCount
= 0;
204 this.templateFile
= templateFile
;
205 this.connectors
= new Map
<number, ConnectorStatus
>();
206 this.evses
= new Map
<number, EvseStatus
>();
207 this.requests
= new Map
<string, CachedRequest
>();
208 this.messageBuffer
= new Set
<string>();
209 this.sharedLRUCache
= SharedLRUCache
.getInstance();
210 this.idTagsCache
= IdTagsCache
.getInstance();
211 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
216 public get
hasEvses(): boolean {
217 return this.connectors
.size
=== 0 && this.evses
.size
> 0;
220 private get
wsConnectionUrl(): URL
{
223 this.getSupervisionUrlOcppConfiguration() &&
224 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
225 isNotEmptyString(getConfigurationKey(this, this.getSupervisionUrlOcppKey())?.value)
226 ? getConfigurationKey(this, this.getSupervisionUrlOcppKey())!.value
227 : this.configuredSupervisionUrl.href
228 }/${this.stationInfo.chargingStationId}`,
232 public logPrefix
= (): string => {
235 (isNotEmptyString(this?.stationInfo?.chargingStationId)
236 ? this?.stationInfo?.chargingStationId
237 : getChargingStationId(this.index, this.getTemplateFromFile()!)) ??
238 'Error at building log prefix'
243 public hasIdTags(): boolean {
244 return isNotEmptyArray(this.idTagsCache
.getIdTags(getIdTagsFile(this.stationInfo
)!));
247 public getEnableStatistics(): boolean {
248 return this.stationInfo
.enableStatistics
?? false;
251 public getRemoteAuthorization(): boolean {
252 return this.stationInfo
.remoteAuthorization
?? true;
255 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number {
256 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
257 switch (this.getCurrentOutType(stationInfo
)) {
259 return !isUndefined(localStationInfo
.numberOfPhases
) ? localStationInfo
.numberOfPhases
! : 3;
265 public isWebSocketConnectionOpened(): boolean {
266 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
269 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
270 return this?.bootNotificationResponse
?.status;
273 public inUnknownState(): boolean {
274 return isNullOrUndefined(this?.bootNotificationResponse
?.status);
277 public inPendingState(): boolean {
278 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
281 public inAcceptedState(): boolean {
282 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
285 public inRejectedState(): boolean {
286 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
289 public isRegistered(): boolean {
291 this.inUnknownState() === false &&
292 (this.inAcceptedState() === true || this.inPendingState() === true)
296 public isChargingStationAvailable(): boolean {
297 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
300 public hasConnector(connectorId
: number): boolean {
302 for (const evseStatus
of this.evses
.values()) {
303 if (evseStatus
.connectors
.has(connectorId
)) {
309 return this.connectors
.has(connectorId
);
312 public isConnectorAvailable(connectorId
: number): boolean {
315 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
319 public getNumberOfConnectors(): number {
321 let numberOfConnectors
= 0;
322 for (const [evseId
, evseStatus
] of this.evses
) {
324 numberOfConnectors
+= evseStatus
.connectors
.size
;
327 return numberOfConnectors
;
329 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
332 public getNumberOfEvses(): number {
333 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
336 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
338 for (const evseStatus
of this.evses
.values()) {
339 if (evseStatus
.connectors
.has(connectorId
)) {
340 return evseStatus
.connectors
.get(connectorId
);
345 return this.connectors
.get(connectorId
);
348 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
349 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
352 public getOcppStrictCompliance(): boolean {
353 return this.stationInfo
?.ocppStrictCompliance
?? true;
356 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number {
357 const defaultVoltageOut
= getDefaultVoltageOut(
358 this.getCurrentOutType(stationInfo
),
362 return (stationInfo
?? this.stationInfo
).voltageOut
?? defaultVoltageOut
;
365 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
366 const localStationInfo
= stationInfo
?? this.stationInfo
;
367 // eslint-disable-next-line @typescript-eslint/dot-notation
369 (localStationInfo
['maxPower' as keyof ChargingStationInfo
] as number) ??
370 localStationInfo
.maximumPower
374 public getConnectorMaximumAvailablePower(connectorId
: number): number {
375 let connectorAmperageLimitationPowerLimit
: number | undefined;
377 !isNullOrUndefined(this.getAmperageLimitation()) &&
378 this.getAmperageLimitation()! < this.stationInfo
.maximumAmperage
!
380 connectorAmperageLimitationPowerLimit
=
381 (this.getCurrentOutType() === CurrentType
.AC
382 ? ACElectricUtils
.powerTotal(
383 this.getNumberOfPhases(),
384 this.getVoltageOut(),
385 this.getAmperageLimitation()! *
386 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
388 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation()!)) /
391 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
392 const connectorChargingProfilesPowerLimit
=
393 getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
395 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
396 isNaN(connectorAmperageLimitationPowerLimit
!)
398 : connectorAmperageLimitationPowerLimit
!,
399 isNaN(connectorChargingProfilesPowerLimit
!) ? Infinity : connectorChargingProfilesPowerLimit
!,
403 public getTransactionIdTag(transactionId
: number): string | undefined {
405 for (const evseStatus
of this.evses
.values()) {
406 for (const connectorStatus
of evseStatus
.connectors
.values()) {
407 if (connectorStatus
.transactionId
=== transactionId
) {
408 return connectorStatus
.transactionIdTag
;
413 for (const connectorId
of this.connectors
.keys()) {
414 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
415 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
421 public getNumberOfRunningTransactions(): number {
422 let numberOfRunningTransactions
= 0;
424 for (const [evseId
, evseStatus
] of this.evses
) {
428 for (const connectorStatus
of evseStatus
.connectors
.values()) {
429 if (connectorStatus
.transactionStarted
=== true) {
430 ++numberOfRunningTransactions
;
435 for (const connectorId
of this.connectors
.keys()) {
436 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
437 ++numberOfRunningTransactions
;
441 return numberOfRunningTransactions
;
444 public getOutOfOrderEndMeterValues(): boolean {
445 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
448 public getBeginEndMeterValues(): boolean {
449 return this.stationInfo
?.beginEndMeterValues
?? false;
452 public getMeteringPerTransaction(): boolean {
453 return this.stationInfo
?.meteringPerTransaction
?? true;
456 public getTransactionDataMeterValues(): boolean {
457 return this.stationInfo
?.transactionDataMeterValues
?? false;
460 public getMainVoltageMeterValues(): boolean {
461 return this.stationInfo
?.mainVoltageMeterValues
?? true;
464 public getPhaseLineToLineVoltageMeterValues(): boolean {
465 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
468 public getCustomValueLimitationMeterValues(): boolean {
469 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
472 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
474 for (const evseStatus
of this.evses
.values()) {
475 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
476 if (connectorStatus
.transactionId
=== transactionId
) {
482 for (const connectorId
of this.connectors
.keys()) {
483 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
490 public getEnergyActiveImportRegisterByTransactionId(
491 transactionId
: number,
494 return this.getEnergyActiveImportRegister(
495 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)!)!,
500 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
501 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
)!, rounded
);
504 public getAuthorizeRemoteTxRequests(): boolean {
505 const authorizeRemoteTxRequests
= getConfigurationKey(
507 StandardParametersKey
.AuthorizeRemoteTxRequests
,
509 return authorizeRemoteTxRequests
? convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
512 public getLocalAuthListEnabled(): boolean {
513 const localAuthListEnabled
= getConfigurationKey(
515 StandardParametersKey
.LocalAuthListEnabled
,
517 return localAuthListEnabled
? convertToBoolean(localAuthListEnabled
.value
) : false;
520 public getHeartbeatInterval(): number {
521 const HeartbeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
);
522 if (HeartbeatInterval
) {
523 return secondsToMilliseconds(convertToInt(HeartbeatInterval
.value
));
525 const HeartBeatInterval
= getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
);
526 if (HeartBeatInterval
) {
527 return secondsToMilliseconds(convertToInt(HeartBeatInterval
.value
));
529 this.stationInfo
?.autoRegister
=== false &&
531 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
532 Constants.DEFAULT_HEARTBEAT_INTERVAL
535 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
538 public setSupervisionUrl(url
: string): void {
540 this.getSupervisionUrlOcppConfiguration() &&
541 isNotEmptyString(this.getSupervisionUrlOcppKey())
543 setConfigurationKeyValue(this, this.getSupervisionUrlOcppKey(), url
);
545 this.stationInfo
.supervisionUrls
= url
;
546 this.saveStationInfo();
547 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
551 public startHeartbeat(): void {
552 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
553 this.heartbeatSetInterval
= setInterval(() => {
554 this.ocppRequestService
555 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
558 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
562 }, this.getHeartbeatInterval());
564 `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
565 this.getHeartbeatInterval(),
568 } else if (this.heartbeatSetInterval
) {
570 `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
571 this.getHeartbeatInterval(),
576 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()},
577 not starting the heartbeat`,
582 public restartHeartbeat(): void {
584 this.stopHeartbeat();
586 this.startHeartbeat();
589 public restartWebSocketPing(): void {
590 // Stop WebSocket ping
591 this.stopWebSocketPing();
592 // Start WebSocket ping
593 this.startWebSocketPing();
596 public startMeterValues(connectorId
: number, interval
: number): void {
597 if (connectorId
=== 0) {
599 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`,
603 if (!this.getConnectorStatus(connectorId
)) {
605 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
610 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
612 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
613 with no transaction started`,
617 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
618 isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
621 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
622 with no transaction id`,
627 this.getConnectorStatus(connectorId
)!.transactionSetInterval
= setInterval(() => {
628 // FIXME: Implement OCPP version agnostic helpers
629 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
632 this.getConnectorStatus(connectorId
)!.transactionId
!,
635 this.ocppRequestService
636 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
638 RequestCommand
.METER_VALUES
,
641 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
642 meterValue
: [meterValue
],
647 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
654 `${this.logPrefix()} Charging station ${
655 StandardParametersKey.MeterValueSampleInterval
656 } configuration set to ${interval}, not sending MeterValues`,
661 public stopMeterValues(connectorId
: number) {
662 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
663 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
667 public start(): void {
668 if (this.started
=== false) {
669 if (this.starting
=== false) {
670 this.starting
= true;
671 if (this.getEnableStatistics() === true) {
672 this.performanceStatistics
?.start();
674 if (hasFeatureProfile(this, SupportedFeatureProfiles
.Reservation
)) {
675 this.startReservationExpirationSetInterval();
677 this.openWSConnection();
678 // Monitor charging station template file
679 this.templateFileWatcher
= watchJsonFile(
681 FileType
.ChargingStationTemplate
,
684 (event
, filename
): void => {
685 if (isNotEmptyString(filename
) && event
=== 'change') {
688 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
690 } file have changed, reload`,
692 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
695 this.idTagsCache
.deleteIdTags(getIdTagsFile(this.stationInfo
)!);
697 this.stopAutomaticTransactionGenerator();
698 delete this.automaticTransactionGeneratorConfiguration
;
699 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
700 this.startAutomaticTransactionGenerator();
702 if (this.getEnableStatistics() === true) {
703 this.performanceStatistics
?.restart();
705 this.performanceStatistics
?.stop();
707 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
710 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
718 parentPort
?.postMessage(buildStartedMessage(this));
719 this.starting
= false;
721 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
724 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
728 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
729 if (this.started
=== true) {
730 if (this.stopping
=== false) {
731 this.stopping
= true;
732 await this.stopMessageSequence(reason
);
733 this.closeWSConnection();
734 if (this.getEnableStatistics() === true) {
735 this.performanceStatistics
?.stop();
737 if (hasFeatureProfile(this, SupportedFeatureProfiles
.Reservation
)) {
738 this.stopReservationExpirationSetInterval();
740 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
741 this.templateFileWatcher
?.close();
742 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
743 delete this.bootNotificationResponse
;
744 this.started
= false;
745 this.saveConfiguration();
746 parentPort
?.postMessage(buildStoppedMessage(this));
747 this.stopping
= false;
749 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
752 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
756 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
757 await this.stop(reason
);
758 await sleep(this.stationInfo
.resetTime
!);
763 public saveOcppConfiguration(): void {
764 if (this.getOcppPersistentConfiguration()) {
765 this.saveConfiguration();
769 public 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
: secondsToMilliseconds(this.getConnectionTimeout()), ...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 getReserveConnectorZeroSupported(): boolean {
942 return convertToBoolean(
943 getConfigurationKey(this, StandardParametersKey
.ReserveConnectorZeroSupported
)!.value
,
947 public async addReservation(reservation
: Reservation
): Promise
<void> {
948 const reservationFound
= this.getReservationBy('reservationId', reservation
.reservationId
);
949 if (!isUndefined(reservationFound
)) {
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 case ReservationTerminationReason
.TRANSACTION_STARTED
:
973 delete connector
.reservation
;
975 case ReservationTerminationReason
.RESERVATION_CANCELED
:
976 case ReservationTerminationReason
.REPLACE_EXISTING
:
977 case ReservationTerminationReason
.EXPIRED
:
978 await OCPPServiceUtils
.sendAndSetConnectorStatus(
980 reservation
.connectorId
,
981 ConnectorStatusEnum
.Available
,
983 { send
: reservation
.connectorId
!== 0 },
985 delete connector
.reservation
;
988 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
989 throw new BaseError(`Unknown reservation termination reason '${reason}'`);
993 public getReservationBy(
994 filterKey
: ReservationKey
,
995 value
: number | string,
996 ): Reservation
| undefined {
998 for (const evseStatus
of this.evses
.values()) {
999 for (const connectorStatus
of evseStatus
.connectors
.values()) {
1000 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
1001 return connectorStatus
.reservation
;
1006 for (const connectorStatus
of this.connectors
.values()) {
1007 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
1008 return connectorStatus
.reservation
;
1014 public isConnectorReservable(
1015 reservationId
: number,
1017 connectorId
?: number,
1019 const reservation
= this.getReservationBy('reservationId', reservationId
);
1020 const reservationExists
= !isUndefined(reservation
) && !hasReservationExpired(reservation
!);
1021 if (arguments.length
=== 1) {
1022 return !reservationExists
;
1023 } else if (arguments.length
> 1) {
1024 const userReservation
= !isUndefined(idTag
)
1025 ? this.getReservationBy('idTag', idTag
!)
1027 const userReservationExists
=
1028 !isUndefined(userReservation
) && !hasReservationExpired(userReservation
!);
1029 const notConnectorZero
= isUndefined(connectorId
) ? true : connectorId
! > 0;
1030 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0;
1032 !reservationExists
&& !userReservationExists
&& notConnectorZero
&& freeConnectorsAvailable
1038 private startReservationExpirationSetInterval(customInterval
?: number): void {
1040 customInterval
?? Constants
.DEFAULT_RESERVATION_EXPIRATION_OBSERVATION_INTERVAL
;
1043 `${this.logPrefix()} Reservation expiration date checks started every ${formatDurationMilliSeconds(
1047 this.reservationExpirationSetInterval
= setInterval((): void => {
1048 removeExpiredReservations(this).catch(Constants
.EMPTY_FUNCTION
);
1053 private stopReservationExpirationSetInterval(): void {
1054 if (this.reservationExpirationSetInterval
) {
1055 clearInterval(this.reservationExpirationSetInterval
);
1059 // private restartReservationExpiryDateSetInterval(): void {
1060 // this.stopReservationExpirationSetInterval();
1061 // this.startReservationExpirationSetInterval();
1064 private getNumberOfReservableConnectors(): number {
1065 let numberOfReservableConnectors
= 0;
1066 if (this.hasEvses
) {
1067 for (const evseStatus
of this.evses
.values()) {
1068 numberOfReservableConnectors
+= getNumberOfReservableConnectors(evseStatus
.connectors
);
1071 numberOfReservableConnectors
= getNumberOfReservableConnectors(this.connectors
);
1073 return numberOfReservableConnectors
- this.getNumberOfReservationsOnConnectorZero();
1076 private getNumberOfReservationsOnConnectorZero(): number {
1078 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1079 (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
) ||
1080 (!this.hasEvses
&& this.connectors
.get(0)?.reservation
)
1087 private flushMessageBuffer(): void {
1088 if (this.messageBuffer
.size
> 0) {
1089 for (const message
of this.messageBuffer
.values()) {
1090 let beginId
: string | undefined;
1091 let commandName
: RequestCommand
| undefined;
1092 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
1093 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
1095 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
1096 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
1098 this.wsConnection
?.send(message
);
1099 isRequest
&& PerformanceStatistics
.endMeasure(commandName
!, beginId
!);
1101 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
1103 )} payload sent: ${message}`,
1105 this.messageBuffer
.delete(message
);
1110 private getSupervisionUrlOcppConfiguration(): boolean {
1111 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
1114 private getSupervisionUrlOcppKey(): string {
1115 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
1118 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
1119 let template
: ChargingStationTemplate
| undefined;
1121 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1122 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
1124 const measureId
= `${FileType.ChargingStationTemplate} read`;
1125 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1126 template
= JSON
.parse(readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
1127 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1128 template
.templateHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1129 .update(JSON
.stringify(template
))
1131 this.sharedLRUCache
.setChargingStationTemplate(template
);
1132 this.templateFileHash
= template
.templateHash
;
1135 handleFileException(
1137 FileType
.ChargingStationTemplate
,
1138 error
as NodeJS
.ErrnoException
,
1145 private getStationInfoFromTemplate(): ChargingStationInfo
{
1146 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile()!;
1147 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1148 warnTemplateKeysDeprecation(stationTemplate
, this.logPrefix(), this.templateFile
);
1149 if (stationTemplate
?.Connectors
) {
1150 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1152 const stationInfo
: ChargingStationInfo
= stationTemplateToStationInfo(stationTemplate
);
1153 stationInfo
.hashId
= getHashId(this.index
, stationTemplate
);
1154 stationInfo
.chargingStationId
= getChargingStationId(this.index
, stationTemplate
);
1155 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
1156 createSerialNumber(stationTemplate
, stationInfo
);
1157 if (isNotEmptyArray(stationTemplate
?.power
)) {
1158 stationTemplate
.power
= stationTemplate
.power
as number[];
1159 const powerArrayRandomIndex
= Math.floor(secureRandom() * stationTemplate
.power
.length
);
1160 stationInfo
.maximumPower
=
1161 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1162 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1163 : stationTemplate
.power
[powerArrayRandomIndex
];
1165 stationTemplate
.power
= stationTemplate
?.power
as number;
1166 stationInfo
.maximumPower
=
1167 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1168 ? stationTemplate
.power
* 1000
1169 : stationTemplate
.power
;
1171 stationInfo
.firmwareVersionPattern
=
1172 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
1174 isNotEmptyString(stationInfo
.firmwareVersion
) &&
1175 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
!) === false
1178 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1180 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`,
1183 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1190 stationTemplate
?.firmwareUpgrade
?? {},
1192 stationInfo
.resetTime
= !isNullOrUndefined(stationTemplate
?.resetTime
)
1193 ? secondsToMilliseconds(stationTemplate
.resetTime
!)
1194 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1195 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1199 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
1200 let stationInfo
: ChargingStationInfo
| undefined;
1201 if (this.getStationInfoPersistentConfiguration()) {
1202 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1204 delete stationInfo
?.infoHash
;
1210 private getStationInfo(): ChargingStationInfo
{
1211 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1212 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
1214 // 1. charging station info from template
1215 // 2. charging station info from configuration file
1216 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1217 return stationInfoFromFile
!;
1219 stationInfoFromFile
&&
1220 propagateSerialNumber(
1221 this.getTemplateFromFile()!,
1222 stationInfoFromFile
,
1223 stationInfoFromTemplate
,
1225 return stationInfoFromTemplate
;
1228 private saveStationInfo(): void {
1229 if (this.getStationInfoPersistentConfiguration()) {
1230 this.saveConfiguration();
1234 private getOcppPersistentConfiguration(): boolean {
1235 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1238 private getStationInfoPersistentConfiguration(): boolean {
1239 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1242 private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean {
1243 return this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
?? true;
1246 private handleUnsupportedVersion(version
: OCPPVersion
) {
1247 const errorMsg
= `Unsupported protocol version '${version}' configured
1248 in template file ${this.templateFile}`;
1249 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1250 throw new BaseError(errorMsg
);
1253 private initialize(): void {
1254 const stationTemplate
= this.getTemplateFromFile()!;
1255 checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1256 this.configurationFile
= join(
1257 dirname(this.templateFile
.replace('station-templates', 'configurations')),
1258 `${getHashId(this.index, stationTemplate)}.json`,
1260 const chargingStationConfiguration
= this.getConfigurationFromFile();
1262 chargingStationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
1263 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1264 (chargingStationConfiguration
?.connectorsStatus
|| chargingStationConfiguration
?.evsesStatus
)
1266 this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration
);
1268 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1270 this.stationInfo
= this.getStationInfo();
1272 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1273 isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1274 isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1276 const patternGroup
: number | undefined =
1277 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1278 this.stationInfo
.firmwareVersion
?.split('.').length
;
1279 const match
= this.stationInfo
1280 .firmwareVersion
!.match(new RegExp(this.stationInfo
.firmwareVersionPattern
!))!
1281 .slice(1, patternGroup
! + 1);
1282 const patchLevelIndex
= match
.length
- 1;
1283 match
[patchLevelIndex
] = (
1284 convertToInt(match
[patchLevelIndex
]) +
1285 this.stationInfo
.firmwareUpgrade
!.versionUpgrade
!.step
!
1287 this.stationInfo
.firmwareVersion
= match
?.join('.');
1289 this.saveStationInfo();
1290 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1291 if (this.getEnableStatistics() === true) {
1292 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1293 this.stationInfo
.hashId
,
1294 this.stationInfo
.chargingStationId
!,
1295 this.configuredSupervisionUrl
,
1298 this.bootNotificationRequest
= createBootNotificationRequest(this.stationInfo
);
1299 this.powerDivider
= this.getPowerDivider();
1300 // OCPP configuration
1301 this.ocppConfiguration
= this.getOcppConfiguration();
1302 this.initializeOcppConfiguration();
1303 this.initializeOcppServices();
1304 if (this.stationInfo
?.autoRegister
=== true) {
1305 this.bootNotificationResponse
= {
1306 currentTime
: new Date(),
1307 interval
: millisecondsToSeconds(this.getHeartbeatInterval()),
1308 status: RegistrationStatusEnumType
.ACCEPTED
,
1313 private initializeOcppServices(): void {
1314 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1315 switch (ocppVersion
) {
1316 case OCPPVersion
.VERSION_16
:
1317 this.ocppIncomingRequestService
=
1318 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1319 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1320 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(),
1323 case OCPPVersion
.VERSION_20
:
1324 case OCPPVersion
.VERSION_201
:
1325 this.ocppIncomingRequestService
=
1326 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1327 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1328 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>(),
1332 this.handleUnsupportedVersion(ocppVersion
);
1337 private initializeOcppConfiguration(): void {
1338 if (!getConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
)) {
1339 addConfigurationKey(this, StandardParametersKey
.HeartbeatInterval
, '0');
1341 if (!getConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
)) {
1342 addConfigurationKey(this, StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false });
1345 this.getSupervisionUrlOcppConfiguration() &&
1346 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1347 !getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1349 addConfigurationKey(
1351 this.getSupervisionUrlOcppKey(),
1352 this.configuredSupervisionUrl
.href
,
1356 !this.getSupervisionUrlOcppConfiguration() &&
1357 isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1358 getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1360 deleteConfigurationKey(this, this.getSupervisionUrlOcppKey(), { save
: false });
1363 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1364 !getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)
1366 addConfigurationKey(
1368 this.stationInfo
.amperageLimitationOcppKey
!,
1370 this.stationInfo
.maximumAmperage
! * getAmperageLimitationUnitDivider(this.stationInfo
)
1374 if (!getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
)) {
1375 addConfigurationKey(
1377 StandardParametersKey
.SupportedFeatureProfiles
,
1378 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`,
1381 addConfigurationKey(
1383 StandardParametersKey
.NumberOfConnectors
,
1384 this.getNumberOfConnectors().toString(),
1386 { overwrite
: true },
1388 if (!getConfigurationKey(this, StandardParametersKey
.MeterValuesSampledData
)) {
1389 addConfigurationKey(
1391 StandardParametersKey
.MeterValuesSampledData
,
1392 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
1395 if (!getConfigurationKey(this, StandardParametersKey
.ConnectorPhaseRotation
)) {
1396 const connectorsPhaseRotation
: string[] = [];
1397 if (this.hasEvses
) {
1398 for (const evseStatus
of this.evses
.values()) {
1399 for (const connectorId
of evseStatus
.connectors
.keys()) {
1400 connectorsPhaseRotation
.push(
1401 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1406 for (const connectorId
of this.connectors
.keys()) {
1407 connectorsPhaseRotation
.push(
1408 getPhaseRotationValue(connectorId
, this.getNumberOfPhases())!,
1412 addConfigurationKey(
1414 StandardParametersKey
.ConnectorPhaseRotation
,
1415 connectorsPhaseRotation
.toString(),
1418 if (!getConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
1419 addConfigurationKey(this, StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1422 !getConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
) &&
1423 getConfigurationKey(this, StandardParametersKey
.SupportedFeatureProfiles
)?.value
?.includes(
1424 SupportedFeatureProfiles
.LocalAuthListManagement
,
1427 addConfigurationKey(this, StandardParametersKey
.LocalAuthListEnabled
, 'false');
1429 if (!getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)) {
1430 addConfigurationKey(
1432 StandardParametersKey
.ConnectionTimeOut
,
1433 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString(),
1436 this.saveOcppConfiguration();
1439 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1440 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1441 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1442 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1444 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1445 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1446 const evseStatus
= cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1447 delete evseStatus
.connectorsStatus
;
1448 this.evses
.set(evseId
, {
1449 ...(evseStatus
as EvseStatus
),
1450 connectors
: new Map
<number, ConnectorStatus
>(
1451 evseStatusConfiguration
.connectorsStatus
!.map((connectorStatus
, connectorId
) => [
1458 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1459 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1460 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1461 throw new BaseError(errorMsg
);
1463 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1464 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1465 throw new BaseError(errorMsg
);
1469 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1470 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1471 this.initializeConnectorsFromTemplate(stationTemplate
);
1472 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1473 this.initializeEvsesFromTemplate(stationTemplate
);
1474 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1475 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1476 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1477 throw new BaseError(errorMsg
);
1479 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1480 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1481 throw new BaseError(errorMsg
);
1485 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1486 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1487 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1488 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1489 throw new BaseError(errorMsg
);
1491 if (!stationTemplate
?.Connectors
?.[0]) {
1493 `${this.logPrefix()} Charging station information from template ${
1495 } with no connector id 0 configuration`,
1498 if (stationTemplate
?.Connectors
) {
1499 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1500 checkConnectorsConfiguration(stationTemplate
, this.logPrefix(), this.templateFile
);
1501 const connectorsConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1503 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`,
1506 const connectorsConfigChanged
=
1507 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1508 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1509 connectorsConfigChanged
&& this.connectors
.clear();
1510 this.connectorsConfigurationHash
= connectorsConfigHash
;
1511 if (templateMaxConnectors
> 0) {
1512 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1514 connectorId
=== 0 &&
1515 (!stationTemplate
?.Connectors
[connectorId
] ||
1516 this.getUseConnectorId0(stationTemplate
) === false)
1520 const templateConnectorId
=
1521 connectorId
> 0 && stationTemplate
?.randomConnectors
1522 ? getRandomInteger(templateMaxAvailableConnectors
, 1)
1524 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1525 checkStationInfoConnectorStatus(
1526 templateConnectorId
,
1531 this.connectors
.set(connectorId
, cloneObject
<ConnectorStatus
>(connectorStatus
));
1533 initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1534 this.saveConnectorsStatus();
1537 `${this.logPrefix()} Charging station information from template ${
1539 } with no connectors configuration defined, cannot create connectors`,
1545 `${this.logPrefix()} Charging station information from template ${
1547 } with no connectors configuration defined, using already defined connectors`,
1552 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1553 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1554 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1555 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1556 throw new BaseError(errorMsg
);
1558 if (!stationTemplate
?.Evses
?.[0]) {
1560 `${this.logPrefix()} Charging station information from template ${
1562 } with no evse id 0 configuration`,
1565 if (!stationTemplate
?.Evses
?.[0]?.Connectors
?.[0]) {
1567 `${this.logPrefix()} Charging station information from template ${
1569 } with evse id 0 with no connector id 0 configuration`,
1572 if (Object.keys(stationTemplate
?.Evses
?.[0]?.Connectors
as object
).length
> 1) {
1574 `${this.logPrefix()} Charging station information from template ${
1576 } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`,
1579 if (stationTemplate
?.Evses
) {
1580 const evsesConfigHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1581 .update(JSON
.stringify(stationTemplate
?.Evses
))
1583 const evsesConfigChanged
=
1584 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1585 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1586 evsesConfigChanged
&& this.evses
.clear();
1587 this.evsesConfigurationHash
= evsesConfigHash
;
1588 const templateMaxEvses
= getMaxNumberOfEvses(stationTemplate
?.Evses
);
1589 if (templateMaxEvses
> 0) {
1590 for (const evse
in stationTemplate
.Evses
) {
1591 const evseId
= convertToInt(evse
);
1592 this.evses
.set(evseId
, {
1593 connectors
: buildConnectorsMap(
1594 stationTemplate
?.Evses
[evse
]?.Connectors
,
1598 availability
: AvailabilityType
.Operative
,
1600 initializeConnectorsMapStatus(this.evses
.get(evseId
)!.connectors
, this.logPrefix());
1602 this.saveEvsesStatus();
1605 `${this.logPrefix()} Charging station information from template ${
1607 } with no evses configuration defined, cannot create evses`,
1613 `${this.logPrefix()} Charging station information from template ${
1615 } with no evses configuration defined, using already defined evses`,
1620 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1621 let configuration
: ChargingStationConfiguration
| undefined;
1622 if (isNotEmptyString(this.configurationFile
) && existsSync(this.configurationFile
)) {
1624 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1625 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1626 this.configurationFileHash
,
1629 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1630 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1631 configuration
= JSON
.parse(
1632 readFileSync(this.configurationFile
, 'utf8'),
1633 ) as ChargingStationConfiguration
;
1634 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1635 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1636 this.configurationFileHash
= configuration
.configurationHash
!;
1639 handleFileException(
1640 this.configurationFile
,
1641 FileType
.ChargingStationConfiguration
,
1642 error
as NodeJS
.ErrnoException
,
1647 return configuration
;
1650 private saveAutomaticTransactionGeneratorConfiguration(): void {
1651 if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) {
1652 this.saveConfiguration();
1656 private saveConnectorsStatus() {
1657 this.saveConfiguration();
1660 private saveEvsesStatus() {
1661 this.saveConfiguration();
1664 private saveConfiguration(): void {
1665 if (isNotEmptyString(this.configurationFile
)) {
1667 if (!existsSync(dirname(this.configurationFile
))) {
1668 mkdirSync(dirname(this.configurationFile
), { recursive
: true });
1670 let configurationData
: ChargingStationConfiguration
= this.getConfigurationFromFile()
1671 ? cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()!)
1673 if (this.getStationInfoPersistentConfiguration() && this.stationInfo
) {
1674 configurationData
.stationInfo
= this.stationInfo
;
1676 delete configurationData
.stationInfo
;
1678 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration
?.configurationKey
) {
1679 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1681 delete configurationData
.configurationKey
;
1683 configurationData
= merge
<ChargingStationConfiguration
>(
1685 buildChargingStationAutomaticTransactionGeneratorConfiguration(this),
1688 !this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
1689 !this.getAutomaticTransactionGeneratorConfiguration()
1691 delete configurationData
.automaticTransactionGenerator
;
1693 if (this.connectors
.size
> 0) {
1694 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1696 delete configurationData
.connectorsStatus
;
1698 if (this.evses
.size
> 0) {
1699 configurationData
.evsesStatus
= buildEvsesStatus(this);
1701 delete configurationData
.evsesStatus
;
1703 delete configurationData
.configurationHash
;
1704 const configurationHash
= createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1707 stationInfo
: configurationData
.stationInfo
,
1708 configurationKey
: configurationData
.configurationKey
,
1709 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1710 } as ChargingStationConfiguration
),
1713 if (this.configurationFileHash
!== configurationHash
) {
1714 AsyncLock
.acquire(AsyncLockType
.configuration
)
1716 configurationData
.configurationHash
= configurationHash
;
1717 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1718 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1719 const fileDescriptor
= openSync(this.configurationFile
, 'w');
1720 writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1721 closeSync(fileDescriptor
);
1722 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1723 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1724 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1725 this.configurationFileHash
= configurationHash
;
1728 handleFileException(
1729 this.configurationFile
,
1730 FileType
.ChargingStationConfiguration
,
1731 error
as NodeJS
.ErrnoException
,
1736 AsyncLock
.release(AsyncLockType
.configuration
).catch(Constants
.EMPTY_FUNCTION
);
1740 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1741 this.configurationFile
1746 handleFileException(
1747 this.configurationFile
,
1748 FileType
.ChargingStationConfiguration
,
1749 error
as NodeJS
.ErrnoException
,
1755 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`,
1760 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1761 return this.getTemplateFromFile()?.Configuration
;
1764 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1765 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1766 if (this.getOcppPersistentConfiguration() === true && configurationKey
) {
1767 return { configurationKey
};
1772 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1773 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1774 this.getOcppConfigurationFromFile();
1775 if (!ocppConfiguration
) {
1776 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1778 return ocppConfiguration
;
1781 private async onOpen(): Promise
<void> {
1782 if (this.isWebSocketConnectionOpened() === true) {
1784 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`,
1786 if (this.isRegistered() === false) {
1787 // Send BootNotification
1788 let registrationRetryCount
= 0;
1790 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1791 BootNotificationRequest
,
1792 BootNotificationResponse
1793 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1794 skipBufferingOnError
: true,
1796 if (this.isRegistered() === false) {
1797 this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount
;
1799 this?.bootNotificationResponse
?.interval
1800 ? secondsToMilliseconds(this.bootNotificationResponse
.interval
)
1801 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
,
1805 this.isRegistered() === false &&
1806 (registrationRetryCount
<= this.getRegistrationMaxRetries()! ||
1807 this.getRegistrationMaxRetries() === -1)
1810 if (this.isRegistered() === true) {
1811 if (this.inAcceptedState() === true) {
1812 await this.startMessageSequence();
1816 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`,
1819 this.wsConnectionRestarted
= false;
1820 this.autoReconnectRetryCount
= 0;
1821 parentPort
?.postMessage(buildUpdatedMessage(this));
1824 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`,
1829 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1832 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1833 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1835 `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString(
1837 )}' and reason '${reason.toString()}'`,
1839 this.autoReconnectRetryCount
= 0;
1844 `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString(
1846 )}' and reason '${reason.toString()}'`,
1848 this.started
=== true && (await this.reconnect());
1851 parentPort
?.postMessage(buildUpdatedMessage(this));
1854 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1855 const cachedRequest
= this.requests
.get(messageId
);
1856 if (Array.isArray(cachedRequest
) === true) {
1857 return cachedRequest
;
1859 throw new OCPPError(
1860 ErrorType
.PROTOCOL_ERROR
,
1861 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1863 )} is not an array`,
1865 cachedRequest
as JsonType
,
1869 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1870 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1871 if (this.getEnableStatistics() === true) {
1872 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1875 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1879 // Process the message
1880 await this.ocppIncomingRequestService
.incomingRequestHandler(
1888 private handleResponseMessage(response
: Response
): void {
1889 const [messageType
, messageId
, commandPayload
] = response
;
1890 if (this.requests
.has(messageId
) === false) {
1892 throw new OCPPError(
1893 ErrorType
.INTERNAL_ERROR
,
1894 `Response for unknown message id ${messageId}`,
1900 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1905 `${this.logPrefix()} << Command '${
1906 requestCommandName ?? Constants.UNKNOWN_COMMAND
1907 }' received response payload: ${JSON.stringify(response)}`,
1909 responseCallback(commandPayload
, requestPayload
);
1912 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1913 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1914 if (this.requests
.has(messageId
) === false) {
1916 throw new OCPPError(
1917 ErrorType
.INTERNAL_ERROR
,
1918 `Error response for unknown message id ${messageId}`,
1920 { errorType
, errorMessage
, errorDetails
},
1923 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
1925 `${this.logPrefix()} << Command '${
1926 requestCommandName ?? Constants.UNKNOWN_COMMAND
1927 }' received error response payload: ${JSON.stringify(errorResponse)}`,
1929 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1932 private async onMessage(data
: RawData
): Promise
<void> {
1933 let request
: IncomingRequest
| Response
| ErrorResponse
| undefined;
1934 let messageType
: number | undefined;
1935 let errorMsg
: string;
1937 // eslint-disable-next-line @typescript-eslint/no-base-to-string
1938 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1939 if (Array.isArray(request
) === true) {
1940 [messageType
] = request
;
1941 // Check the type of message
1942 switch (messageType
) {
1944 case MessageType
.CALL_MESSAGE
:
1945 await this.handleIncomingMessage(request
as IncomingRequest
);
1948 case MessageType
.CALL_RESULT_MESSAGE
:
1949 this.handleResponseMessage(request
as Response
);
1952 case MessageType
.CALL_ERROR_MESSAGE
:
1953 this.handleErrorMessage(request
as ErrorResponse
);
1957 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1958 errorMsg
= `Wrong message type ${messageType}`;
1959 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1960 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
1962 parentPort
?.postMessage(buildUpdatedMessage(this));
1964 throw new OCPPError(
1965 ErrorType
.PROTOCOL_ERROR
,
1966 'Incoming message is not an array',
1974 let commandName
: IncomingRequestCommand
| undefined;
1975 let requestCommandName
: RequestCommand
| IncomingRequestCommand
| undefined;
1976 let errorCallback
: ErrorCallback
;
1977 const [, messageId
] = request
!;
1978 switch (messageType
) {
1979 case MessageType
.CALL_MESSAGE
:
1980 [, , commandName
] = request
as IncomingRequest
;
1982 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
1984 case MessageType
.CALL_RESULT_MESSAGE
:
1985 case MessageType
.CALL_ERROR_MESSAGE
:
1986 if (this.requests
.has(messageId
) === true) {
1987 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
)!;
1988 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1989 errorCallback(error
as OCPPError
, false);
1991 // Remove the request from the cache in case of error at response handling
1992 this.requests
.delete(messageId
);
1996 if (error
instanceof OCPPError
=== false) {
1998 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1999 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2000 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2001 }' message '${data.toString()}' handling is not an OCPPError:`,
2006 `${this.logPrefix()} Incoming OCPP command '${
2007 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2008 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2009 }' message '${data.toString()}'${
2010 messageType !== MessageType.CALL_MESSAGE
2011 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
2013 } processing error:`,
2019 private onPing(): void {
2020 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
2023 private onPong(): void {
2024 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
2027 private onError(error
: WSError
): void {
2028 this.closeWSConnection();
2029 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
2032 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
2033 if (this.getMeteringPerTransaction() === true) {
2036 ? Math.round(connectorStatus
.transactionEnergyActiveImportRegisterValue
!)
2037 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2042 ? Math.round(connectorStatus
.energyActiveImportRegisterValue
!)
2043 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2047 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
2048 return stationTemplate
?.useConnectorId0
?? true;
2051 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
2052 if (this.hasEvses
) {
2053 for (const [evseId
, evseStatus
] of this.evses
) {
2057 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2058 if (connectorStatus
.transactionStarted
=== true) {
2059 await this.stopTransactionOnConnector(connectorId
, reason
);
2064 for (const connectorId
of this.connectors
.keys()) {
2065 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2066 await this.stopTransactionOnConnector(connectorId
, reason
);
2073 private getConnectionTimeout(): number {
2074 if (getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)) {
2076 parseInt(getConfigurationKey(this, StandardParametersKey
.ConnectionTimeOut
)!.value
!) ??
2077 Constants
.DEFAULT_CONNECTION_TIMEOUT
2080 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
2083 // -1 for unlimited, 0 for disabling
2084 private getAutoReconnectMaxRetries(): number | undefined {
2086 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
2091 private getRegistrationMaxRetries(): number | undefined {
2092 return this.stationInfo
.registrationMaxRetries
?? -1;
2095 private getPowerDivider(): number {
2096 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
2097 if (this.stationInfo
?.powerSharedByConnectors
) {
2098 powerDivider
= this.getNumberOfRunningTransactions();
2100 return powerDivider
;
2103 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
2104 const maximumPower
= this.getMaximumPower(stationInfo
);
2105 switch (this.getCurrentOutType(stationInfo
)) {
2106 case CurrentType
.AC
:
2107 return ACElectricUtils
.amperagePerPhaseFromPower(
2108 this.getNumberOfPhases(stationInfo
),
2109 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2110 this.getVoltageOut(stationInfo
),
2112 case CurrentType
.DC
:
2113 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
2117 private getAmperageLimitation(): number | undefined {
2119 isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2120 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)
2124 getConfigurationKey(this, this.stationInfo
.amperageLimitationOcppKey
!)?.value
,
2125 ) / getAmperageLimitationUnitDivider(this.stationInfo
)
2130 private async startMessageSequence(): Promise
<void> {
2131 if (this.stationInfo
?.autoRegister
=== true) {
2132 await this.ocppRequestService
.requestHandler
<
2133 BootNotificationRequest
,
2134 BootNotificationResponse
2135 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2136 skipBufferingOnError
: true,
2139 // Start WebSocket ping
2140 this.startWebSocketPing();
2142 this.startHeartbeat();
2143 // Initialize connectors status
2144 if (this.hasEvses
) {
2145 for (const [evseId
, evseStatus
] of this.evses
) {
2147 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2148 const connectorBootStatus
= getBootConnectorStatus(this, connectorId
, connectorStatus
);
2149 await OCPPServiceUtils
.sendAndSetConnectorStatus(
2152 connectorBootStatus
,
2159 for (const connectorId
of this.connectors
.keys()) {
2160 if (connectorId
> 0) {
2161 const connectorBootStatus
= getBootConnectorStatus(
2164 this.getConnectorStatus(connectorId
)!,
2166 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2170 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2171 await this.ocppRequestService
.requestHandler
<
2172 FirmwareStatusNotificationRequest
,
2173 FirmwareStatusNotificationResponse
2174 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2175 status: FirmwareStatus
.Installed
,
2177 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2181 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2182 this.startAutomaticTransactionGenerator();
2184 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2187 private async stopMessageSequence(
2188 reason
: StopTransactionReason
= StopTransactionReason
.NONE
,
2190 // Stop WebSocket ping
2191 this.stopWebSocketPing();
2193 this.stopHeartbeat();
2194 // Stop ongoing transactions
2195 if (this.automaticTransactionGenerator
?.started
=== true) {
2196 this.stopAutomaticTransactionGenerator();
2198 await this.stopRunningTransactions(reason
);
2200 if (this.hasEvses
) {
2201 for (const [evseId
, evseStatus
] of this.evses
) {
2203 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2204 await this.ocppRequestService
.requestHandler
<
2205 StatusNotificationRequest
,
2206 StatusNotificationResponse
2209 RequestCommand
.STATUS_NOTIFICATION
,
2210 OCPPServiceUtils
.buildStatusNotificationRequest(
2213 ConnectorStatusEnum
.Unavailable
,
2217 delete connectorStatus
?.status;
2222 for (const connectorId
of this.connectors
.keys()) {
2223 if (connectorId
> 0) {
2224 await this.ocppRequestService
.requestHandler
<
2225 StatusNotificationRequest
,
2226 StatusNotificationResponse
2229 RequestCommand
.STATUS_NOTIFICATION
,
2230 OCPPServiceUtils
.buildStatusNotificationRequest(
2233 ConnectorStatusEnum
.Unavailable
,
2236 delete this.getConnectorStatus(connectorId
)?.status;
2242 private startWebSocketPing(): void {
2243 const webSocketPingInterval
: number = getConfigurationKey(
2245 StandardParametersKey
.WebSocketPingInterval
,
2247 ? convertToInt(getConfigurationKey(this, StandardParametersKey
.WebSocketPingInterval
)?.value
)
2249 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2250 this.webSocketPingSetInterval
= setInterval(() => {
2251 if (this.isWebSocketConnectionOpened() === true) {
2252 this.wsConnection
?.ping();
2254 }, secondsToMilliseconds(webSocketPingInterval
));
2256 `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds(
2257 webSocketPingInterval,
2260 } else if (this.webSocketPingSetInterval
) {
2262 `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds(
2263 webSocketPingInterval,
2268 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`,
2273 private stopWebSocketPing(): void {
2274 if (this.webSocketPingSetInterval
) {
2275 clearInterval(this.webSocketPingSetInterval
);
2276 delete this.webSocketPingSetInterval
;
2280 private getConfiguredSupervisionUrl(): URL
{
2281 let configuredSupervisionUrl
: string;
2282 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2283 if (isNotEmptyArray(supervisionUrls
)) {
2284 let configuredSupervisionUrlIndex
: number;
2285 switch (Configuration
.getSupervisionUrlDistribution()) {
2286 case SupervisionUrlDistribution
.RANDOM
:
2287 configuredSupervisionUrlIndex
= Math.floor(
2288 secureRandom() * (supervisionUrls
as string[]).length
,
2291 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2292 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2294 Object.values(SupervisionUrlDistribution
).includes(
2295 Configuration
.getSupervisionUrlDistribution()!,
2298 // eslint-disable-next-line @typescript-eslint/no-base-to-string
2299 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2300 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2303 configuredSupervisionUrlIndex
= (this.index
- 1) % (supervisionUrls
as string[]).length
;
2306 configuredSupervisionUrl
= (supervisionUrls
as string[])[configuredSupervisionUrlIndex
];
2308 configuredSupervisionUrl
= supervisionUrls
as string;
2310 if (isNotEmptyString(configuredSupervisionUrl
)) {
2311 return new URL(configuredSupervisionUrl
);
2313 const errorMsg
= 'No supervision url(s) configured';
2314 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2315 throw new BaseError(`${errorMsg}`);
2318 private stopHeartbeat(): void {
2319 if (this.heartbeatSetInterval
) {
2320 clearInterval(this.heartbeatSetInterval
);
2321 delete this.heartbeatSetInterval
;
2325 private terminateWSConnection(): void {
2326 if (this.isWebSocketConnectionOpened() === true) {
2327 this.wsConnection
?.terminate();
2328 this.wsConnection
= null;
2332 private getReconnectExponentialDelay(): boolean {
2333 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2336 private async reconnect(): Promise
<void> {
2337 // Stop WebSocket ping
2338 this.stopWebSocketPing();
2340 this.stopHeartbeat();
2341 // Stop the ATG if needed
2342 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
=== true) {
2343 this.stopAutomaticTransactionGenerator();
2346 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries()! ||
2347 this.getAutoReconnectMaxRetries() === -1
2349 ++this.autoReconnectRetryCount
;
2350 const reconnectDelay
= this.getReconnectExponentialDelay()
2351 ? exponentialDelay(this.autoReconnectRetryCount
)
2352 : secondsToMilliseconds(this.getConnectionTimeout());
2353 const reconnectDelayWithdraw
= 1000;
2354 const reconnectTimeout
=
2355 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2356 ? reconnectDelay
- reconnectDelayWithdraw
2359 `${this.logPrefix()} WebSocket connection retry in ${roundTo(
2362 )}ms, timeout ${reconnectTimeout}ms`,
2364 await sleep(reconnectDelay
);
2366 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`,
2368 this.openWSConnection(
2370 ...(this.stationInfo
?.wsOptions
?? {}),
2371 handshakeTimeout
: reconnectTimeout
,
2373 { closeOpened
: true },
2375 this.wsConnectionRestarted
= true;
2376 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2378 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2379 this.autoReconnectRetryCount
2380 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`,