1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import crypto from
'node:crypto';
4 import fs from
'node:fs';
5 import path from
'node:path';
6 import { URL
} from
'node:url';
7 import { parentPort
} from
'node:worker_threads';
9 import merge from
'just-merge';
10 import WebSocket
, { type RawData
} from
'ws';
12 import { AutomaticTransactionGenerator
} from
'./AutomaticTransactionGenerator';
13 import { ChargingStationWorkerBroadcastChannel
} from
'./broadcast-channel/ChargingStationWorkerBroadcastChannel';
14 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
15 import { ChargingStationUtils
} from
'./ChargingStationUtils';
16 import { IdTagsCache
} from
'./IdTagsCache';
18 OCPP16IncomingRequestService
,
20 OCPP16ResponseService
,
22 OCPP20IncomingRequestService
,
24 OCPP20ResponseService
,
25 type OCPPIncomingRequestService
,
26 type OCPPRequestService
,
29 import { SharedLRUCache
} from
'./SharedLRUCache';
30 import { BaseError
, OCPPError
} from
'../exception';
31 import { PerformanceStatistics
} from
'../performance';
33 type AutomaticTransactionGeneratorConfiguration
,
35 type BootNotificationRequest
,
36 type BootNotificationResponse
,
38 type ChargingStationConfiguration
,
39 type ChargingStationInfo
,
40 type ChargingStationOcppConfiguration
,
41 type ChargingStationTemplate
,
49 type EvseStatusConfiguration
,
52 type FirmwareStatusNotificationRequest
,
53 type FirmwareStatusNotificationResponse
,
55 type HeartbeatRequest
,
56 type HeartbeatResponse
,
58 type IncomingRequestCommand
,
63 type MeterValuesRequest
,
64 type MeterValuesResponse
,
68 RegistrationStatusEnumType
,
72 ReservationTerminationReason
,
74 StandardParametersKey
,
76 type StatusNotificationRequest
,
77 type StatusNotificationResponse
,
78 StopTransactionReason
,
79 type StopTransactionRequest
,
80 type StopTransactionResponse
,
81 SupervisionUrlDistribution
,
82 SupportedFeatureProfiles
,
85 WebSocketCloseEventStatusCode
,
96 buildChargingStationAutomaticTransactionGeneratorConfiguration
,
97 buildConnectorsStatus
,
107 export class ChargingStation
{
108 public readonly index
: number;
109 public readonly templateFile
: string;
110 public stationInfo
!: ChargingStationInfo
;
111 public started
: boolean;
112 public starting
: boolean;
113 public idTagsCache
: IdTagsCache
;
114 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
115 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
116 public wsConnection
!: WebSocket
| null;
117 public readonly connectors
: Map
<number, ConnectorStatus
>;
118 public readonly evses
: Map
<number, EvseStatus
>;
119 public readonly requests
: Map
<string, CachedRequest
>;
120 public performanceStatistics
!: PerformanceStatistics
| undefined;
121 public heartbeatSetInterval
!: NodeJS
.Timeout
;
122 public ocppRequestService
!: OCPPRequestService
;
123 public bootNotificationRequest
!: BootNotificationRequest
;
124 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
125 public powerDivider
!: number;
126 private stopping
: boolean;
127 private configurationFile
!: string;
128 private configurationFileHash
!: string;
129 private connectorsConfigurationHash
!: string;
130 private evsesConfigurationHash
!: string;
131 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
132 private readonly messageBuffer
: Set
<string>;
133 private configuredSupervisionUrl
!: URL
;
134 private wsConnectionRestarted
: boolean;
135 private autoReconnectRetryCount
: number;
136 private templateFileWatcher
!: fs
.FSWatcher
| undefined;
137 private templateFileHash
!: string;
138 private readonly sharedLRUCache
: SharedLRUCache
;
139 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
140 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
141 private reservationExpirationSetInterval
?: NodeJS
.Timeout
;
143 constructor(index
: number, templateFile
: string) {
144 this.started
= false;
145 this.starting
= false;
146 this.stopping
= false;
147 this.wsConnectionRestarted
= false;
148 this.autoReconnectRetryCount
= 0;
150 this.templateFile
= templateFile
;
151 this.connectors
= new Map
<number, ConnectorStatus
>();
152 this.evses
= new Map
<number, EvseStatus
>();
153 this.requests
= new Map
<string, CachedRequest
>();
154 this.messageBuffer
= new Set
<string>();
155 this.sharedLRUCache
= SharedLRUCache
.getInstance();
156 this.idTagsCache
= IdTagsCache
.getInstance();
157 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
162 public get
hasEvses(): boolean {
163 return this.connectors
.size
=== 0 && this.evses
.size
> 0;
166 private get
wsConnectionUrl(): URL
{
169 this.getSupervisionUrlOcppConfiguration() &&
170 Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
171 Utils.isNotEmptyString(
172 ChargingStationConfigurationUtils.getConfigurationKey(
174 this.getSupervisionUrlOcppKey()
177 ? ChargingStationConfigurationUtils.getConfigurationKey(
179 this.getSupervisionUrlOcppKey()
181 : this.configuredSupervisionUrl.href
182 }/${this.stationInfo.chargingStationId}`
186 public logPrefix
= (): string => {
187 return Utils
.logPrefix(
189 (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId)
190 ? this?.stationInfo?.chargingStationId
191 : ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())) ??
192 'Error at building log prefix'
197 public hasIdTags(): boolean {
198 return Utils
.isNotEmptyArray(
199 this.idTagsCache
.getIdTags(ChargingStationUtils
.getIdTagsFile(this.stationInfo
))
203 public getEnableStatistics(): boolean {
204 return this.stationInfo
.enableStatistics
?? false;
207 public getMustAuthorizeAtRemoteStart(): boolean {
208 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
211 public getPayloadSchemaValidation(): boolean {
212 return this.stationInfo
.payloadSchemaValidation
?? true;
215 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
216 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
217 switch (this.getCurrentOutType(stationInfo
)) {
219 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
220 ? localStationInfo
.numberOfPhases
227 public isWebSocketConnectionOpened(): boolean {
228 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
231 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
232 return this?.bootNotificationResponse
?.status;
235 public inUnknownState(): boolean {
236 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
239 public inPendingState(): boolean {
240 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
243 public inAcceptedState(): boolean {
244 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
247 public inRejectedState(): boolean {
248 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
251 public isRegistered(): boolean {
253 this.inUnknownState() === false &&
254 (this.inAcceptedState() === true || this.inPendingState() === true)
258 public isChargingStationAvailable(): boolean {
259 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.Operative
;
262 public hasConnector(connectorId
: number): boolean {
264 for (const evseStatus
of this.evses
.values()) {
265 if (evseStatus
.connectors
.has(connectorId
)) {
271 return this.connectors
.has(connectorId
);
274 public isConnectorAvailable(connectorId
: number): boolean {
277 this.getConnectorStatus(connectorId
)?.availability
=== AvailabilityType
.Operative
281 public getNumberOfConnectors(): number {
283 if (this.evses
.size
=== 0) {
284 throw new BaseError('Evses not initialized, cannot get number of connectors');
286 let numberOfConnectors
= 0;
287 for (const [evseId
, evseStatus
] of this.evses
) {
289 numberOfConnectors
+= evseStatus
.connectors
.size
;
292 return numberOfConnectors
;
294 if (this.connectors
.size
=== 0) {
295 throw new BaseError('Connectors not initialized, cannot get number of connectors');
297 return this.connectors
.has(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
300 public getNumberOfEvses(): number {
301 if (this.evses
.size
=== 0) {
302 throw new BaseError('Evses not initialized, cannot get number of evses');
304 return this.evses
.has(0) ? this.evses
.size
- 1 : this.evses
.size
;
307 public getConnectorStatus(connectorId
: number): ConnectorStatus
| undefined {
309 for (const evseStatus
of this.evses
.values()) {
310 if (evseStatus
.connectors
.has(connectorId
)) {
311 return evseStatus
.connectors
.get(connectorId
);
316 return this.connectors
.get(connectorId
);
319 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
320 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
323 public getOcppStrictCompliance(): boolean {
324 return this.stationInfo
?.ocppStrictCompliance
?? false;
327 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
328 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
329 this.getCurrentOutType(stationInfo
),
333 return (stationInfo
?? this.stationInfo
).voltageOut
?? defaultVoltageOut
;
336 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
337 const localStationInfo
= stationInfo
?? this.stationInfo
;
338 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
341 public getConnectorMaximumAvailablePower(connectorId
: number): number {
342 let connectorAmperageLimitationPowerLimit
: number;
344 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
345 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
347 connectorAmperageLimitationPowerLimit
=
348 (this.getCurrentOutType() === CurrentType
.AC
349 ? ACElectricUtils
.powerTotal(
350 this.getNumberOfPhases(),
351 this.getVoltageOut(),
352 this.getAmperageLimitation() *
353 (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors())
355 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
358 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
359 const connectorChargingProfilesPowerLimit
=
360 ChargingStationUtils
.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
362 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
363 isNaN(connectorAmperageLimitationPowerLimit
)
365 : connectorAmperageLimitationPowerLimit
,
366 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
370 public getTransactionIdTag(transactionId
: number): string | undefined {
372 for (const evseStatus
of this.evses
.values()) {
373 for (const connectorStatus
of evseStatus
.connectors
.values()) {
374 if (connectorStatus
.transactionId
=== transactionId
) {
375 return connectorStatus
.transactionIdTag
;
380 for (const connectorId
of this.connectors
.keys()) {
381 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
382 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
388 public getNumberOfRunningTransactions(): number {
391 for (const [evseId
, evseStatus
] of this.evses
) {
395 for (const connectorStatus
of evseStatus
.connectors
.values()) {
396 if (connectorStatus
.transactionStarted
=== true) {
402 for (const connectorId
of this.connectors
.keys()) {
403 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
411 public getOutOfOrderEndMeterValues(): boolean {
412 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
415 public getBeginEndMeterValues(): boolean {
416 return this.stationInfo
?.beginEndMeterValues
?? false;
419 public getMeteringPerTransaction(): boolean {
420 return this.stationInfo
?.meteringPerTransaction
?? true;
423 public getTransactionDataMeterValues(): boolean {
424 return this.stationInfo
?.transactionDataMeterValues
?? false;
427 public getMainVoltageMeterValues(): boolean {
428 return this.stationInfo
?.mainVoltageMeterValues
?? true;
431 public getPhaseLineToLineVoltageMeterValues(): boolean {
432 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
435 public getCustomValueLimitationMeterValues(): boolean {
436 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
439 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
441 for (const evseStatus
of this.evses
.values()) {
442 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
443 if (connectorStatus
.transactionId
=== transactionId
) {
449 for (const connectorId
of this.connectors
.keys()) {
450 if (this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
457 public getEnergyActiveImportRegisterByTransactionId(
458 transactionId
: number,
461 return this.getEnergyActiveImportRegister(
462 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
467 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
468 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
471 public getAuthorizeRemoteTxRequests(): boolean {
472 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
474 StandardParametersKey
.AuthorizeRemoteTxRequests
476 return authorizeRemoteTxRequests
477 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
481 public getLocalAuthListEnabled(): boolean {
482 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
484 StandardParametersKey
.LocalAuthListEnabled
486 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
489 public getHeartbeatInterval(): number {
490 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
492 StandardParametersKey
.HeartbeatInterval
494 if (HeartbeatInterval
) {
495 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
497 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
499 StandardParametersKey
.HeartBeatInterval
501 if (HeartBeatInterval
) {
502 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
504 this.stationInfo
?.autoRegister
=== false &&
506 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
507 Constants.DEFAULT_HEARTBEAT_INTERVAL
510 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
513 public setSupervisionUrl(url
: string): void {
515 this.getSupervisionUrlOcppConfiguration() &&
516 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey())
518 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
520 this.getSupervisionUrlOcppKey(),
524 this.stationInfo
.supervisionUrls
= url
;
525 this.saveStationInfo();
526 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
530 public startHeartbeat(): void {
531 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
532 this.heartbeatSetInterval
= setInterval(() => {
533 this.ocppRequestService
534 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
537 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
541 }, this.getHeartbeatInterval());
543 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
544 this.getHeartbeatInterval()
547 } else if (this.heartbeatSetInterval
) {
549 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
550 this.getHeartbeatInterval()
555 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()},
556 not starting the heartbeat`
561 public restartHeartbeat(): void {
563 this.stopHeartbeat();
565 this.startHeartbeat();
568 public restartWebSocketPing(): void {
569 // Stop WebSocket ping
570 this.stopWebSocketPing();
571 // Start WebSocket ping
572 this.startWebSocketPing();
575 public startMeterValues(connectorId
: number, interval
: number): void {
576 if (connectorId
=== 0) {
578 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`
582 if (!this.getConnectorStatus(connectorId
)) {
584 `${this.logPrefix()} Trying to start MeterValues on non existing connector id
585 ${connectorId.toString()}`
589 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
591 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
592 with no transaction started`
596 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
597 Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
600 `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
601 with no transaction id`
606 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
607 // FIXME: Implement OCPP version agnostic helpers
608 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
611 this.getConnectorStatus(connectorId
).transactionId
,
614 this.ocppRequestService
615 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
617 RequestCommand
.METER_VALUES
,
620 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
621 meterValue
: [meterValue
],
626 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
633 `${this.logPrefix()} Charging station ${
634 StandardParametersKey.MeterValueSampleInterval
635 } configuration set to ${interval}, not sending MeterValues`
640 public stopMeterValues(connectorId
: number) {
641 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
642 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
646 public start(): void {
647 if (this.started
=== false) {
648 if (this.starting
=== false) {
649 this.starting
= true;
650 if (this.getEnableStatistics() === true) {
651 this.performanceStatistics
?.start();
653 if (this.hasFeatureProfile(SupportedFeatureProfiles
.Reservation
)) {
654 this.startReservationExpirationSetInterval();
656 this.openWSConnection();
657 // Monitor charging station template file
658 this.templateFileWatcher
= watchJsonFile(
660 FileType
.ChargingStationTemplate
,
663 (event
, filename
): void => {
664 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
667 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
669 } file have changed, reload`
671 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
672 // FIXME: cleanup idtags cache if idtags file has changed
676 this.stopAutomaticTransactionGenerator();
677 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
678 this.startAutomaticTransactionGenerator();
680 if (this.getEnableStatistics() === true) {
681 this.performanceStatistics
?.restart();
683 this.performanceStatistics
?.stop();
685 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
688 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
696 parentPort
?.postMessage(buildStartedMessage(this));
697 this.starting
= false;
699 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
702 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
706 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
707 if (this.started
=== true) {
708 if (this.stopping
=== false) {
709 this.stopping
= true;
710 await this.stopMessageSequence(reason
);
711 this.closeWSConnection();
712 if (this.getEnableStatistics() === true) {
713 this.performanceStatistics
?.stop();
715 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
716 this.templateFileWatcher
?.close();
717 this.sharedLRUCache
.deleteChargingStationTemplate(this.templateFileHash
);
718 delete this.bootNotificationResponse
;
719 this.started
= false;
720 this.saveConfiguration();
721 parentPort
?.postMessage(buildStoppedMessage(this));
722 this.stopping
= false;
724 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
727 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
731 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
732 await this.stop(reason
);
733 await Utils
.sleep(this.stationInfo
.resetTime
);
738 public saveOcppConfiguration(): void {
739 if (this.getOcppPersistentConfiguration()) {
740 this.saveConfiguration();
744 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
745 return ChargingStationConfigurationUtils
.getConfigurationKey(
747 StandardParametersKey
.SupportedFeatureProfiles
748 )?.value
?.includes(featureProfile
);
751 public bufferMessage(message
: string): void {
752 this.messageBuffer
.add(message
);
755 public openWSConnection(
756 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
757 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
759 terminateOpened
: false,
762 options
= { handshakeTimeout
: this.getConnectionTimeout() * 1000, ...options
};
763 params
= { ...{ closeOpened
: false, terminateOpened
: false }, ...params
};
764 if (this.started
=== false && this.starting
=== false) {
766 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()}
767 on stopped charging station`
772 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
773 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
775 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
777 if (params
?.closeOpened
) {
778 this.closeWSConnection();
780 if (params
?.terminateOpened
) {
781 this.terminateWSConnection();
784 if (this.isWebSocketConnectionOpened() === true) {
786 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()}
793 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
796 this.wsConnection
= new WebSocket(
797 this.wsConnectionUrl
,
798 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
802 // Handle WebSocket message
803 this.wsConnection
.on(
805 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
807 // Handle WebSocket error
808 this.wsConnection
.on(
810 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
812 // Handle WebSocket close
813 this.wsConnection
.on(
815 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
817 // Handle WebSocket open
818 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
819 // Handle WebSocket ping
820 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
821 // Handle WebSocket pong
822 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
825 public closeWSConnection(): void {
826 if (this.isWebSocketConnectionOpened() === true) {
827 this.wsConnection
?.close();
828 this.wsConnection
= null;
832 public getAutomaticTransactionGeneratorConfiguration():
833 | AutomaticTransactionGeneratorConfiguration
835 let automaticTransactionGeneratorConfiguration
:
836 | AutomaticTransactionGeneratorConfiguration
838 const automaticTransactionGeneratorConfigurationFromFile
=
839 this.getConfigurationFromFile()?.automaticTransactionGenerator
;
841 this.getAutomaticTransactionGeneratorPersistentConfiguration() &&
842 automaticTransactionGeneratorConfigurationFromFile
844 automaticTransactionGeneratorConfiguration
=
845 automaticTransactionGeneratorConfigurationFromFile
;
847 automaticTransactionGeneratorConfiguration
=
848 this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
851 ...Constants
.DEFAULT_ATG_CONFIGURATION
,
852 ...automaticTransactionGeneratorConfiguration
,
856 public getAutomaticTransactionGeneratorStatuses(): Status
[] | undefined {
857 return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses
;
860 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
861 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
862 if (Utils
.isNotEmptyArray(connectorIds
)) {
863 for (const connectorId
of connectorIds
) {
864 this.automaticTransactionGenerator
?.startConnector(connectorId
);
867 this.automaticTransactionGenerator
?.start();
869 this.saveAutomaticTransactionGeneratorConfiguration();
870 parentPort
?.postMessage(buildUpdatedMessage(this));
873 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
874 if (Utils
.isNotEmptyArray(connectorIds
)) {
875 for (const connectorId
of connectorIds
) {
876 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
879 this.automaticTransactionGenerator
?.stop();
881 this.saveAutomaticTransactionGeneratorConfiguration();
882 parentPort
?.postMessage(buildUpdatedMessage(this));
885 public async stopTransactionOnConnector(
887 reason
= StopTransactionReason
.NONE
888 ): Promise
<StopTransactionResponse
> {
889 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
891 this.getBeginEndMeterValues() === true &&
892 this.getOcppStrictCompliance() === true &&
893 this.getOutOfOrderEndMeterValues() === false
895 // FIXME: Implement OCPP version agnostic helpers
896 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
899 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
901 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
903 RequestCommand
.METER_VALUES
,
907 meterValue
: [transactionEndMeterValue
],
911 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
913 RequestCommand
.STOP_TRANSACTION
,
916 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
922 public getReservationOnConnectorId0Enabled(): boolean {
923 return Utils
.convertToBoolean(
924 ChargingStationConfigurationUtils
.getConfigurationKey(
926 StandardParametersKey
.ReserveConnectorZeroSupported
931 public async addReservation(reservation
: Reservation
): Promise
<void> {
932 const [exists
, reservationFound
] = this.doesReservationExists(reservation
);
934 await this.removeReservation(reservationFound
, ReservationTerminationReason
.REPLACE_EXISTING
);
936 this.getConnectorStatus(reservation
.connectorId
).reservation
= reservation
;
937 await OCPPServiceUtils
.sendAndSetConnectorStatus(
939 reservation
.connectorId
,
940 ConnectorStatusEnum
.Reserved
,
942 { send
: reservation
.connectorId
!== 0 }
946 public async removeReservation(
947 reservation
: Reservation
,
948 reason
?: ReservationTerminationReason
950 const connector
= this.getConnectorStatus(reservation
.connectorId
);
952 case ReservationTerminationReason
.CONNECTOR_STATE_CHANGED
:
953 delete connector
.reservation
;
955 case ReservationTerminationReason
.TRANSACTION_STARTED
:
956 delete connector
.reservation
;
958 case ReservationTerminationReason
.RESERVATION_CANCELED
||
959 ReservationTerminationReason
.REPLACE_EXISTING
||
960 ReservationTerminationReason
.EXPIRED
:
961 await OCPPServiceUtils
.sendAndSetConnectorStatus(
963 reservation
.connectorId
,
964 ConnectorStatusEnum
.Available
,
966 { send
: reservation
.connectorId
!== 0 }
968 delete connector
.reservation
;
975 public getReservationBy(
976 filterKey
: ReservationFilterKey
,
977 value
: number | string
978 ): Reservation
| undefined {
980 for (const evseStatus
of this.evses
.values()) {
981 for (const connectorStatus
of evseStatus
.connectors
.values()) {
982 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
983 return connectorStatus
.reservation
;
988 for (const connectorStatus
of this.connectors
.values()) {
989 if (connectorStatus
?.reservation
?.[filterKey
] === value
) {
990 return connectorStatus
.reservation
;
996 public doesReservationExists(reservation
: Partial
<Reservation
>): [boolean, Reservation
] {
997 const foundReservation
= this.getReservationBy(
998 ReservationFilterKey
.RESERVATION_ID
,
1001 return Utils
.isUndefined(foundReservation
) ? [false, null] : [true, foundReservation
];
1004 public startReservationExpirationSetInterval(customInterval
?: number): void {
1006 customInterval
?? Constants
.DEFAULT_RESERVATION_EXPIRATION_OBSERVATION_INTERVAL
;
1008 `${this.logPrefix()} Reservation expiration date interval is set to ${interval}
1009 and starts on charging station now`
1011 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1012 this.reservationExpirationSetInterval
= setInterval(async (): Promise
<void> => {
1013 const now
= new Date();
1014 if (this.hasEvses
) {
1015 for (const evseStatus
of this.evses
.values()) {
1016 for (const connectorStatus
of evseStatus
.connectors
.values()) {
1017 if (connectorStatus
?.reservation
?.expiryDate
< now
) {
1018 await this.removeReservation(
1019 connectorStatus
.reservation
,
1020 ReservationTerminationReason
.EXPIRED
1026 for (const connectorStatus
of this.connectors
.values()) {
1027 if (connectorStatus
?.reservation
?.expiryDate
< now
) {
1028 await this.removeReservation(
1029 connectorStatus
.reservation
,
1030 ReservationTerminationReason
.EXPIRED
1038 public restartReservationExpiryDateSetInterval(): void {
1039 this.stopReservationExpirationSetInterval();
1040 this.startReservationExpirationSetInterval();
1043 public validateIncomingRequestWithReservation(connectorId
: number, idTag
: string): boolean {
1044 return this.getReservationBy(ReservationFilterKey
.CONNECTOR_ID
, connectorId
)?.idTag
=== idTag
;
1047 public isConnectorReservable(
1048 reservationId
: number,
1050 connectorId
?: number
1052 const [alreadyExists
] = this.doesReservationExists({ id
: reservationId
});
1053 if (alreadyExists
) {
1054 return alreadyExists
;
1056 const userReservedAlready
= Utils
.isUndefined(
1057 this.getReservationBy(ReservationFilterKey
.ID_TAG
, idTag
)
1061 const notConnectorZero
= Utils
.isUndefined(connectorId
) ? true : connectorId
> 0;
1062 const freeConnectorsAvailable
= this.getNumberOfReservableConnectors() > 0;
1063 return !alreadyExists
&& !userReservedAlready
&& notConnectorZero
&& freeConnectorsAvailable
;
1066 private getNumberOfReservableConnectors(): number {
1067 let reservableConnectors
= 0;
1068 if (this.hasEvses
) {
1069 for (const evseStatus
of this.evses
.values()) {
1070 reservableConnectors
+= ChargingStationUtils
.countReservableConnectors(
1071 evseStatus
.connectors
1075 reservableConnectors
= ChargingStationUtils
.countReservableConnectors(this.connectors
);
1077 return reservableConnectors
- this.getNumberOfReservationsOnConnectorZero();
1080 private getNumberOfReservationsOnConnectorZero(): number {
1081 let numberOfReservations
= 0;
1082 if (this.hasEvses
&& this.evses
.get(0)?.connectors
.get(0)?.reservation
) {
1083 ++numberOfReservations
;
1084 } else if (this.connectors
.get(0)?.reservation
) {
1085 ++numberOfReservations
;
1087 return numberOfReservations
;
1090 private flushMessageBuffer(): void {
1091 if (this.messageBuffer
.size
> 0) {
1092 for (const message
of this.messageBuffer
.values()) {
1093 let beginId
: string;
1094 let commandName
: RequestCommand
;
1095 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
1096 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
1098 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
1099 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
1101 this.wsConnection
?.send(message
);
1102 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
1104 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
1106 )} payload sent: ${message}`
1108 this.messageBuffer
.delete(message
);
1113 private getSupervisionUrlOcppConfiguration(): boolean {
1114 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
1117 private stopReservationExpirationSetInterval(): void {
1118 if (this.reservationExpirationSetInterval
) {
1119 clearInterval(this.reservationExpirationSetInterval
);
1123 private getSupervisionUrlOcppKey(): string {
1124 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
1127 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
1128 let template
: ChargingStationTemplate
;
1130 if (this.sharedLRUCache
.hasChargingStationTemplate(this.templateFileHash
)) {
1131 template
= this.sharedLRUCache
.getChargingStationTemplate(this.templateFileHash
);
1133 const measureId
= `${FileType.ChargingStationTemplate} read`;
1134 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1135 template
= JSON
.parse(
1136 fs
.readFileSync(this.templateFile
, 'utf8')
1137 ) as ChargingStationTemplate
;
1138 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1139 template
.templateHash
= crypto
1140 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1141 .update(JSON
.stringify(template
))
1143 this.sharedLRUCache
.setChargingStationTemplate(template
);
1144 this.templateFileHash
= template
.templateHash
;
1147 handleFileException(
1149 FileType
.ChargingStationTemplate
,
1150 error
as NodeJS
.ErrnoException
,
1157 private getStationInfoFromTemplate(): ChargingStationInfo
{
1158 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
1159 ChargingStationUtils
.checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1160 ChargingStationUtils
.warnTemplateKeysDeprecation(
1165 if (stationTemplate
?.Connectors
) {
1166 ChargingStationUtils
.checkConnectorsConfiguration(
1172 const stationInfo
: ChargingStationInfo
=
1173 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
1174 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
1175 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
1179 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
1180 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
1181 if (Utils
.isNotEmptyArray(stationTemplate
?.power
)) {
1182 stationTemplate
.power
= stationTemplate
.power
as number[];
1183 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
1184 stationInfo
.maximumPower
=
1185 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1186 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
1187 : stationTemplate
.power
[powerArrayRandomIndex
];
1189 stationTemplate
.power
= stationTemplate
?.power
as number;
1190 stationInfo
.maximumPower
=
1191 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
1192 ? stationTemplate
.power
* 1000
1193 : stationTemplate
.power
;
1195 stationInfo
.firmwareVersionPattern
=
1196 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
1198 Utils
.isNotEmptyString(stationInfo
.firmwareVersion
) &&
1199 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
1202 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
1204 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
1207 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
1214 stationTemplate
?.firmwareUpgrade
?? {}
1216 stationInfo
.resetTime
= !Utils
.isNullOrUndefined(stationTemplate
?.resetTime
)
1217 ? stationTemplate
.resetTime
* 1000
1218 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1219 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
1223 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
1224 let stationInfo
: ChargingStationInfo
| undefined;
1225 if (this.getStationInfoPersistentConfiguration()) {
1226 stationInfo
= this.getConfigurationFromFile()?.stationInfo
;
1228 delete stationInfo
?.infoHash
;
1234 private getStationInfo(): ChargingStationInfo
{
1235 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1236 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
1238 // 1. charging station info from template
1239 // 2. charging station info from configuration file
1240 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1241 return stationInfoFromFile
;
1243 stationInfoFromFile
&&
1244 ChargingStationUtils
.propagateSerialNumber(
1245 this.getTemplateFromFile(),
1246 stationInfoFromFile
,
1247 stationInfoFromTemplate
1249 return stationInfoFromTemplate
;
1252 private saveStationInfo(): void {
1253 if (this.getStationInfoPersistentConfiguration()) {
1254 this.saveConfiguration();
1258 private getOcppPersistentConfiguration(): boolean {
1259 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
1262 private getStationInfoPersistentConfiguration(): boolean {
1263 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1266 private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean {
1267 return this.stationInfo
?.automaticTransactionGeneratorPersistentConfiguration
?? true;
1270 private handleUnsupportedVersion(version
: OCPPVersion
) {
1271 const errorMsg
= `Unsupported protocol version '${version}' configured
1272 in template file ${this.templateFile}`;
1273 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1274 throw new BaseError(errorMsg
);
1277 private initialize(): void {
1278 const stationTemplate
= this.getTemplateFromFile();
1279 ChargingStationUtils
.checkTemplate(stationTemplate
, this.logPrefix(), this.templateFile
);
1280 this.configurationFile
= path
.join(
1281 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
1282 `${ChargingStationUtils.getHashId(this.index, stationTemplate)}.json`
1284 const chargingStationConfiguration
= this.getConfigurationFromFile();
1286 chargingStationConfiguration
?.stationInfo
?.templateHash
=== stationTemplate
?.templateHash
&&
1287 (chargingStationConfiguration
?.connectorsStatus
|| chargingStationConfiguration
?.evsesStatus
)
1289 this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration
);
1291 this.initializeConnectorsOrEvsesFromTemplate(stationTemplate
);
1293 this.stationInfo
= this.getStationInfo();
1295 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1296 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1297 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1299 const patternGroup
: number | undefined =
1300 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1301 this.stationInfo
.firmwareVersion
?.split('.').length
;
1302 const match
= this.stationInfo
?.firmwareVersion
1303 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1304 ?.slice(1, patternGroup
+ 1);
1305 const patchLevelIndex
= match
.length
- 1;
1306 match
[patchLevelIndex
] = (
1307 Utils
.convertToInt(match
[patchLevelIndex
]) +
1308 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1310 this.stationInfo
.firmwareVersion
= match
?.join('.');
1312 this.saveStationInfo();
1313 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1314 if (this.getEnableStatistics() === true) {
1315 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1316 this.stationInfo
.hashId
,
1317 this.stationInfo
.chargingStationId
,
1318 this.configuredSupervisionUrl
1321 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1324 this.powerDivider
= this.getPowerDivider();
1325 // OCPP configuration
1326 this.ocppConfiguration
= this.getOcppConfiguration();
1327 this.initializeOcppConfiguration();
1328 this.initializeOcppServices();
1329 if (this.stationInfo
?.autoRegister
=== true) {
1330 this.bootNotificationResponse
= {
1331 currentTime
: new Date(),
1332 interval
: this.getHeartbeatInterval() / 1000,
1333 status: RegistrationStatusEnumType
.ACCEPTED
,
1338 private initializeOcppServices(): void {
1339 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1340 switch (ocppVersion
) {
1341 case OCPPVersion
.VERSION_16
:
1342 this.ocppIncomingRequestService
=
1343 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1344 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1345 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1348 case OCPPVersion
.VERSION_20
:
1349 case OCPPVersion
.VERSION_201
:
1350 this.ocppIncomingRequestService
=
1351 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1352 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1353 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1357 this.handleUnsupportedVersion(ocppVersion
);
1362 private initializeOcppConfiguration(): void {
1364 !ChargingStationConfigurationUtils
.getConfigurationKey(
1366 StandardParametersKey
.HeartbeatInterval
1369 ChargingStationConfigurationUtils
.addConfigurationKey(
1371 StandardParametersKey
.HeartbeatInterval
,
1376 !ChargingStationConfigurationUtils
.getConfigurationKey(
1378 StandardParametersKey
.HeartBeatInterval
1381 ChargingStationConfigurationUtils
.addConfigurationKey(
1383 StandardParametersKey
.HeartBeatInterval
,
1389 this.getSupervisionUrlOcppConfiguration() &&
1390 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1391 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1393 ChargingStationConfigurationUtils
.addConfigurationKey(
1395 this.getSupervisionUrlOcppKey(),
1396 this.configuredSupervisionUrl
.href
,
1400 !this.getSupervisionUrlOcppConfiguration() &&
1401 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1402 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1404 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1406 this.getSupervisionUrlOcppKey(),
1411 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1412 !ChargingStationConfigurationUtils
.getConfigurationKey(
1414 this.stationInfo
.amperageLimitationOcppKey
1417 ChargingStationConfigurationUtils
.addConfigurationKey(
1419 this.stationInfo
.amperageLimitationOcppKey
,
1421 this.stationInfo
.maximumAmperage
*
1422 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1427 !ChargingStationConfigurationUtils
.getConfigurationKey(
1429 StandardParametersKey
.SupportedFeatureProfiles
1432 ChargingStationConfigurationUtils
.addConfigurationKey(
1434 StandardParametersKey
.SupportedFeatureProfiles
,
1435 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1438 ChargingStationConfigurationUtils
.addConfigurationKey(
1440 StandardParametersKey
.NumberOfConnectors
,
1441 this.getNumberOfConnectors().toString(),
1446 !ChargingStationConfigurationUtils
.getConfigurationKey(
1448 StandardParametersKey
.MeterValuesSampledData
1451 ChargingStationConfigurationUtils
.addConfigurationKey(
1453 StandardParametersKey
.MeterValuesSampledData
,
1454 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1458 !ChargingStationConfigurationUtils
.getConfigurationKey(
1460 StandardParametersKey
.ConnectorPhaseRotation
1463 const connectorsPhaseRotation
: string[] = [];
1464 if (this.hasEvses
) {
1465 for (const evseStatus
of this.evses
.values()) {
1466 for (const connectorId
of evseStatus
.connectors
.keys()) {
1467 connectorsPhaseRotation
.push(
1468 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1473 for (const connectorId
of this.connectors
.keys()) {
1474 connectorsPhaseRotation
.push(
1475 ChargingStationUtils
.getPhaseRotationValue(connectorId
, this.getNumberOfPhases())
1479 ChargingStationConfigurationUtils
.addConfigurationKey(
1481 StandardParametersKey
.ConnectorPhaseRotation
,
1482 connectorsPhaseRotation
.toString()
1486 !ChargingStationConfigurationUtils
.getConfigurationKey(
1488 StandardParametersKey
.AuthorizeRemoteTxRequests
1491 ChargingStationConfigurationUtils
.addConfigurationKey(
1493 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1498 !ChargingStationConfigurationUtils
.getConfigurationKey(
1500 StandardParametersKey
.LocalAuthListEnabled
1502 ChargingStationConfigurationUtils
.getConfigurationKey(
1504 StandardParametersKey
.SupportedFeatureProfiles
1505 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1507 ChargingStationConfigurationUtils
.addConfigurationKey(
1509 StandardParametersKey
.LocalAuthListEnabled
,
1514 !ChargingStationConfigurationUtils
.getConfigurationKey(
1516 StandardParametersKey
.ConnectionTimeOut
1519 ChargingStationConfigurationUtils
.addConfigurationKey(
1521 StandardParametersKey
.ConnectionTimeOut
,
1522 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1525 this.saveOcppConfiguration();
1528 private initializeConnectorsOrEvsesFromFile(configuration
: ChargingStationConfiguration
): void {
1529 if (configuration
?.connectorsStatus
&& !configuration
?.evsesStatus
) {
1530 for (const [connectorId
, connectorStatus
] of configuration
.connectorsStatus
.entries()) {
1531 this.connectors
.set(connectorId
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1533 } else if (configuration
?.evsesStatus
&& !configuration
?.connectorsStatus
) {
1534 for (const [evseId
, evseStatusConfiguration
] of configuration
.evsesStatus
.entries()) {
1535 const evseStatus
= Utils
.cloneObject
<EvseStatusConfiguration
>(evseStatusConfiguration
);
1536 delete evseStatus
.connectorsStatus
;
1537 this.evses
.set(evseId
, {
1538 ...(evseStatus
as EvseStatus
),
1539 connectors
: new Map
<number, ConnectorStatus
>(
1540 evseStatusConfiguration
.connectorsStatus
.map((connectorStatus
, connectorId
) => [
1547 } else if (configuration
?.evsesStatus
&& configuration
?.connectorsStatus
) {
1548 const errorMsg
= `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`;
1549 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1550 throw new BaseError(errorMsg
);
1552 const errorMsg
= `No connectors or evses defined in configuration file ${this.configurationFile}`;
1553 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1554 throw new BaseError(errorMsg
);
1558 private initializeConnectorsOrEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
) {
1559 if (stationTemplate
?.Connectors
&& !stationTemplate
?.Evses
) {
1560 this.initializeConnectorsFromTemplate(stationTemplate
);
1561 } else if (stationTemplate
?.Evses
&& !stationTemplate
?.Connectors
) {
1562 this.initializeEvsesFromTemplate(stationTemplate
);
1563 } else if (stationTemplate
?.Evses
&& stationTemplate
?.Connectors
) {
1564 const errorMsg
= `Connectors and evses defined at the same time in template file ${this.templateFile}`;
1565 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1566 throw new BaseError(errorMsg
);
1568 const errorMsg
= `No connectors or evses defined in template file ${this.templateFile}`;
1569 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1570 throw new BaseError(errorMsg
);
1574 private initializeConnectorsFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1575 if (!stationTemplate
?.Connectors
&& this.connectors
.size
=== 0) {
1576 const errorMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1577 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1578 throw new BaseError(errorMsg
);
1580 if (!stationTemplate
?.Connectors
[0]) {
1582 `${this.logPrefix()} Charging station information from template ${
1584 } with no connector id 0 configuration`
1587 if (stationTemplate
?.Connectors
) {
1588 const { configuredMaxConnectors
, templateMaxConnectors
, templateMaxAvailableConnectors
} =
1589 ChargingStationUtils
.checkConnectorsConfiguration(
1594 const connectorsConfigHash
= crypto
1595 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1597 `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`
1600 const connectorsConfigChanged
=
1601 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1602 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1603 connectorsConfigChanged
&& this.connectors
.clear();
1604 this.connectorsConfigurationHash
= connectorsConfigHash
;
1605 if (templateMaxConnectors
> 0) {
1606 for (let connectorId
= 0; connectorId
<= configuredMaxConnectors
; connectorId
++) {
1608 connectorId
=== 0 &&
1609 (!stationTemplate
?.Connectors
[connectorId
] ||
1610 this.getUseConnectorId0(stationTemplate
) === false)
1614 const templateConnectorId
=
1615 connectorId
> 0 && stationTemplate
?.randomConnectors
1616 ? Utils
.getRandomInteger(templateMaxAvailableConnectors
, 1)
1618 const connectorStatus
= stationTemplate
?.Connectors
[templateConnectorId
];
1619 ChargingStationUtils
.checkStationInfoConnectorStatus(
1620 templateConnectorId
,
1625 this.connectors
.set(connectorId
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1627 ChargingStationUtils
.initializeConnectorsMapStatus(this.connectors
, this.logPrefix());
1628 this.saveConnectorsStatus();
1631 `${this.logPrefix()} Charging station information from template ${
1633 } with no connectors configuration defined, cannot create connectors`
1639 `${this.logPrefix()} Charging station information from template ${
1641 } with no connectors configuration defined, using already defined connectors`
1646 private initializeEvsesFromTemplate(stationTemplate
: ChargingStationTemplate
): void {
1647 if (!stationTemplate
?.Evses
&& this.evses
.size
=== 0) {
1648 const errorMsg
= `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`;
1649 logger
.error(`${this.logPrefix()} ${errorMsg}`);
1650 throw new BaseError(errorMsg
);
1652 if (!stationTemplate
?.Evses
[0]) {
1654 `${this.logPrefix()} Charging station information from template ${
1656 } with no evse id 0 configuration`
1659 if (!stationTemplate
?.Evses
[0]?.Connectors
[0]) {
1661 `${this.logPrefix()} Charging station information from template ${
1663 } with evse id 0 with no connector id 0 configuration`
1666 if (stationTemplate
?.Evses
) {
1667 const evsesConfigHash
= crypto
1668 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1669 .update(JSON
.stringify(stationTemplate
?.Evses
))
1671 const evsesConfigChanged
=
1672 this.evses
?.size
!== 0 && this.evsesConfigurationHash
!== evsesConfigHash
;
1673 if (this.evses
?.size
=== 0 || evsesConfigChanged
) {
1674 evsesConfigChanged
&& this.evses
.clear();
1675 this.evsesConfigurationHash
= evsesConfigHash
;
1676 const templateMaxEvses
= ChargingStationUtils
.getMaxNumberOfEvses(stationTemplate
?.Evses
);
1677 if (templateMaxEvses
> 0) {
1678 for (const evse
in stationTemplate
.Evses
) {
1679 const evseId
= Utils
.convertToInt(evse
);
1680 this.evses
.set(evseId
, {
1681 connectors
: ChargingStationUtils
.buildConnectorsMap(
1682 stationTemplate
?.Evses
[evse
]?.Connectors
,
1686 availability
: AvailabilityType
.Operative
,
1688 ChargingStationUtils
.initializeConnectorsMapStatus(
1689 this.evses
.get(evseId
)?.connectors
,
1693 this.saveEvsesStatus();
1696 `${this.logPrefix()} Charging station information from template ${
1698 } with no evses configuration defined, cannot create evses`
1704 `${this.logPrefix()} Charging station information from template ${
1706 } with no evses configuration defined, using already defined evses`
1711 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1712 let configuration
: ChargingStationConfiguration
| undefined;
1713 if (Utils
.isNotEmptyString(this.configurationFile
) && fs
.existsSync(this.configurationFile
)) {
1715 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1716 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1717 this.configurationFileHash
1720 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1721 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1722 configuration
= JSON
.parse(
1723 fs
.readFileSync(this.configurationFile
, 'utf8')
1724 ) as ChargingStationConfiguration
;
1725 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1726 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1727 this.configurationFileHash
= configuration
.configurationHash
;
1730 handleFileException(
1731 this.configurationFile
,
1732 FileType
.ChargingStationConfiguration
,
1733 error
as NodeJS
.ErrnoException
,
1738 return configuration
;
1741 private saveAutomaticTransactionGeneratorConfiguration(): void {
1742 if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) {
1743 this.saveConfiguration();
1747 private saveConnectorsStatus() {
1748 this.saveConfiguration();
1751 private saveEvsesStatus() {
1752 this.saveConfiguration();
1755 private saveConfiguration(): void {
1756 if (Utils
.isNotEmptyString(this.configurationFile
)) {
1758 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1759 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1761 let configurationData
: ChargingStationConfiguration
=
1762 Utils
.cloneObject
<ChargingStationConfiguration
>(this.getConfigurationFromFile()) ?? {};
1763 if (this.getStationInfoPersistentConfiguration() && this.stationInfo
) {
1764 configurationData
.stationInfo
= this.stationInfo
;
1766 delete configurationData
.stationInfo
;
1768 if (this.getOcppPersistentConfiguration() && this.ocppConfiguration
?.configurationKey
) {
1769 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1771 delete configurationData
.configurationKey
;
1773 configurationData
= merge
<ChargingStationConfiguration
>(
1775 buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
1778 !this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
1779 !this.getAutomaticTransactionGeneratorConfiguration()
1781 delete configurationData
.automaticTransactionGenerator
;
1783 if (this.connectors
.size
> 0) {
1784 configurationData
.connectorsStatus
= buildConnectorsStatus(this);
1786 delete configurationData
.connectorsStatus
;
1788 if (this.evses
.size
> 0) {
1789 configurationData
.evsesStatus
= buildEvsesStatus(this);
1791 delete configurationData
.evsesStatus
;
1793 delete configurationData
.configurationHash
;
1794 const configurationHash
= crypto
1795 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1798 stationInfo
: configurationData
.stationInfo
,
1799 configurationKey
: configurationData
.configurationKey
,
1800 automaticTransactionGenerator
: configurationData
.automaticTransactionGenerator
,
1801 } as ChargingStationConfiguration
)
1804 if (this.configurationFileHash
!== configurationHash
) {
1805 AsyncLock
.acquire(AsyncLockType
.configuration
)
1807 configurationData
.configurationHash
= configurationHash
;
1808 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1809 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1810 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1811 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1812 fs
.closeSync(fileDescriptor
);
1813 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1814 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1815 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1816 this.configurationFileHash
= configurationHash
;
1819 handleFileException(
1820 this.configurationFile
,
1821 FileType
.ChargingStationConfiguration
,
1822 error
as NodeJS
.ErrnoException
,
1827 AsyncLock
.release(AsyncLockType
.configuration
).catch(Constants
.EMPTY_FUNCTION
);
1831 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1832 this.configurationFile
1837 handleFileException(
1838 this.configurationFile
,
1839 FileType
.ChargingStationConfiguration
,
1840 error
as NodeJS
.ErrnoException
,
1846 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1851 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1852 return this.getTemplateFromFile()?.Configuration
;
1855 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1856 const configurationKey
= this.getConfigurationFromFile()?.configurationKey
;
1857 if (this.getOcppPersistentConfiguration() === true && configurationKey
) {
1858 return { configurationKey
};
1863 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1864 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1865 this.getOcppConfigurationFromFile();
1866 if (!ocppConfiguration
) {
1867 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1869 return ocppConfiguration
;
1872 private async onOpen(): Promise
<void> {
1873 if (this.isWebSocketConnectionOpened() === true) {
1875 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1877 if (this.isRegistered() === false) {
1878 // Send BootNotification
1879 let registrationRetryCount
= 0;
1881 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1882 BootNotificationRequest
,
1883 BootNotificationResponse
1884 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1885 skipBufferingOnError
: true,
1887 if (this.isRegistered() === false) {
1888 this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount
;
1890 this?.bootNotificationResponse
?.interval
1891 ? this.bootNotificationResponse
.interval
* 1000
1892 : Constants
.DEFAULT_BOOT_NOTIFICATION_INTERVAL
1896 this.isRegistered() === false &&
1897 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1898 this.getRegistrationMaxRetries() === -1)
1901 if (this.isRegistered() === true) {
1902 if (this.inAcceptedState() === true) {
1903 await this.startMessageSequence();
1907 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1910 this.wsConnectionRestarted
= false;
1911 this.autoReconnectRetryCount
= 0;
1912 parentPort
?.postMessage(buildUpdatedMessage(this));
1915 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1920 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1923 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1924 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1926 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1928 )}' and reason '${reason.toString()}'`
1930 this.autoReconnectRetryCount
= 0;
1935 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1937 )}' and reason '${reason.toString()}'`
1939 this.started
=== true && (await this.reconnect());
1942 parentPort
?.postMessage(buildUpdatedMessage(this));
1945 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1946 const cachedRequest
= this.requests
.get(messageId
);
1947 if (Array.isArray(cachedRequest
) === true) {
1948 return cachedRequest
;
1950 throw new OCPPError(
1951 ErrorType
.PROTOCOL_ERROR
,
1952 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1954 )} is not an array`,
1956 cachedRequest
as JsonType
1960 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1961 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1962 if (this.getEnableStatistics() === true) {
1963 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1966 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1970 // Process the message
1971 await this.ocppIncomingRequestService
.incomingRequestHandler(
1979 private handleResponseMessage(response
: Response
): void {
1980 const [messageType
, messageId
, commandPayload
] = response
;
1981 if (this.requests
.has(messageId
) === false) {
1983 throw new OCPPError(
1984 ErrorType
.INTERNAL_ERROR
,
1985 `Response for unknown message id ${messageId}`,
1991 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1996 `${this.logPrefix()} << Command '${
1997 requestCommandName ?? Constants.UNKNOWN_COMMAND
1998 }' received response payload: ${JSON.stringify(response)}`
2000 responseCallback(commandPayload
, requestPayload
);
2003 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
2004 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
2005 if (this.requests
.has(messageId
) === false) {
2007 throw new OCPPError(
2008 ErrorType
.INTERNAL_ERROR
,
2009 `Error response for unknown message id ${messageId}`,
2011 { errorType
, errorMessage
, errorDetails
}
2014 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
2016 `${this.logPrefix()} << Command '${
2017 requestCommandName ?? Constants.UNKNOWN_COMMAND
2018 }' received error response payload: ${JSON.stringify(errorResponse)}`
2020 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
2023 private async onMessage(data
: RawData
): Promise
<void> {
2024 let request
: IncomingRequest
| Response
| ErrorResponse
;
2025 let messageType
: number;
2026 let errorMsg
: string;
2028 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
2029 if (Array.isArray(request
) === true) {
2030 [messageType
] = request
;
2031 // Check the type of message
2032 switch (messageType
) {
2034 case MessageType
.CALL_MESSAGE
:
2035 await this.handleIncomingMessage(request
as IncomingRequest
);
2038 case MessageType
.CALL_RESULT_MESSAGE
:
2039 this.handleResponseMessage(request
as Response
);
2042 case MessageType
.CALL_ERROR_MESSAGE
:
2043 this.handleErrorMessage(request
as ErrorResponse
);
2047 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2048 errorMsg
= `Wrong message type ${messageType}`;
2049 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2050 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errorMsg
);
2052 parentPort
?.postMessage(buildUpdatedMessage(this));
2054 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
2059 let commandName
: IncomingRequestCommand
;
2060 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
2061 let errorCallback
: ErrorCallback
;
2062 const [, messageId
] = request
;
2063 switch (messageType
) {
2064 case MessageType
.CALL_MESSAGE
:
2065 [, , commandName
] = request
as IncomingRequest
;
2067 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
2069 case MessageType
.CALL_RESULT_MESSAGE
:
2070 case MessageType
.CALL_ERROR_MESSAGE
:
2071 if (this.requests
.has(messageId
) === true) {
2072 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
2073 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
2074 errorCallback(error
as OCPPError
, false);
2076 // Remove the request from the cache in case of error at response handling
2077 this.requests
.delete(messageId
);
2081 if (error
instanceof OCPPError
=== false) {
2083 `${this.logPrefix()} Error thrown at incoming OCPP command '${
2084 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2085 }' message '${data.toString()}' handling is not an OCPPError:`,
2090 `${this.logPrefix()} Incoming OCPP command '${
2091 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
2092 }' message '${data.toString()}'${
2093 messageType !== MessageType.CALL_MESSAGE
2094 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
2096 } processing error:`,
2102 private onPing(): void {
2103 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
2106 private onPong(): void {
2107 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
2110 private onError(error
: WSError
): void {
2111 this.closeWSConnection();
2112 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
2115 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
2116 if (this.getMeteringPerTransaction() === true) {
2119 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
2120 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
2125 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
2126 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
2130 private getUseConnectorId0(stationTemplate
?: ChargingStationTemplate
): boolean {
2131 return stationTemplate
?.useConnectorId0
?? true;
2134 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
2135 if (this.hasEvses
) {
2136 for (const [evseId
, evseStatus
] of this.evses
) {
2140 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2141 if (connectorStatus
.transactionStarted
=== true) {
2142 await this.stopTransactionOnConnector(connectorId
, reason
);
2147 for (const connectorId
of this.connectors
.keys()) {
2148 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
2149 await this.stopTransactionOnConnector(connectorId
, reason
);
2156 private getConnectionTimeout(): number {
2158 ChargingStationConfigurationUtils
.getConfigurationKey(
2160 StandardParametersKey
.ConnectionTimeOut
2165 ChargingStationConfigurationUtils
.getConfigurationKey(
2167 StandardParametersKey
.ConnectionTimeOut
2169 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
2172 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
2175 // -1 for unlimited, 0 for disabling
2176 private getAutoReconnectMaxRetries(): number | undefined {
2178 this.stationInfo
.autoReconnectMaxRetries
?? Configuration
.getAutoReconnectMaxRetries() ?? -1
2183 private getRegistrationMaxRetries(): number | undefined {
2184 return this.stationInfo
.registrationMaxRetries
?? -1;
2187 private getPowerDivider(): number {
2188 let powerDivider
= this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors();
2189 if (this.stationInfo
?.powerSharedByConnectors
) {
2190 powerDivider
= this.getNumberOfRunningTransactions();
2192 return powerDivider
;
2195 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
2196 const maximumPower
= this.getMaximumPower(stationInfo
);
2197 switch (this.getCurrentOutType(stationInfo
)) {
2198 case CurrentType
.AC
:
2199 return ACElectricUtils
.amperagePerPhaseFromPower(
2200 this.getNumberOfPhases(stationInfo
),
2201 maximumPower
/ (this.hasEvses
? this.getNumberOfEvses() : this.getNumberOfConnectors()),
2202 this.getVoltageOut(stationInfo
)
2204 case CurrentType
.DC
:
2205 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
2209 private getAmperageLimitation(): number | undefined {
2211 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
2212 ChargingStationConfigurationUtils
.getConfigurationKey(
2214 this.stationInfo
.amperageLimitationOcppKey
2219 ChargingStationConfigurationUtils
.getConfigurationKey(
2221 this.stationInfo
.amperageLimitationOcppKey
2223 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
2228 private async startMessageSequence(): Promise
<void> {
2229 if (this.stationInfo
?.autoRegister
=== true) {
2230 await this.ocppRequestService
.requestHandler
<
2231 BootNotificationRequest
,
2232 BootNotificationResponse
2233 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
2234 skipBufferingOnError
: true,
2237 // Start WebSocket ping
2238 this.startWebSocketPing();
2240 this.startHeartbeat();
2241 // Initialize connectors status
2242 if (this.hasEvses
) {
2243 for (const [evseId
, evseStatus
] of this.evses
) {
2245 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2246 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
2251 await OCPPServiceUtils
.sendAndSetConnectorStatus(
2254 connectorBootStatus
,
2261 for (const connectorId
of this.connectors
.keys()) {
2262 if (connectorId
> 0) {
2263 const connectorBootStatus
= ChargingStationUtils
.getBootConnectorStatus(
2266 this.getConnectorStatus(connectorId
)
2268 await OCPPServiceUtils
.sendAndSetConnectorStatus(this, connectorId
, connectorBootStatus
);
2272 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
2273 await this.ocppRequestService
.requestHandler
<
2274 FirmwareStatusNotificationRequest
,
2275 FirmwareStatusNotificationResponse
2276 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
2277 status: FirmwareStatus
.Installed
,
2279 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
2283 if (this.getAutomaticTransactionGeneratorConfiguration()?.enable
=== true) {
2284 this.startAutomaticTransactionGenerator();
2286 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
2289 private async stopMessageSequence(
2290 reason
: StopTransactionReason
= StopTransactionReason
.NONE
2292 // Stop WebSocket ping
2293 this.stopWebSocketPing();
2295 this.stopHeartbeat();
2296 // Stop ongoing transactions
2297 if (this.automaticTransactionGenerator
?.started
=== true) {
2298 this.stopAutomaticTransactionGenerator();
2300 await this.stopRunningTransactions(reason
);
2302 if (this.hasEvses
) {
2303 for (const [evseId
, evseStatus
] of this.evses
) {
2305 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
2306 await this.ocppRequestService
.requestHandler
<
2307 StatusNotificationRequest
,
2308 StatusNotificationResponse
2311 RequestCommand
.STATUS_NOTIFICATION
,
2312 OCPPServiceUtils
.buildStatusNotificationRequest(
2315 ConnectorStatusEnum
.Unavailable
,
2319 delete connectorStatus
?.status;
2324 for (const connectorId
of this.connectors
.keys()) {
2325 if (connectorId
> 0) {
2326 await this.ocppRequestService
.requestHandler
<
2327 StatusNotificationRequest
,
2328 StatusNotificationResponse
2331 RequestCommand
.STATUS_NOTIFICATION
,
2332 OCPPServiceUtils
.buildStatusNotificationRequest(
2335 ConnectorStatusEnum
.Unavailable
2338 delete this.getConnectorStatus(connectorId
)?.status;
2344 private startWebSocketPing(): void {
2345 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
2347 StandardParametersKey
.WebSocketPingInterval
2349 ? Utils
.convertToInt(
2350 ChargingStationConfigurationUtils
.getConfigurationKey(
2352 StandardParametersKey
.WebSocketPingInterval
2356 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2357 this.webSocketPingSetInterval
= setInterval(() => {
2358 if (this.isWebSocketConnectionOpened() === true) {
2359 this.wsConnection
?.ping();
2361 }, webSocketPingInterval
* 1000);
2363 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
2364 webSocketPingInterval
2367 } else if (this.webSocketPingSetInterval
) {
2369 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
2370 webSocketPingInterval
2375 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
2380 private stopWebSocketPing(): void {
2381 if (this.webSocketPingSetInterval
) {
2382 clearInterval(this.webSocketPingSetInterval
);
2383 delete this.webSocketPingSetInterval
;
2387 private getConfiguredSupervisionUrl(): URL
{
2388 let configuredSupervisionUrl
: string;
2389 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
2390 if (Utils
.isNotEmptyArray(supervisionUrls
)) {
2391 let configuredSupervisionUrlIndex
: number;
2392 switch (Configuration
.getSupervisionUrlDistribution()) {
2393 case SupervisionUrlDistribution
.RANDOM
:
2394 configuredSupervisionUrlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
2396 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2397 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
2399 Object.values(SupervisionUrlDistribution
).includes(
2400 Configuration
.getSupervisionUrlDistribution()
2403 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2404 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
2407 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2410 configuredSupervisionUrl
= supervisionUrls
[configuredSupervisionUrlIndex
];
2412 configuredSupervisionUrl
= supervisionUrls
as string;
2414 if (Utils
.isNotEmptyString(configuredSupervisionUrl
)) {
2415 return new URL(configuredSupervisionUrl
);
2417 const errorMsg
= 'No supervision url(s) configured';
2418 logger
.error(`${this.logPrefix()} ${errorMsg}`);
2419 throw new BaseError(`${errorMsg}`);
2422 private stopHeartbeat(): void {
2423 if (this.heartbeatSetInterval
) {
2424 clearInterval(this.heartbeatSetInterval
);
2425 delete this.heartbeatSetInterval
;
2429 private terminateWSConnection(): void {
2430 if (this.isWebSocketConnectionOpened() === true) {
2431 this.wsConnection
?.terminate();
2432 this.wsConnection
= null;
2436 private getReconnectExponentialDelay(): boolean {
2437 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2440 private async reconnect(): Promise
<void> {
2441 // Stop WebSocket ping
2442 this.stopWebSocketPing();
2444 this.stopHeartbeat();
2445 // Stop the ATG if needed
2446 if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure
=== true) {
2447 this.stopAutomaticTransactionGenerator();
2450 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2451 this.getAutoReconnectMaxRetries() === -1
2453 ++this.autoReconnectRetryCount
;
2454 const reconnectDelay
= this.getReconnectExponentialDelay()
2455 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2456 : this.getConnectionTimeout() * 1000;
2457 const reconnectDelayWithdraw
= 1000;
2458 const reconnectTimeout
=
2459 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2460 ? reconnectDelay
- reconnectDelayWithdraw
2463 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2466 )}ms, timeout ${reconnectTimeout}ms`
2468 await Utils
.sleep(reconnectDelay
);
2470 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2472 this.openWSConnection(
2474 ...(this.stationInfo
?.wsOptions
?? {}),
2475 handshakeTimeout
: reconnectTimeout
,
2477 { closeOpened
: true }
2479 this.wsConnectionRestarted
= true;
2480 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2482 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2483 this.autoReconnectRetryCount
2484 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`