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';
14 AutomaticTransactionGenerator
,
15 ChargingStationConfigurationUtils
,
17 ChargingStationWorkerBroadcastChannel
,
22 // OCPP16IncomingRequestService,
24 // OCPP16ResponseService,
26 OCPP20IncomingRequestService
,
28 // OCPP20ResponseService,
29 type OCPPIncomingRequestService
,
30 type OCPPRequestService
,
33 import { OCPP16IncomingRequestService
} from
'./ocpp/1.6/OCPP16IncomingRequestService';
34 import { OCPP16ResponseService
} from
'./ocpp/1.6/OCPP16ResponseService';
35 import { OCPP20ResponseService
} from
'./ocpp/2.0/OCPP20ResponseService';
36 import { OCPPServiceUtils
} from
'./ocpp/OCPPServiceUtils';
37 import { BaseError
, OCPPError
} from
'../exception';
38 import { PerformanceStatistics
} from
'../performance';
40 type AutomaticTransactionGeneratorConfiguration
,
42 type BootNotificationRequest
,
43 type BootNotificationResponse
,
45 type ChargingStationConfiguration
,
46 type ChargingStationInfo
,
47 type ChargingStationOcppConfiguration
,
48 type ChargingStationTemplate
,
49 ConnectorPhaseRotation
,
58 type FirmwareStatusNotificationRequest
,
59 type FirmwareStatusNotificationResponse
,
61 type HeartbeatRequest
,
62 type HeartbeatResponse
,
64 type IncomingRequestCommand
,
69 type MeterValuesRequest
,
70 type MeterValuesResponse
,
74 RegistrationStatusEnumType
,
77 type ResponseCallback
,
78 StandardParametersKey
,
79 type StatusNotificationRequest
,
80 type StatusNotificationResponse
,
81 StopTransactionReason
,
82 type StopTransactionRequest
,
83 type StopTransactionResponse
,
84 SupervisionUrlDistribution
,
85 SupportedFeatureProfiles
,
88 WebSocketCloseEventStatusCode
,
101 export class ChargingStation
{
102 public readonly index
: number;
103 public readonly templateFile
: string;
104 public stationInfo
!: ChargingStationInfo
;
105 public started
: boolean;
106 public starting
: boolean;
107 public authorizedTagsCache
: AuthorizedTagsCache
;
108 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
109 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
110 public wsConnection
!: WebSocket
| null;
111 public readonly connectors
: Map
<number, ConnectorStatus
>;
112 public readonly requests
: Map
<string, CachedRequest
>;
113 public performanceStatistics
!: PerformanceStatistics
| undefined;
114 public heartbeatSetInterval
!: NodeJS
.Timeout
;
115 public ocppRequestService
!: OCPPRequestService
;
116 public bootNotificationRequest
!: BootNotificationRequest
;
117 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
118 public powerDivider
!: number;
119 private stopping
: boolean;
120 private configurationFile
!: string;
121 private configurationFileHash
!: string;
122 private connectorsConfigurationHash
!: string;
123 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
124 private readonly messageBuffer
: Set
<string>;
125 private configuredSupervisionUrl
!: URL
;
126 private configuredSupervisionUrlIndex
!: number;
127 private wsConnectionRestarted
: boolean;
128 private autoReconnectRetryCount
: number;
129 private templateFileWatcher
!: fs
.FSWatcher
| undefined;
130 private readonly sharedLRUCache
: SharedLRUCache
;
131 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
132 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
134 constructor(index
: number, templateFile
: string) {
135 this.started
= false;
136 this.starting
= false;
137 this.stopping
= false;
138 this.wsConnectionRestarted
= false;
139 this.autoReconnectRetryCount
= 0;
141 this.templateFile
= templateFile
;
142 this.connectors
= new Map
<number, ConnectorStatus
>();
143 this.requests
= new Map
<string, CachedRequest
>();
144 this.messageBuffer
= new Set
<string>();
145 this.sharedLRUCache
= SharedLRUCache
.getInstance();
146 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
147 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
152 private get
wsConnectionUrl(): URL
{
155 this.getSupervisionUrlOcppConfiguration()
156 ? ChargingStationConfigurationUtils.getConfigurationKey(
158 this.getSupervisionUrlOcppKey()
160 : this.configuredSupervisionUrl.href
161 }/${this.stationInfo.chargingStationId}`
165 public logPrefix
= (): string => {
166 return Utils
.logPrefix(
168 (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId) &&
169 this?.stationInfo?.chargingStationId) ??
170 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile()) ??
176 public hasAuthorizedTags(): boolean {
177 return Utils
.isNotEmptyArray(
178 this.authorizedTagsCache
.getAuthorizedTags(
179 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
184 public getEnableStatistics(): boolean {
185 return this.stationInfo
.enableStatistics
?? false;
188 public getMustAuthorizeAtRemoteStart(): boolean {
189 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
192 public getPayloadSchemaValidation(): boolean {
193 return this.stationInfo
.payloadSchemaValidation
?? true;
196 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
197 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
198 switch (this.getCurrentOutType(stationInfo
)) {
200 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
201 ? localStationInfo
.numberOfPhases
208 public isWebSocketConnectionOpened(): boolean {
209 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
212 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
213 return this?.bootNotificationResponse
?.status;
216 public isInUnknownState(): boolean {
217 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
220 public isInPendingState(): boolean {
221 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
224 public isInAcceptedState(): boolean {
225 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
228 public isInRejectedState(): boolean {
229 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
232 public isRegistered(): boolean {
234 this.isInUnknownState() === false &&
235 (this.isInAcceptedState() === true || this.isInPendingState() === true)
239 public isChargingStationAvailable(): boolean {
240 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.OPERATIVE
;
243 public isConnectorAvailable(id
: number): boolean {
244 return id
> 0 && this.getConnectorStatus(id
)?.availability
=== AvailabilityType
.OPERATIVE
;
247 public getNumberOfConnectors(): number {
248 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
251 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
252 return this.connectors
.get(id
);
255 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
256 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
259 public getOcppStrictCompliance(): boolean {
260 return this.stationInfo
?.ocppStrictCompliance
?? false;
263 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
264 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
265 this.getCurrentOutType(stationInfo
),
269 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
270 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
271 ? localStationInfo
.voltageOut
275 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
276 const localStationInfo
= stationInfo
?? this.stationInfo
;
277 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
280 public getConnectorMaximumAvailablePower(connectorId
: number): number {
281 let connectorAmperageLimitationPowerLimit
: number;
283 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
284 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
286 connectorAmperageLimitationPowerLimit
=
287 (this.getCurrentOutType() === CurrentType
.AC
288 ? ACElectricUtils
.powerTotal(
289 this.getNumberOfPhases(),
290 this.getVoltageOut(),
291 this.getAmperageLimitation() * this.getNumberOfConnectors()
293 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
296 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
297 const connectorChargingProfilesPowerLimit
=
298 ChargingStationUtils
.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
300 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
301 isNaN(connectorAmperageLimitationPowerLimit
)
303 : connectorAmperageLimitationPowerLimit
,
304 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
308 public getTransactionIdTag(transactionId
: number): string | undefined {
309 for (const connectorId
of this.connectors
.keys()) {
312 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
314 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
319 public getOutOfOrderEndMeterValues(): boolean {
320 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
323 public getBeginEndMeterValues(): boolean {
324 return this.stationInfo
?.beginEndMeterValues
?? false;
327 public getMeteringPerTransaction(): boolean {
328 return this.stationInfo
?.meteringPerTransaction
?? true;
331 public getTransactionDataMeterValues(): boolean {
332 return this.stationInfo
?.transactionDataMeterValues
?? false;
335 public getMainVoltageMeterValues(): boolean {
336 return this.stationInfo
?.mainVoltageMeterValues
?? true;
339 public getPhaseLineToLineVoltageMeterValues(): boolean {
340 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
343 public getCustomValueLimitationMeterValues(): boolean {
344 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
347 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
348 for (const connectorId
of this.connectors
.keys()) {
351 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
358 public getEnergyActiveImportRegisterByTransactionId(
359 transactionId
: number,
362 return this.getEnergyActiveImportRegister(
363 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
368 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
369 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
372 public getAuthorizeRemoteTxRequests(): boolean {
373 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
375 StandardParametersKey
.AuthorizeRemoteTxRequests
377 return authorizeRemoteTxRequests
378 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
382 public getLocalAuthListEnabled(): boolean {
383 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
385 StandardParametersKey
.LocalAuthListEnabled
387 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
390 public startHeartbeat(): void {
392 this.getHeartbeatInterval() &&
393 this.getHeartbeatInterval() > 0 &&
394 !this.heartbeatSetInterval
396 this.heartbeatSetInterval
= setInterval(() => {
397 this.ocppRequestService
398 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
401 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
405 }, this.getHeartbeatInterval());
407 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
408 this.getHeartbeatInterval()
411 } else if (this.heartbeatSetInterval
) {
413 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
414 this.getHeartbeatInterval()
419 `${this.logPrefix()} Heartbeat interval set to ${
420 this.getHeartbeatInterval()
421 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
422 : this.getHeartbeatInterval()
423 }, not starting the heartbeat`
428 public restartHeartbeat(): void {
430 this.stopHeartbeat();
432 this.startHeartbeat();
435 public restartWebSocketPing(): void {
436 // Stop WebSocket ping
437 this.stopWebSocketPing();
438 // Start WebSocket ping
439 this.startWebSocketPing();
442 public startMeterValues(connectorId
: number, interval
: number): void {
443 if (connectorId
=== 0) {
445 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
449 if (!this.getConnectorStatus(connectorId
)) {
451 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
455 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
457 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
461 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
462 Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
465 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
470 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
471 // FIXME: Implement OCPP version agnostic helpers
472 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
475 this.getConnectorStatus(connectorId
).transactionId
,
478 this.ocppRequestService
479 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
481 RequestCommand
.METER_VALUES
,
484 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
485 meterValue
: [meterValue
],
490 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
497 `${this.logPrefix()} Charging station ${
498 StandardParametersKey.MeterValueSampleInterval
499 } configuration set to ${
500 interval ? Utils.formatDurationMilliSeconds(interval) : interval
501 }, not sending MeterValues`
506 public start(): void {
507 if (this.started
=== false) {
508 if (this.starting
=== false) {
509 this.starting
= true;
510 if (this.getEnableStatistics() === true) {
511 this.performanceStatistics
?.start();
513 this.openWSConnection();
514 // Monitor charging station template file
515 this.templateFileWatcher
= FileUtils
.watchJsonFile(
517 FileType
.ChargingStationTemplate
,
520 (event
, filename
): void => {
521 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
524 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
526 } file have changed, reload`
528 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
532 this.stopAutomaticTransactionGenerator();
534 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
536 this.startAutomaticTransactionGenerator();
538 if (this.getEnableStatistics() === true) {
539 this.performanceStatistics
?.restart();
541 this.performanceStatistics
?.stop();
543 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
546 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
554 parentPort
?.postMessage(MessageChannelUtils
.buildStartedMessage(this));
555 this.starting
= false;
557 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
560 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
564 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
565 if (this.started
=== true) {
566 if (this.stopping
=== false) {
567 this.stopping
= true;
568 await this.stopMessageSequence(reason
);
569 this.closeWSConnection();
570 if (this.getEnableStatistics() === true) {
571 this.performanceStatistics
?.stop();
573 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
574 this.templateFileWatcher
?.close();
575 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
576 this.bootNotificationResponse
= undefined;
577 this.started
= false;
578 parentPort
?.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
579 this.stopping
= false;
581 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
584 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
588 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
589 await this.stop(reason
);
590 await Utils
.sleep(this.stationInfo
.resetTime
);
595 public saveOcppConfiguration(): void {
596 if (this.getOcppPersistentConfiguration()) {
597 this.saveConfiguration();
601 public resetConnectorStatus(connectorId
: number): void {
602 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
603 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
604 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
605 this.getConnectorStatus(connectorId
).transactionStarted
= false;
606 delete this.getConnectorStatus(connectorId
)?.localAuthorizeIdTag
;
607 delete this.getConnectorStatus(connectorId
)?.authorizeIdTag
;
608 delete this.getConnectorStatus(connectorId
)?.transactionId
;
609 delete this.getConnectorStatus(connectorId
)?.transactionIdTag
;
610 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
611 delete this.getConnectorStatus(connectorId
)?.transactionBeginMeterValue
;
612 this.stopMeterValues(connectorId
);
613 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
616 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
617 return ChargingStationConfigurationUtils
.getConfigurationKey(
619 StandardParametersKey
.SupportedFeatureProfiles
620 )?.value
?.includes(featureProfile
);
623 public bufferMessage(message
: string): void {
624 this.messageBuffer
.add(message
);
627 public openWSConnection(
628 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
629 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
631 terminateOpened
: false,
634 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
635 params
.closeOpened
= params
?.closeOpened
?? false;
636 params
.terminateOpened
= params
?.terminateOpened
?? false;
637 if (this.started
=== false && this.starting
=== false) {
639 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
644 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
645 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
647 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
649 if (params
?.closeOpened
) {
650 this.closeWSConnection();
652 if (params
?.terminateOpened
) {
653 this.terminateWSConnection();
655 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
656 let protocol
: string;
657 switch (ocppVersion
) {
658 case OCPPVersion
.VERSION_16
:
659 case OCPPVersion
.VERSION_20
:
660 case OCPPVersion
.VERSION_201
:
661 protocol
= `ocpp${ocppVersion}`;
664 this.handleUnsupportedVersion(ocppVersion
);
668 if (this.isWebSocketConnectionOpened() === true) {
670 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
676 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
679 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
681 // Handle WebSocket message
682 this.wsConnection
.on(
684 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
686 // Handle WebSocket error
687 this.wsConnection
.on(
689 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
691 // Handle WebSocket close
692 this.wsConnection
.on(
694 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
696 // Handle WebSocket open
697 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
698 // Handle WebSocket ping
699 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
700 // Handle WebSocket pong
701 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
704 public closeWSConnection(): void {
705 if (this.isWebSocketConnectionOpened() === true) {
706 this.wsConnection
?.close();
707 this.wsConnection
= null;
711 public startAutomaticTransactionGenerator(
712 connectorIds
?: number[],
713 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
715 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
716 automaticTransactionGeneratorConfiguration
??
717 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
720 if (Utils
.isNotEmptyArray(connectorIds
)) {
721 for (const connectorId
of connectorIds
) {
722 this.automaticTransactionGenerator
?.startConnector(connectorId
);
725 this.automaticTransactionGenerator
?.start();
727 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
730 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
731 if (Utils
.isNotEmptyArray(connectorIds
)) {
732 for (const connectorId
of connectorIds
) {
733 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
736 this.automaticTransactionGenerator
?.stop();
738 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
741 public async stopTransactionOnConnector(
743 reason
= StopTransactionReason
.NONE
744 ): Promise
<StopTransactionResponse
> {
745 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
747 this.getBeginEndMeterValues() === true &&
748 this.getOcppStrictCompliance() === true &&
749 this.getOutOfOrderEndMeterValues() === false
751 // FIXME: Implement OCPP version agnostic helpers
752 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
755 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
757 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
759 RequestCommand
.METER_VALUES
,
763 meterValue
: [transactionEndMeterValue
],
767 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
769 RequestCommand
.STOP_TRANSACTION
,
772 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
778 private flushMessageBuffer(): void {
779 if (this.messageBuffer
.size
> 0) {
780 this.messageBuffer
.forEach((message
) => {
782 let commandName
: RequestCommand
;
783 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
784 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
786 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
787 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
789 this.wsConnection
?.send(message
);
790 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
792 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
794 )} payload sent: ${message}`
796 this.messageBuffer
.delete(message
);
801 private getSupervisionUrlOcppConfiguration(): boolean {
802 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
805 private getSupervisionUrlOcppKey(): string {
806 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
809 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
810 let template
: ChargingStationTemplate
;
812 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
813 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
815 const measureId
= `${FileType.ChargingStationTemplate} read`;
816 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
817 template
= JSON
.parse(
818 fs
.readFileSync(this.templateFile
, 'utf8')
819 ) as ChargingStationTemplate
;
820 PerformanceStatistics
.endMeasure(measureId
, beginId
);
821 template
.templateHash
= crypto
822 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
823 .update(JSON
.stringify(template
))
825 this.sharedLRUCache
.setChargingStationTemplate(template
);
828 FileUtils
.handleFileException(
830 FileType
.ChargingStationTemplate
,
831 error
as NodeJS
.ErrnoException
,
838 private getStationInfoFromTemplate(): ChargingStationInfo
{
839 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
840 if (Utils
.isNullOrUndefined(stationTemplate
)) {
841 const errorMsg
= `Failed to read charging station template file ${this.templateFile}`;
842 logger
.error(`${this.logPrefix()} ${errorMsg}`);
843 throw new BaseError(errorMsg
);
845 if (Utils
.isEmptyObject(stationTemplate
)) {
846 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
847 logger
.error(`${this.logPrefix()} ${errorMsg}`);
848 throw new BaseError(errorMsg
);
850 // Deprecation template keys section
851 ChargingStationUtils
.warnDeprecatedTemplateKey(
856 "Use 'supervisionUrls' instead"
858 ChargingStationUtils
.convertDeprecatedTemplateKey(
863 const stationInfo
: ChargingStationInfo
=
864 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
865 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
866 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
870 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
871 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
872 if (Utils
.isNotEmptyArray(stationTemplate
?.power
)) {
873 stationTemplate
.power
= stationTemplate
.power
as number[];
874 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
875 stationInfo
.maximumPower
=
876 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
877 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
878 : stationTemplate
.power
[powerArrayRandomIndex
];
880 stationTemplate
.power
= stationTemplate
?.power
as number;
881 stationInfo
.maximumPower
=
882 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
883 ? stationTemplate
.power
* 1000
884 : stationTemplate
.power
;
886 stationInfo
.firmwareVersionPattern
=
887 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
889 Utils
.isNotEmptyString(stationInfo
.firmwareVersion
) &&
890 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
893 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
895 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
898 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
905 stationTemplate
?.firmwareUpgrade
?? {}
907 stationInfo
.resetTime
= !Utils
.isNullOrUndefined(stationTemplate
?.resetTime
)
908 ? stationTemplate
.resetTime
* 1000
909 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
910 const configuredMaxConnectors
=
911 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
912 ChargingStationUtils
.checkConfiguredMaxConnectors(
913 configuredMaxConnectors
,
917 const templateMaxConnectors
=
918 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
919 ChargingStationUtils
.checkTemplateMaxConnectors(
920 templateMaxConnectors
,
925 configuredMaxConnectors
>
926 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
927 !stationTemplate
?.randomConnectors
930 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
932 }, forcing random connector configurations affectation`
934 stationInfo
.randomConnectors
= true;
936 // Build connectors if needed (FIXME: should be factored out)
937 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
938 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
939 ChargingStationUtils
.createStationInfoHash(stationInfo
);
943 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
944 let stationInfo
: ChargingStationInfo
| undefined;
945 this.getStationInfoPersistentConfiguration() &&
946 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
);
947 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
951 private getStationInfo(): ChargingStationInfo
{
952 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
953 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
954 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
955 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
956 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
957 return this.stationInfo
;
959 return stationInfoFromFile
;
961 stationInfoFromFile
&&
962 ChargingStationUtils
.propagateSerialNumber(
963 this.getTemplateFromFile(),
965 stationInfoFromTemplate
967 return stationInfoFromTemplate
;
970 private saveStationInfo(): void {
971 if (this.getStationInfoPersistentConfiguration()) {
972 this.saveConfiguration();
976 private getOcppPersistentConfiguration(): boolean {
977 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
980 private getStationInfoPersistentConfiguration(): boolean {
981 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
984 private handleUnsupportedVersion(version
: OCPPVersion
) {
985 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
986 logger
.error(`${this.logPrefix()} ${errMsg}`);
987 throw new BaseError(errMsg
);
990 private initialize(): void {
991 this.configurationFile
= path
.join(
992 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
993 `${ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile())}.json`
995 this.stationInfo
= this.getStationInfo();
996 this.saveStationInfo();
997 // Avoid duplication of connectors related information in RAM
998 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
999 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1000 if (this.getEnableStatistics() === true) {
1001 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1002 this.stationInfo
.hashId
,
1003 this.stationInfo
.chargingStationId
,
1004 this.configuredSupervisionUrl
1007 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1010 this.powerDivider
= this.getPowerDivider();
1011 // OCPP configuration
1012 this.ocppConfiguration
= this.getOcppConfiguration();
1013 this.initializeOcppConfiguration();
1014 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1015 switch (ocppVersion
) {
1016 case OCPPVersion
.VERSION_16
:
1017 this.ocppIncomingRequestService
=
1018 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1019 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1020 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1023 case OCPPVersion
.VERSION_20
:
1024 case OCPPVersion
.VERSION_201
:
1025 this.ocppIncomingRequestService
=
1026 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1027 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1028 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1032 this.handleUnsupportedVersion(ocppVersion
);
1035 if (this.stationInfo
?.autoRegister
=== true) {
1036 this.bootNotificationResponse
= {
1037 currentTime
: new Date(),
1038 interval
: this.getHeartbeatInterval() / 1000,
1039 status: RegistrationStatusEnumType
.ACCEPTED
,
1043 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1044 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1045 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1047 const patternGroup
: number | undefined =
1048 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1049 this.stationInfo
.firmwareVersion
?.split('.').length
;
1050 const match
= this.stationInfo
?.firmwareVersion
1051 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1052 ?.slice(1, patternGroup
+ 1);
1053 const patchLevelIndex
= match
.length
- 1;
1054 match
[patchLevelIndex
] = (
1055 Utils
.convertToInt(match
[patchLevelIndex
]) +
1056 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1058 this.stationInfo
.firmwareVersion
= match
?.join('.');
1062 private initializeOcppConfiguration(): void {
1064 !ChargingStationConfigurationUtils
.getConfigurationKey(
1066 StandardParametersKey
.HeartbeatInterval
1069 ChargingStationConfigurationUtils
.addConfigurationKey(
1071 StandardParametersKey
.HeartbeatInterval
,
1076 !ChargingStationConfigurationUtils
.getConfigurationKey(
1078 StandardParametersKey
.HeartBeatInterval
1081 ChargingStationConfigurationUtils
.addConfigurationKey(
1083 StandardParametersKey
.HeartBeatInterval
,
1089 this.getSupervisionUrlOcppConfiguration() &&
1090 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1092 ChargingStationConfigurationUtils
.addConfigurationKey(
1094 this.getSupervisionUrlOcppKey(),
1095 this.configuredSupervisionUrl
.href
,
1099 !this.getSupervisionUrlOcppConfiguration() &&
1100 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1102 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1104 this.getSupervisionUrlOcppKey(),
1109 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1110 !ChargingStationConfigurationUtils
.getConfigurationKey(
1112 this.stationInfo
.amperageLimitationOcppKey
1115 ChargingStationConfigurationUtils
.addConfigurationKey(
1117 this.stationInfo
.amperageLimitationOcppKey
,
1119 this.stationInfo
.maximumAmperage
*
1120 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1125 !ChargingStationConfigurationUtils
.getConfigurationKey(
1127 StandardParametersKey
.SupportedFeatureProfiles
1130 ChargingStationConfigurationUtils
.addConfigurationKey(
1132 StandardParametersKey
.SupportedFeatureProfiles
,
1133 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1136 ChargingStationConfigurationUtils
.addConfigurationKey(
1138 StandardParametersKey
.NumberOfConnectors
,
1139 this.getNumberOfConnectors().toString(),
1144 !ChargingStationConfigurationUtils
.getConfigurationKey(
1146 StandardParametersKey
.MeterValuesSampledData
1149 ChargingStationConfigurationUtils
.addConfigurationKey(
1151 StandardParametersKey
.MeterValuesSampledData
,
1152 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1156 !ChargingStationConfigurationUtils
.getConfigurationKey(
1158 StandardParametersKey
.ConnectorPhaseRotation
1161 const connectorPhaseRotation
= [];
1162 for (const connectorId
of this.connectors
.keys()) {
1164 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1165 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1166 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1167 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1169 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1170 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1171 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1172 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1175 ChargingStationConfigurationUtils
.addConfigurationKey(
1177 StandardParametersKey
.ConnectorPhaseRotation
,
1178 connectorPhaseRotation
.toString()
1182 !ChargingStationConfigurationUtils
.getConfigurationKey(
1184 StandardParametersKey
.AuthorizeRemoteTxRequests
1187 ChargingStationConfigurationUtils
.addConfigurationKey(
1189 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1194 !ChargingStationConfigurationUtils
.getConfigurationKey(
1196 StandardParametersKey
.LocalAuthListEnabled
1198 ChargingStationConfigurationUtils
.getConfigurationKey(
1200 StandardParametersKey
.SupportedFeatureProfiles
1201 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1203 ChargingStationConfigurationUtils
.addConfigurationKey(
1205 StandardParametersKey
.LocalAuthListEnabled
,
1210 !ChargingStationConfigurationUtils
.getConfigurationKey(
1212 StandardParametersKey
.ConnectionTimeOut
1215 ChargingStationConfigurationUtils
.addConfigurationKey(
1217 StandardParametersKey
.ConnectionTimeOut
,
1218 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1221 this.saveOcppConfiguration();
1224 private initializeConnectors(
1225 stationInfo
: ChargingStationInfo
,
1226 configuredMaxConnectors
: number,
1227 templateMaxConnectors
: number
1229 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1230 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1231 logger
.error(`${this.logPrefix()} ${logMsg}`);
1232 throw new BaseError(logMsg
);
1234 if (!stationInfo
?.Connectors
[0]) {
1236 `${this.logPrefix()} Charging station information from template ${
1238 } with no connector Id 0 configuration`
1241 if (stationInfo
?.Connectors
) {
1242 const connectorsConfigHash
= crypto
1243 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1244 .update(`${JSON.stringify(stationInfo?.Connectors)}${configuredMaxConnectors.toString()}`)
1246 const connectorsConfigChanged
=
1247 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1248 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1249 connectorsConfigChanged
&& this.connectors
.clear();
1250 this.connectorsConfigurationHash
= connectorsConfigHash
;
1251 // Add connector Id 0
1252 let lastConnector
= '0';
1253 for (lastConnector
in stationInfo
?.Connectors
) {
1254 const connectorStatus
= stationInfo
?.Connectors
[lastConnector
];
1255 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1257 lastConnectorId
=== 0 &&
1258 this.getUseConnectorId0(stationInfo
) === true &&
1261 this.checkStationInfoConnectorStatus(lastConnectorId
, connectorStatus
);
1262 this.connectors
.set(
1264 Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
)
1266 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1267 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1268 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1272 // Generate all connectors
1273 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1274 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1275 const randConnectorId
= stationInfo
?.randomConnectors
1276 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1278 const connectorStatus
= stationInfo
?.Connectors
[randConnectorId
.toString()];
1279 this.checkStationInfoConnectorStatus(randConnectorId
, connectorStatus
);
1280 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1281 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1282 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1283 this.getConnectorStatus(index
).chargingProfiles
= [];
1290 `${this.logPrefix()} Charging station information from template ${
1292 } with no connectors configuration defined, using already defined connectors`
1295 // Initialize transaction attributes on connectors
1296 for (const connectorId
of this.connectors
.keys()) {
1297 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1299 `${this.logPrefix()} Connector ${connectorId} at initialization has a transaction started: ${
1300 this.getConnectorStatus(connectorId)?.transactionId
1306 (this.getConnectorStatus(connectorId
)?.transactionStarted
=== undefined ||
1307 this.getConnectorStatus(connectorId
)?.transactionStarted
=== null)
1309 this.initializeConnectorStatus(connectorId
);
1314 private checkStationInfoConnectorStatus(
1315 connectorId
: number,
1316 connectorStatus
: ConnectorStatus
1318 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
1320 `${this.logPrefix()} Charging station information from template ${
1322 } with connector ${connectorId} status configuration defined, undefine it`
1324 connectorStatus
.status = undefined;
1328 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1329 let configuration
: ChargingStationConfiguration
| undefined;
1330 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1332 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1333 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1334 this.configurationFileHash
1337 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1338 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1339 configuration
= JSON
.parse(
1340 fs
.readFileSync(this.configurationFile
, 'utf8')
1341 ) as ChargingStationConfiguration
;
1342 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1343 this.configurationFileHash
= configuration
.configurationHash
;
1344 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1347 FileUtils
.handleFileException(
1348 this.configurationFile
,
1349 FileType
.ChargingStationConfiguration
,
1350 error
as NodeJS
.ErrnoException
,
1355 return configuration
;
1358 private saveConfiguration(): void {
1359 if (this.configurationFile
) {
1361 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1362 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1364 const configurationData
: ChargingStationConfiguration
=
1365 this.getConfigurationFromFile() ?? {};
1366 this.ocppConfiguration
?.configurationKey
&&
1367 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1368 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1369 delete configurationData
.configurationHash
;
1370 const configurationHash
= crypto
1371 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1372 .update(JSON
.stringify(configurationData
))
1374 if (this.configurationFileHash
!== configurationHash
) {
1375 configurationData
.configurationHash
= configurationHash
;
1376 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1377 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1378 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1379 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1380 fs
.closeSync(fileDescriptor
);
1381 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1382 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1383 this.configurationFileHash
= configurationHash
;
1384 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1387 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1388 this.configurationFile
1393 FileUtils
.handleFileException(
1394 this.configurationFile
,
1395 FileType
.ChargingStationConfiguration
,
1396 error
as NodeJS
.ErrnoException
,
1402 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1407 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1408 return this.getTemplateFromFile()?.Configuration
;
1411 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1412 let configuration
: ChargingStationConfiguration
| undefined;
1413 if (this.getOcppPersistentConfiguration() === true) {
1414 const configurationFromFile
= this.getConfigurationFromFile();
1415 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1417 configuration
&& delete configuration
.stationInfo
;
1418 return configuration
;
1421 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1422 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1423 this.getOcppConfigurationFromFile();
1424 if (!ocppConfiguration
) {
1425 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1427 return ocppConfiguration
;
1430 private async onOpen(): Promise
<void> {
1431 if (this.isWebSocketConnectionOpened() === true) {
1433 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1435 if (this.isRegistered() === false) {
1436 // Send BootNotification
1437 let registrationRetryCount
= 0;
1439 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1440 BootNotificationRequest
,
1441 BootNotificationResponse
1442 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1443 skipBufferingOnError
: true,
1445 if (this.isRegistered() === false) {
1446 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1448 this?.bootNotificationResponse
?.interval
1449 ? this.bootNotificationResponse
.interval
* 1000
1450 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1454 this.isRegistered() === false &&
1455 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1456 this.getRegistrationMaxRetries() === -1)
1459 if (this.isRegistered() === true) {
1460 if (this.isInAcceptedState() === true) {
1461 await this.startMessageSequence();
1465 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1468 this.wsConnectionRestarted
= false;
1469 this.autoReconnectRetryCount
= 0;
1470 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1473 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1478 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1481 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1482 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1484 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1486 )}' and reason '${reason.toString()}'`
1488 this.autoReconnectRetryCount
= 0;
1493 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1495 )}' and reason '${reason.toString()}'`
1497 this.started
=== true && (await this.reconnect());
1500 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1503 private async onMessage(data
: RawData
): Promise
<void> {
1504 let messageType
: number;
1505 let messageId
: string;
1506 let commandName
: IncomingRequestCommand
;
1507 let commandPayload
: JsonType
;
1508 let errorType
: ErrorType
;
1509 let errorMessage
: string;
1510 let errorDetails
: JsonType
;
1511 let responseCallback
: ResponseCallback
;
1512 let errorCallback
: ErrorCallback
;
1513 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1514 let requestPayload
: JsonType
;
1515 let cachedRequest
: CachedRequest
;
1518 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1519 if (Array.isArray(request
) === true) {
1520 [messageType
, messageId
] = request
;
1521 // Check the type of message
1522 switch (messageType
) {
1524 case MessageType
.CALL_MESSAGE
:
1525 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1526 if (this.getEnableStatistics() === true) {
1527 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1530 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1534 // Process the message
1535 await this.ocppIncomingRequestService
.incomingRequestHandler(
1543 case MessageType
.CALL_RESULT_MESSAGE
:
1544 [, , commandPayload
] = request
as Response
;
1545 if (this.requests
.has(messageId
) === false) {
1547 throw new OCPPError(
1548 ErrorType
.INTERNAL_ERROR
,
1549 `Response for unknown message id ${messageId}`,
1555 cachedRequest
= this.requests
.get(messageId
);
1556 if (Array.isArray(cachedRequest
) === true) {
1557 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1559 throw new OCPPError(
1560 ErrorType
.PROTOCOL_ERROR
,
1561 `Cached request for message id ${messageId} response is not an array`,
1563 cachedRequest
as unknown
as JsonType
1567 `${this.logPrefix()} << Command '${
1568 requestCommandName ?? Constants.UNKNOWN_COMMAND
1569 }' received response payload: ${JSON.stringify(request)}`
1571 responseCallback(commandPayload
, requestPayload
);
1574 case MessageType
.CALL_ERROR_MESSAGE
:
1575 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1576 if (this.requests
.has(messageId
) === false) {
1578 throw new OCPPError(
1579 ErrorType
.INTERNAL_ERROR
,
1580 `Error response for unknown message id ${messageId}`,
1582 { errorType
, errorMessage
, errorDetails
}
1585 cachedRequest
= this.requests
.get(messageId
);
1586 if (Array.isArray(cachedRequest
) === true) {
1587 [, errorCallback
, requestCommandName
] = cachedRequest
;
1589 throw new OCPPError(
1590 ErrorType
.PROTOCOL_ERROR
,
1591 `Cached request for message id ${messageId} error response is not an array`,
1593 cachedRequest
as unknown
as JsonType
1597 `${this.logPrefix()} << Command '${
1598 requestCommandName ?? Constants.UNKNOWN_COMMAND
1599 }' received error response payload: ${JSON.stringify(request)}`
1601 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1605 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1606 errMsg
= `Wrong message type ${messageType}`;
1607 logger
.error(`${this.logPrefix()} ${errMsg}`);
1608 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1610 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1612 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1619 `${this.logPrefix()} Incoming OCPP command '${
1620 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1621 }' message '${data.toString()}'${
1622 messageType !== MessageType.CALL_MESSAGE
1623 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1625 } processing error:`,
1628 if (error
instanceof OCPPError
=== false) {
1630 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1631 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1632 }' message '${data.toString()}' handling is not an OCPPError:`,
1636 switch (messageType
) {
1637 case MessageType
.CALL_MESSAGE
:
1639 await this.ocppRequestService
.sendError(
1643 commandName
?? requestCommandName
?? null
1646 case MessageType
.CALL_RESULT_MESSAGE
:
1647 case MessageType
.CALL_ERROR_MESSAGE
:
1648 if (errorCallback
) {
1649 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1650 errorCallback(error
as OCPPError
, false);
1652 // Remove the request from the cache in case of error at response handling
1653 this.requests
.delete(messageId
);
1660 private onPing(): void {
1661 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1664 private onPong(): void {
1665 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1668 private onError(error
: WSError
): void {
1669 this.closeWSConnection();
1670 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1673 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1674 if (this.getMeteringPerTransaction() === true) {
1677 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1678 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1683 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1684 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1688 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1689 const localStationInfo
= stationInfo
?? this.stationInfo
;
1690 return localStationInfo
?.useConnectorId0
?? true;
1693 private getNumberOfRunningTransactions(): number {
1695 for (const connectorId
of this.connectors
.keys()) {
1696 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1703 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1704 for (const connectorId
of this.connectors
.keys()) {
1705 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1706 await this.stopTransactionOnConnector(connectorId
, reason
);
1712 private getConnectionTimeout(): number {
1714 ChargingStationConfigurationUtils
.getConfigurationKey(
1716 StandardParametersKey
.ConnectionTimeOut
1721 ChargingStationConfigurationUtils
.getConfigurationKey(
1723 StandardParametersKey
.ConnectionTimeOut
1725 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1728 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1731 // -1 for unlimited, 0 for disabling
1732 private getAutoReconnectMaxRetries(): number | undefined {
1733 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1734 return this.stationInfo
.autoReconnectMaxRetries
;
1736 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1737 return Configuration
.getAutoReconnectMaxRetries();
1743 private getRegistrationMaxRetries(): number | undefined {
1744 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1745 return this.stationInfo
.registrationMaxRetries
;
1750 private getPowerDivider(): number {
1751 let powerDivider
= this.getNumberOfConnectors();
1752 if (this.stationInfo
?.powerSharedByConnectors
) {
1753 powerDivider
= this.getNumberOfRunningTransactions();
1755 return powerDivider
;
1758 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1759 const maximumPower
= this.getMaximumPower(stationInfo
);
1760 switch (this.getCurrentOutType(stationInfo
)) {
1761 case CurrentType
.AC
:
1762 return ACElectricUtils
.amperagePerPhaseFromPower(
1763 this.getNumberOfPhases(stationInfo
),
1764 maximumPower
/ this.getNumberOfConnectors(),
1765 this.getVoltageOut(stationInfo
)
1767 case CurrentType
.DC
:
1768 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1772 private getAmperageLimitation(): number | undefined {
1774 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1775 ChargingStationConfigurationUtils
.getConfigurationKey(
1777 this.stationInfo
.amperageLimitationOcppKey
1782 ChargingStationConfigurationUtils
.getConfigurationKey(
1784 this.stationInfo
.amperageLimitationOcppKey
1786 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1791 private async startMessageSequence(): Promise
<void> {
1792 if (this.stationInfo
?.autoRegister
=== true) {
1793 await this.ocppRequestService
.requestHandler
<
1794 BootNotificationRequest
,
1795 BootNotificationResponse
1796 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1797 skipBufferingOnError
: true,
1800 // Start WebSocket ping
1801 this.startWebSocketPing();
1803 this.startHeartbeat();
1804 // Initialize connectors status
1805 for (const connectorId
of this.connectors
.keys()) {
1806 let connectorStatus
: ConnectorStatusEnum
| undefined;
1807 if (connectorId
=== 0) {
1810 !this.getConnectorStatus(connectorId
)?.status &&
1811 (this.isChargingStationAvailable() === false ||
1812 this.isConnectorAvailable(connectorId
) === false)
1814 connectorStatus
= ConnectorStatusEnum
.UNAVAILABLE
;
1816 !this.getConnectorStatus(connectorId
)?.status &&
1817 this.getConnectorStatus(connectorId
)?.bootStatus
1819 // Set boot status in template at startup
1820 connectorStatus
= this.getConnectorStatus(connectorId
)?.bootStatus
;
1821 } else if (this.getConnectorStatus(connectorId
)?.status) {
1822 // Set previous status at startup
1823 connectorStatus
= this.getConnectorStatus(connectorId
)?.status;
1825 // Set default status
1826 connectorStatus
= ConnectorStatusEnum
.AVAILABLE
;
1828 await this.ocppRequestService
.requestHandler
<
1829 StatusNotificationRequest
,
1830 StatusNotificationResponse
1833 RequestCommand
.STATUS_NOTIFICATION
,
1834 OCPPServiceUtils
.buildStatusNotificationRequest(this, connectorId
, connectorStatus
)
1836 this.getConnectorStatus(connectorId
).status = connectorStatus
;
1838 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
1839 await this.ocppRequestService
.requestHandler
<
1840 FirmwareStatusNotificationRequest
,
1841 FirmwareStatusNotificationResponse
1842 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1843 status: FirmwareStatus
.Installed
,
1845 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
1849 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1850 this.startAutomaticTransactionGenerator();
1852 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1855 private async stopMessageSequence(
1856 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1858 // Stop WebSocket ping
1859 this.stopWebSocketPing();
1861 this.stopHeartbeat();
1862 // Stop ongoing transactions
1863 if (this.automaticTransactionGenerator
?.started
=== true) {
1864 this.stopAutomaticTransactionGenerator();
1866 await this.stopRunningTransactions(reason
);
1868 for (const connectorId
of this.connectors
.keys()) {
1869 if (connectorId
> 0) {
1870 await this.ocppRequestService
.requestHandler
<
1871 StatusNotificationRequest
,
1872 StatusNotificationResponse
1875 RequestCommand
.STATUS_NOTIFICATION
,
1876 OCPPServiceUtils
.buildStatusNotificationRequest(
1879 ConnectorStatusEnum
.UNAVAILABLE
1882 this.getConnectorStatus(connectorId
).status = undefined;
1887 private startWebSocketPing(): void {
1888 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1890 StandardParametersKey
.WebSocketPingInterval
1892 ? Utils
.convertToInt(
1893 ChargingStationConfigurationUtils
.getConfigurationKey(
1895 StandardParametersKey
.WebSocketPingInterval
1899 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1900 this.webSocketPingSetInterval
= setInterval(() => {
1901 if (this.isWebSocketConnectionOpened() === true) {
1902 this.wsConnection
?.ping();
1904 }, webSocketPingInterval
* 1000);
1906 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
1907 webSocketPingInterval
1910 } else if (this.webSocketPingSetInterval
) {
1912 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
1913 webSocketPingInterval
1918 `${this.logPrefix()} WebSocket ping interval set to ${
1919 webSocketPingInterval
1920 ? Utils.formatDurationSeconds(webSocketPingInterval)
1921 : webSocketPingInterval
1922 }, not starting the WebSocket ping`
1927 private stopWebSocketPing(): void {
1928 if (this.webSocketPingSetInterval
) {
1929 clearInterval(this.webSocketPingSetInterval
);
1933 private getConfiguredSupervisionUrl(): URL
{
1934 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
1935 if (Utils
.isNotEmptyArray(supervisionUrls
)) {
1936 switch (Configuration
.getSupervisionUrlDistribution()) {
1937 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1939 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1941 case SupervisionUrlDistribution
.RANDOM
:
1942 this.configuredSupervisionUrlIndex
= Math.floor(
1943 Utils
.secureRandom() * supervisionUrls
.length
1946 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1947 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1951 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1952 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1955 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1958 return new URL(supervisionUrls
[this.configuredSupervisionUrlIndex
]);
1960 return new URL(supervisionUrls
as string);
1963 private getHeartbeatInterval(): number {
1964 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1966 StandardParametersKey
.HeartbeatInterval
1968 if (HeartbeatInterval
) {
1969 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1971 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1973 StandardParametersKey
.HeartBeatInterval
1975 if (HeartBeatInterval
) {
1976 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1978 this.stationInfo
?.autoRegister
=== false &&
1980 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1981 Constants.DEFAULT_HEARTBEAT_INTERVAL
1984 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1987 private stopHeartbeat(): void {
1988 if (this.heartbeatSetInterval
) {
1989 clearInterval(this.heartbeatSetInterval
);
1993 private terminateWSConnection(): void {
1994 if (this.isWebSocketConnectionOpened() === true) {
1995 this.wsConnection
?.terminate();
1996 this.wsConnection
= null;
2000 private stopMeterValues(connectorId
: number) {
2001 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2002 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
2006 private getReconnectExponentialDelay(): boolean {
2007 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2010 private async reconnect(): Promise
<void> {
2011 // Stop WebSocket ping
2012 this.stopWebSocketPing();
2014 this.stopHeartbeat();
2015 // Stop the ATG if needed
2016 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2017 this.stopAutomaticTransactionGenerator();
2020 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2021 this.getAutoReconnectMaxRetries() === -1
2023 this.autoReconnectRetryCount
++;
2024 const reconnectDelay
= this.getReconnectExponentialDelay()
2025 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2026 : this.getConnectionTimeout() * 1000;
2027 const reconnectDelayWithdraw
= 1000;
2028 const reconnectTimeout
=
2029 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2030 ? reconnectDelay
- reconnectDelayWithdraw
2033 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2036 )}ms, timeout ${reconnectTimeout}ms`
2038 await Utils
.sleep(reconnectDelay
);
2040 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2042 this.openWSConnection(
2043 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2044 { closeOpened
: true }
2046 this.wsConnectionRestarted
= true;
2047 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2049 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2050 this.autoReconnectRetryCount
2051 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
2056 private getAutomaticTransactionGeneratorConfigurationFromTemplate():
2057 | AutomaticTransactionGeneratorConfiguration
2059 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
2062 private initializeConnectorStatus(connectorId
: number): void {
2063 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2064 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2065 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2066 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2067 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2068 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;