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
'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';
39 import { PerformanceStatistics
} from
'../performance/PerformanceStatistics';
41 type AutomaticTransactionGeneratorConfiguration
,
43 type BootNotificationRequest
,
44 type BootNotificationResponse
,
46 type ChargingStationConfiguration
,
47 type ChargingStationInfo
,
48 type ChargingStationOcppConfiguration
,
49 type ChargingStationTemplate
,
50 ConnectorPhaseRotation
,
59 type FirmwareStatusNotificationRequest
,
60 type FirmwareStatusNotificationResponse
,
62 type HeartbeatRequest
,
63 type HeartbeatResponse
,
65 type IncomingRequestCommand
,
70 type MeterValuesRequest
,
71 type MeterValuesResponse
,
75 RegistrationStatusEnumType
,
78 type ResponseCallback
,
79 StandardParametersKey
,
80 type StatusNotificationRequest
,
81 type StatusNotificationResponse
,
82 StopTransactionReason
,
83 type StopTransactionRequest
,
84 type StopTransactionResponse
,
85 SupervisionUrlDistribution
,
86 SupportedFeatureProfiles
,
87 VendorDefaultParametersKey
,
89 WebSocketCloseEventStatusCode
,
102 export class ChargingStation
{
103 public readonly index
: number;
104 public readonly templateFile
: string;
105 public stationInfo
!: ChargingStationInfo
;
106 public started
: boolean;
107 public starting
: boolean;
108 public authorizedTagsCache
: AuthorizedTagsCache
;
109 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
110 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
111 public wsConnection
!: WebSocket
| null;
112 public readonly connectors
: Map
<number, ConnectorStatus
>;
113 public readonly requests
: Map
<string, CachedRequest
>;
114 public performanceStatistics
!: PerformanceStatistics
| undefined;
115 public heartbeatSetInterval
!: NodeJS
.Timeout
;
116 public ocppRequestService
!: OCPPRequestService
;
117 public bootNotificationRequest
!: BootNotificationRequest
;
118 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
119 public powerDivider
!: number;
120 private stopping
: boolean;
121 private configurationFile
!: string;
122 private configurationFileHash
!: string;
123 private connectorsConfigurationHash
!: string;
124 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
125 private readonly messageBuffer
: Set
<string>;
126 private configuredSupervisionUrl
!: URL
;
127 private configuredSupervisionUrlIndex
!: number;
128 private wsConnectionRestarted
: boolean;
129 private autoReconnectRetryCount
: number;
130 private templateFileWatcher
!: fs
.FSWatcher
| undefined;
131 private readonly sharedLRUCache
: SharedLRUCache
;
132 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
133 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
135 constructor(index
: number, templateFile
: string) {
136 this.started
= false;
137 this.starting
= false;
138 this.stopping
= false;
139 this.wsConnectionRestarted
= false;
140 this.autoReconnectRetryCount
= 0;
142 this.templateFile
= templateFile
;
143 this.connectors
= new Map
<number, ConnectorStatus
>();
144 this.requests
= new Map
<string, CachedRequest
>();
145 this.messageBuffer
= new Set
<string>();
146 this.sharedLRUCache
= SharedLRUCache
.getInstance();
147 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
148 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
153 private get
wsConnectionUrl(): URL
{
156 this.getSupervisionUrlOcppConfiguration()
157 ? ChargingStationConfigurationUtils.getConfigurationKey(
159 this.getSupervisionUrlOcppKey()
161 : this.configuredSupervisionUrl.href
162 }/${this.stationInfo.chargingStationId}`
166 public logPrefix
= (): string => {
167 return Utils
.logPrefix(
169 (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId) &&
170 this?.stationInfo?.chargingStationId) ??
171 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile()) ??
177 public hasAuthorizedTags(): boolean {
178 return Utils
.isNotEmptyArray(
179 this.authorizedTagsCache
.getAuthorizedTags(
180 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
185 public getEnableStatistics(): boolean {
186 return this.stationInfo
.enableStatistics
?? false;
189 public getMustAuthorizeAtRemoteStart(): boolean {
190 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
193 public getPayloadSchemaValidation(): boolean {
194 return this.stationInfo
.payloadSchemaValidation
?? true;
197 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
198 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
199 switch (this.getCurrentOutType(stationInfo
)) {
201 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
202 ? localStationInfo
.numberOfPhases
209 public isWebSocketConnectionOpened(): boolean {
210 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
213 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
214 return this?.bootNotificationResponse
?.status;
217 public isInUnknownState(): boolean {
218 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
221 public isInPendingState(): boolean {
222 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
225 public isInAcceptedState(): boolean {
226 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
229 public isInRejectedState(): boolean {
230 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
233 public isRegistered(): boolean {
235 this.isInUnknownState() === false &&
236 (this.isInAcceptedState() === true || this.isInPendingState() === true)
240 public isChargingStationAvailable(): boolean {
241 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.OPERATIVE
;
244 public isConnectorAvailable(id
: number): boolean {
245 return id
> 0 && this.getConnectorStatus(id
)?.availability
=== AvailabilityType
.OPERATIVE
;
248 public getNumberOfConnectors(): number {
249 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
252 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
253 return this.connectors
.get(id
);
256 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
257 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
260 public getOcppStrictCompliance(): boolean {
261 return this.stationInfo
?.ocppStrictCompliance
?? false;
264 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
265 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
266 this.getCurrentOutType(stationInfo
),
270 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
271 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
272 ? localStationInfo
.voltageOut
276 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
277 const localStationInfo
= stationInfo
?? this.stationInfo
;
278 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
281 public getConnectorMaximumAvailablePower(connectorId
: number): number {
282 let connectorAmperageLimitationPowerLimit
: number;
284 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
285 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
287 connectorAmperageLimitationPowerLimit
=
288 (this.getCurrentOutType() === CurrentType
.AC
289 ? ACElectricUtils
.powerTotal(
290 this.getNumberOfPhases(),
291 this.getVoltageOut(),
292 this.getAmperageLimitation() * this.getNumberOfConnectors()
294 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
297 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
298 const connectorChargingProfilesPowerLimit
=
299 ChargingStationUtils
.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
301 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
302 isNaN(connectorAmperageLimitationPowerLimit
)
304 : connectorAmperageLimitationPowerLimit
,
305 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
309 public getTransactionIdTag(transactionId
: number): string | undefined {
310 for (const connectorId
of this.connectors
.keys()) {
313 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
315 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
320 public getOutOfOrderEndMeterValues(): boolean {
321 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
324 public getBeginEndMeterValues(): boolean {
325 return this.stationInfo
?.beginEndMeterValues
?? false;
328 public getMeteringPerTransaction(): boolean {
329 return this.stationInfo
?.meteringPerTransaction
?? true;
332 public getTransactionDataMeterValues(): boolean {
333 return this.stationInfo
?.transactionDataMeterValues
?? false;
336 public getMainVoltageMeterValues(): boolean {
337 return this.stationInfo
?.mainVoltageMeterValues
?? true;
340 public getPhaseLineToLineVoltageMeterValues(): boolean {
341 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
344 public getCustomValueLimitationMeterValues(): boolean {
345 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
348 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
349 for (const connectorId
of this.connectors
.keys()) {
352 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
359 public getEnergyActiveImportRegisterByTransactionId(
360 transactionId
: number,
363 return this.getEnergyActiveImportRegister(
364 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
369 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
370 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
373 public getAuthorizeRemoteTxRequests(): boolean {
374 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
376 StandardParametersKey
.AuthorizeRemoteTxRequests
378 return authorizeRemoteTxRequests
379 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
383 public getLocalAuthListEnabled(): boolean {
384 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
386 StandardParametersKey
.LocalAuthListEnabled
388 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
391 public startHeartbeat(): void {
393 this.getHeartbeatInterval() &&
394 this.getHeartbeatInterval() > 0 &&
395 !this.heartbeatSetInterval
397 this.heartbeatSetInterval
= setInterval(() => {
398 this.ocppRequestService
399 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
402 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
406 }, this.getHeartbeatInterval());
408 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
409 this.getHeartbeatInterval()
412 } else if (this.heartbeatSetInterval
) {
414 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
415 this.getHeartbeatInterval()
420 `${this.logPrefix()} Heartbeat interval set to ${
421 this.getHeartbeatInterval()
422 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
423 : this.getHeartbeatInterval()
424 }, not starting the heartbeat`
429 public restartHeartbeat(): void {
431 this.stopHeartbeat();
433 this.startHeartbeat();
436 public restartWebSocketPing(): void {
437 // Stop WebSocket ping
438 this.stopWebSocketPing();
439 // Start WebSocket ping
440 this.startWebSocketPing();
443 public startMeterValues(connectorId
: number, interval
: number): void {
444 if (connectorId
=== 0) {
446 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
450 if (!this.getConnectorStatus(connectorId
)) {
452 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
456 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
458 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
462 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
463 Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
466 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
471 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
472 // FIXME: Implement OCPP version agnostic helpers
473 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
476 this.getConnectorStatus(connectorId
).transactionId
,
479 this.ocppRequestService
480 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
482 RequestCommand
.METER_VALUES
,
485 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
486 meterValue
: [meterValue
],
491 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
498 `${this.logPrefix()} Charging station ${
499 StandardParametersKey.MeterValueSampleInterval
500 } configuration set to ${
501 interval ? Utils.formatDurationMilliSeconds(interval) : interval
502 }, not sending MeterValues`
507 public start(): void {
508 if (this.started
=== false) {
509 if (this.starting
=== false) {
510 this.starting
= true;
511 if (this.getEnableStatistics() === true) {
512 this.performanceStatistics
?.start();
514 this.openWSConnection();
515 // Monitor charging station template file
516 this.templateFileWatcher
= FileUtils
.watchJsonFile(
518 FileType
.ChargingStationTemplate
,
521 (event
, filename
): void => {
522 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
525 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
527 } file have changed, reload`
529 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
533 this.stopAutomaticTransactionGenerator();
535 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
537 this.startAutomaticTransactionGenerator();
539 if (this.getEnableStatistics() === true) {
540 this.performanceStatistics
?.restart();
542 this.performanceStatistics
?.stop();
544 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
547 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
555 parentPort
?.postMessage(MessageChannelUtils
.buildStartedMessage(this));
556 this.starting
= false;
558 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
561 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
565 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
566 if (this.started
=== true) {
567 if (this.stopping
=== false) {
568 this.stopping
= true;
569 await this.stopMessageSequence(reason
);
570 this.closeWSConnection();
571 if (this.getEnableStatistics() === true) {
572 this.performanceStatistics
?.stop();
574 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
575 this.templateFileWatcher
?.close();
576 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
577 this.bootNotificationResponse
= undefined;
578 this.started
= false;
579 parentPort
?.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
580 this.stopping
= false;
582 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
585 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
589 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
590 await this.stop(reason
);
591 await Utils
.sleep(this.stationInfo
.resetTime
);
596 public saveOcppConfiguration(): void {
597 if (this.getOcppPersistentConfiguration()) {
598 this.saveConfiguration();
602 public resetConnectorStatus(connectorId
: number): void {
603 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
604 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
605 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
606 this.getConnectorStatus(connectorId
).transactionStarted
= false;
607 delete this.getConnectorStatus(connectorId
)?.localAuthorizeIdTag
;
608 delete this.getConnectorStatus(connectorId
)?.authorizeIdTag
;
609 delete this.getConnectorStatus(connectorId
)?.transactionId
;
610 delete this.getConnectorStatus(connectorId
)?.transactionIdTag
;
611 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
612 delete this.getConnectorStatus(connectorId
)?.transactionBeginMeterValue
;
613 this.stopMeterValues(connectorId
);
614 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
617 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
618 return ChargingStationConfigurationUtils
.getConfigurationKey(
620 StandardParametersKey
.SupportedFeatureProfiles
621 )?.value
?.includes(featureProfile
);
624 public bufferMessage(message
: string): void {
625 this.messageBuffer
.add(message
);
628 public openWSConnection(
629 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
630 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
632 terminateOpened
: false,
635 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
636 params
.closeOpened
= params
?.closeOpened
?? false;
637 params
.terminateOpened
= params
?.terminateOpened
?? false;
638 if (this.started
=== false && this.starting
=== false) {
640 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
645 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
646 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
648 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
650 if (params
?.closeOpened
) {
651 this.closeWSConnection();
653 if (params
?.terminateOpened
) {
654 this.terminateWSConnection();
656 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
657 let protocol
: string;
658 switch (ocppVersion
) {
659 case OCPPVersion
.VERSION_16
:
660 case OCPPVersion
.VERSION_20
:
661 case OCPPVersion
.VERSION_201
:
662 protocol
= `ocpp${ocppVersion}`;
665 this.handleUnsupportedVersion(ocppVersion
);
669 if (this.isWebSocketConnectionOpened() === true) {
671 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
677 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
680 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
682 // Handle WebSocket message
683 this.wsConnection
.on(
685 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
687 // Handle WebSocket error
688 this.wsConnection
.on(
690 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
692 // Handle WebSocket close
693 this.wsConnection
.on(
695 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
697 // Handle WebSocket open
698 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
699 // Handle WebSocket ping
700 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
701 // Handle WebSocket pong
702 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
705 public closeWSConnection(): void {
706 if (this.isWebSocketConnectionOpened() === true) {
707 this.wsConnection
?.close();
708 this.wsConnection
= null;
712 public startAutomaticTransactionGenerator(
713 connectorIds
?: number[],
714 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
716 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
717 automaticTransactionGeneratorConfiguration
??
718 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
721 if (Utils
.isNotEmptyArray(connectorIds
)) {
722 for (const connectorId
of connectorIds
) {
723 this.automaticTransactionGenerator
?.startConnector(connectorId
);
726 this.automaticTransactionGenerator
?.start();
728 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
731 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
732 if (Utils
.isNotEmptyArray(connectorIds
)) {
733 for (const connectorId
of connectorIds
) {
734 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
737 this.automaticTransactionGenerator
?.stop();
739 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
742 public async stopTransactionOnConnector(
744 reason
= StopTransactionReason
.NONE
745 ): Promise
<StopTransactionResponse
> {
746 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
748 this.getBeginEndMeterValues() === true &&
749 this.getOcppStrictCompliance() === true &&
750 this.getOutOfOrderEndMeterValues() === false
752 // FIXME: Implement OCPP version agnostic helpers
753 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
756 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
758 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
760 RequestCommand
.METER_VALUES
,
764 meterValue
: [transactionEndMeterValue
],
768 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
770 RequestCommand
.STOP_TRANSACTION
,
773 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
779 private flushMessageBuffer(): void {
780 if (this.messageBuffer
.size
> 0) {
781 this.messageBuffer
.forEach((message
) => {
783 let commandName
: RequestCommand
;
784 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
785 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
787 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
788 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
790 this.wsConnection
?.send(message
);
791 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
793 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
795 )} payload sent: ${message}`
797 this.messageBuffer
.delete(message
);
802 private getSupervisionUrlOcppConfiguration(): boolean {
803 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
806 private getSupervisionUrlOcppKey(): string {
807 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
810 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
811 let template
: ChargingStationTemplate
;
813 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
814 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
816 const measureId
= `${FileType.ChargingStationTemplate} read`;
817 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
818 template
= JSON
.parse(
819 fs
.readFileSync(this.templateFile
, 'utf8')
820 ) as ChargingStationTemplate
;
821 PerformanceStatistics
.endMeasure(measureId
, beginId
);
822 template
.templateHash
= crypto
823 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
824 .update(JSON
.stringify(template
))
826 this.sharedLRUCache
.setChargingStationTemplate(template
);
829 FileUtils
.handleFileException(
831 FileType
.ChargingStationTemplate
,
832 error
as NodeJS
.ErrnoException
,
839 private getStationInfoFromTemplate(): ChargingStationInfo
{
840 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
841 if (Utils
.isNullOrUndefined(stationTemplate
)) {
842 const errorMsg
= `Failed to read charging station template file ${this.templateFile}`;
843 logger
.error(`${this.logPrefix()} ${errorMsg}`);
844 throw new BaseError(errorMsg
);
846 if (Utils
.isEmptyObject(stationTemplate
)) {
847 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
848 logger
.error(`${this.logPrefix()} ${errorMsg}`);
849 throw new BaseError(errorMsg
);
851 // Deprecation template keys section
852 ChargingStationUtils
.warnDeprecatedTemplateKey(
857 "Use 'supervisionUrls' instead"
859 ChargingStationUtils
.convertDeprecatedTemplateKey(
864 const stationInfo
: ChargingStationInfo
=
865 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
866 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
867 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
871 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
872 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
873 if (Utils
.isNotEmptyArray(stationTemplate
?.power
)) {
874 stationTemplate
.power
= stationTemplate
.power
as number[];
875 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
876 stationInfo
.maximumPower
=
877 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
878 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
879 : stationTemplate
.power
[powerArrayRandomIndex
];
881 stationTemplate
.power
= stationTemplate
?.power
as number;
882 stationInfo
.maximumPower
=
883 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
884 ? stationTemplate
.power
* 1000
885 : stationTemplate
.power
;
887 stationInfo
.firmwareVersionPattern
=
888 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
890 Utils
.isNotEmptyString(stationInfo
.firmwareVersion
) &&
891 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
894 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
896 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
899 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
906 stationTemplate
?.firmwareUpgrade
?? {}
908 stationInfo
.resetTime
= !Utils
.isNullOrUndefined(stationTemplate
?.resetTime
)
909 ? stationTemplate
.resetTime
* 1000
910 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
911 const configuredMaxConnectors
=
912 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
913 ChargingStationUtils
.checkConfiguredMaxConnectors(
914 configuredMaxConnectors
,
918 const templateMaxConnectors
=
919 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
920 ChargingStationUtils
.checkTemplateMaxConnectors(
921 templateMaxConnectors
,
926 configuredMaxConnectors
>
927 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
928 !stationTemplate
?.randomConnectors
931 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
933 }, forcing random connector configurations affectation`
935 stationInfo
.randomConnectors
= true;
937 // Build connectors if needed (FIXME: should be factored out)
938 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
939 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
940 ChargingStationUtils
.createStationInfoHash(stationInfo
);
944 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
945 let stationInfo
: ChargingStationInfo
| undefined;
946 this.getStationInfoPersistentConfiguration() &&
947 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
);
948 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
952 private getStationInfo(): ChargingStationInfo
{
953 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
954 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
955 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
956 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
957 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
958 return this.stationInfo
;
960 return stationInfoFromFile
;
962 stationInfoFromFile
&&
963 ChargingStationUtils
.propagateSerialNumber(
964 this.getTemplateFromFile(),
966 stationInfoFromTemplate
968 return stationInfoFromTemplate
;
971 private saveStationInfo(): void {
972 if (this.getStationInfoPersistentConfiguration()) {
973 this.saveConfiguration();
977 private getOcppPersistentConfiguration(): boolean {
978 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
981 private getStationInfoPersistentConfiguration(): boolean {
982 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
985 private handleUnsupportedVersion(version
: OCPPVersion
) {
986 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
987 logger
.error(`${this.logPrefix()} ${errMsg}`);
988 throw new BaseError(errMsg
);
991 private initialize(): void {
992 this.configurationFile
= path
.join(
993 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
994 `${ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile())}.json`
996 this.stationInfo
= this.getStationInfo();
997 this.saveStationInfo();
998 // Avoid duplication of connectors related information in RAM
999 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
1000 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1001 if (this.getEnableStatistics() === true) {
1002 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1003 this.stationInfo
.hashId
,
1004 this.stationInfo
.chargingStationId
,
1005 this.configuredSupervisionUrl
1008 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1011 this.powerDivider
= this.getPowerDivider();
1012 // OCPP configuration
1013 this.ocppConfiguration
= this.getOcppConfiguration();
1014 this.initializeOcppConfiguration();
1015 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1016 switch (ocppVersion
) {
1017 case OCPPVersion
.VERSION_16
:
1018 this.ocppIncomingRequestService
=
1019 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1020 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1021 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1024 case OCPPVersion
.VERSION_20
:
1025 case OCPPVersion
.VERSION_201
:
1026 this.ocppIncomingRequestService
=
1027 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1028 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1029 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1033 this.handleUnsupportedVersion(ocppVersion
);
1036 if (this.stationInfo
?.autoRegister
=== true) {
1037 this.bootNotificationResponse
= {
1038 currentTime
: new Date(),
1039 interval
: this.getHeartbeatInterval() / 1000,
1040 status: RegistrationStatusEnumType
.ACCEPTED
,
1044 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1045 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1046 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1048 const patternGroup
: number | undefined =
1049 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1050 this.stationInfo
.firmwareVersion
?.split('.').length
;
1051 const match
= this.stationInfo
?.firmwareVersion
1052 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1053 ?.slice(1, patternGroup
+ 1);
1054 const patchLevelIndex
= match
.length
- 1;
1055 match
[patchLevelIndex
] = (
1056 Utils
.convertToInt(match
[patchLevelIndex
]) +
1057 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1059 this.stationInfo
.firmwareVersion
= match
?.join('.');
1063 private initializeOcppConfiguration(): void {
1065 !ChargingStationConfigurationUtils
.getConfigurationKey(
1067 StandardParametersKey
.HeartbeatInterval
1070 ChargingStationConfigurationUtils
.addConfigurationKey(
1072 StandardParametersKey
.HeartbeatInterval
,
1077 !ChargingStationConfigurationUtils
.getConfigurationKey(
1079 StandardParametersKey
.HeartBeatInterval
1082 ChargingStationConfigurationUtils
.addConfigurationKey(
1084 StandardParametersKey
.HeartBeatInterval
,
1090 this.getSupervisionUrlOcppConfiguration() &&
1091 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1093 ChargingStationConfigurationUtils
.addConfigurationKey(
1095 this.getSupervisionUrlOcppKey(),
1096 this.configuredSupervisionUrl
.href
,
1100 !this.getSupervisionUrlOcppConfiguration() &&
1101 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1103 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1105 this.getSupervisionUrlOcppKey(),
1110 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1111 !ChargingStationConfigurationUtils
.getConfigurationKey(
1113 this.stationInfo
.amperageLimitationOcppKey
1116 ChargingStationConfigurationUtils
.addConfigurationKey(
1118 this.stationInfo
.amperageLimitationOcppKey
,
1120 this.stationInfo
.maximumAmperage
*
1121 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1126 !ChargingStationConfigurationUtils
.getConfigurationKey(
1128 StandardParametersKey
.SupportedFeatureProfiles
1131 ChargingStationConfigurationUtils
.addConfigurationKey(
1133 StandardParametersKey
.SupportedFeatureProfiles
,
1134 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1137 ChargingStationConfigurationUtils
.addConfigurationKey(
1139 StandardParametersKey
.NumberOfConnectors
,
1140 this.getNumberOfConnectors().toString(),
1145 !ChargingStationConfigurationUtils
.getConfigurationKey(
1147 StandardParametersKey
.MeterValuesSampledData
1150 ChargingStationConfigurationUtils
.addConfigurationKey(
1152 StandardParametersKey
.MeterValuesSampledData
,
1153 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1157 !ChargingStationConfigurationUtils
.getConfigurationKey(
1159 StandardParametersKey
.ConnectorPhaseRotation
1162 const connectorPhaseRotation
= [];
1163 for (const connectorId
of this.connectors
.keys()) {
1165 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1166 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1167 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1168 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1170 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1171 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1172 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1173 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1176 ChargingStationConfigurationUtils
.addConfigurationKey(
1178 StandardParametersKey
.ConnectorPhaseRotation
,
1179 connectorPhaseRotation
.toString()
1183 !ChargingStationConfigurationUtils
.getConfigurationKey(
1185 StandardParametersKey
.AuthorizeRemoteTxRequests
1188 ChargingStationConfigurationUtils
.addConfigurationKey(
1190 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1195 !ChargingStationConfigurationUtils
.getConfigurationKey(
1197 StandardParametersKey
.LocalAuthListEnabled
1199 ChargingStationConfigurationUtils
.getConfigurationKey(
1201 StandardParametersKey
.SupportedFeatureProfiles
1202 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1204 ChargingStationConfigurationUtils
.addConfigurationKey(
1206 StandardParametersKey
.LocalAuthListEnabled
,
1211 !ChargingStationConfigurationUtils
.getConfigurationKey(
1213 StandardParametersKey
.ConnectionTimeOut
1216 ChargingStationConfigurationUtils
.addConfigurationKey(
1218 StandardParametersKey
.ConnectionTimeOut
,
1219 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1222 this.saveOcppConfiguration();
1225 private initializeConnectors(
1226 stationInfo
: ChargingStationInfo
,
1227 configuredMaxConnectors
: number,
1228 templateMaxConnectors
: number
1230 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1231 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1232 logger
.error(`${this.logPrefix()} ${logMsg}`);
1233 throw new BaseError(logMsg
);
1235 if (!stationInfo
?.Connectors
[0]) {
1237 `${this.logPrefix()} Charging station information from template ${
1239 } with no connector Id 0 configuration`
1242 if (stationInfo
?.Connectors
) {
1243 const connectorsConfigHash
= crypto
1244 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1245 .update(`${JSON.stringify(stationInfo?.Connectors)}${configuredMaxConnectors.toString()}`)
1247 const connectorsConfigChanged
=
1248 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1249 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1250 connectorsConfigChanged
&& this.connectors
.clear();
1251 this.connectorsConfigurationHash
= connectorsConfigHash
;
1252 // Add connector Id 0
1253 let lastConnector
= '0';
1254 for (lastConnector
in stationInfo
?.Connectors
) {
1255 const connectorStatus
= stationInfo
?.Connectors
[lastConnector
];
1256 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1258 lastConnectorId
=== 0 &&
1259 this.getUseConnectorId0(stationInfo
) === true &&
1262 this.checkStationInfoConnectorStatus(lastConnectorId
, connectorStatus
);
1263 this.connectors
.set(
1265 Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
)
1267 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1268 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1269 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1273 // Generate all connectors
1274 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1275 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1276 const randConnectorId
= stationInfo
?.randomConnectors
1277 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1279 const connectorStatus
= stationInfo
?.Connectors
[randConnectorId
.toString()];
1280 this.checkStationInfoConnectorStatus(randConnectorId
, connectorStatus
);
1281 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1282 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1283 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1284 this.getConnectorStatus(index
).chargingProfiles
= [];
1291 `${this.logPrefix()} Charging station information from template ${
1293 } with no connectors configuration defined, using already defined connectors`
1296 // Initialize transaction attributes on connectors
1297 for (const connectorId
of this.connectors
.keys()) {
1298 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1300 `${this.logPrefix()} Connector ${connectorId} at initialization has a transaction started: ${
1301 this.getConnectorStatus(connectorId)?.transactionId
1307 (this.getConnectorStatus(connectorId
)?.transactionStarted
=== undefined ||
1308 this.getConnectorStatus(connectorId
)?.transactionStarted
=== null)
1310 this.initializeConnectorStatus(connectorId
);
1315 private checkStationInfoConnectorStatus(
1316 connectorId
: number,
1317 connectorStatus
: ConnectorStatus
1319 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
1321 `${this.logPrefix()} Charging station information from template ${
1323 } with connector ${connectorId} status configuration defined, undefine it`
1325 connectorStatus
.status = undefined;
1329 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1330 let configuration
: ChargingStationConfiguration
| undefined;
1331 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1333 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1334 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1335 this.configurationFileHash
1338 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1339 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1340 configuration
= JSON
.parse(
1341 fs
.readFileSync(this.configurationFile
, 'utf8')
1342 ) as ChargingStationConfiguration
;
1343 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1344 this.configurationFileHash
= configuration
.configurationHash
;
1345 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1348 FileUtils
.handleFileException(
1349 this.configurationFile
,
1350 FileType
.ChargingStationConfiguration
,
1351 error
as NodeJS
.ErrnoException
,
1356 return configuration
;
1359 private saveConfiguration(): void {
1360 if (this.configurationFile
) {
1362 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1363 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1365 const configurationData
: ChargingStationConfiguration
=
1366 this.getConfigurationFromFile() ?? {};
1367 this.ocppConfiguration
?.configurationKey
&&
1368 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1369 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1370 delete configurationData
.configurationHash
;
1371 const configurationHash
= crypto
1372 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1373 .update(JSON
.stringify(configurationData
))
1375 if (this.configurationFileHash
!== configurationHash
) {
1376 configurationData
.configurationHash
= configurationHash
;
1377 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1378 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1379 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1380 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1381 fs
.closeSync(fileDescriptor
);
1382 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1383 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1384 this.configurationFileHash
= configurationHash
;
1385 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1388 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1389 this.configurationFile
1394 FileUtils
.handleFileException(
1395 this.configurationFile
,
1396 FileType
.ChargingStationConfiguration
,
1397 error
as NodeJS
.ErrnoException
,
1403 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1408 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1409 return this.getTemplateFromFile()?.Configuration
;
1412 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1413 let configuration
: ChargingStationConfiguration
| undefined;
1414 if (this.getOcppPersistentConfiguration() === true) {
1415 const configurationFromFile
= this.getConfigurationFromFile();
1416 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1418 configuration
&& delete configuration
.stationInfo
;
1419 return configuration
;
1422 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1423 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1424 this.getOcppConfigurationFromFile();
1425 if (!ocppConfiguration
) {
1426 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1428 return ocppConfiguration
;
1431 private async onOpen(): Promise
<void> {
1432 if (this.isWebSocketConnectionOpened() === true) {
1434 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1436 if (this.isRegistered() === false) {
1437 // Send BootNotification
1438 let registrationRetryCount
= 0;
1440 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1441 BootNotificationRequest
,
1442 BootNotificationResponse
1443 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1444 skipBufferingOnError
: true,
1446 if (this.isRegistered() === false) {
1447 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1449 this?.bootNotificationResponse
?.interval
1450 ? this.bootNotificationResponse
.interval
* 1000
1451 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1455 this.isRegistered() === false &&
1456 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1457 this.getRegistrationMaxRetries() === -1)
1460 if (this.isRegistered() === true) {
1461 if (this.isInAcceptedState() === true) {
1462 await this.startMessageSequence();
1466 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1469 this.wsConnectionRestarted
= false;
1470 this.autoReconnectRetryCount
= 0;
1471 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1474 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1479 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1482 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1483 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1485 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1487 )}' and reason '${reason.toString()}'`
1489 this.autoReconnectRetryCount
= 0;
1494 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1496 )}' and reason '${reason.toString()}'`
1498 this.started
=== true && (await this.reconnect());
1501 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1504 private async onMessage(data
: RawData
): Promise
<void> {
1505 let messageType
: number;
1506 let messageId
: string;
1507 let commandName
: IncomingRequestCommand
;
1508 let commandPayload
: JsonType
;
1509 let errorType
: ErrorType
;
1510 let errorMessage
: string;
1511 let errorDetails
: JsonType
;
1512 let responseCallback
: ResponseCallback
;
1513 let errorCallback
: ErrorCallback
;
1514 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1515 let requestPayload
: JsonType
;
1516 let cachedRequest
: CachedRequest
;
1519 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1520 if (Array.isArray(request
) === true) {
1521 [messageType
, messageId
] = request
;
1522 // Check the type of message
1523 switch (messageType
) {
1525 case MessageType
.CALL_MESSAGE
:
1526 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1527 if (this.getEnableStatistics() === true) {
1528 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1531 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1535 // Process the message
1536 await this.ocppIncomingRequestService
.incomingRequestHandler(
1544 case MessageType
.CALL_RESULT_MESSAGE
:
1545 [, , commandPayload
] = request
as Response
;
1546 if (this.requests
.has(messageId
) === false) {
1548 throw new OCPPError(
1549 ErrorType
.INTERNAL_ERROR
,
1550 `Response for unknown message id ${messageId}`,
1556 cachedRequest
= this.requests
.get(messageId
);
1557 if (Array.isArray(cachedRequest
) === true) {
1558 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1560 throw new OCPPError(
1561 ErrorType
.PROTOCOL_ERROR
,
1562 `Cached request for message id ${messageId} response is not an array`,
1564 cachedRequest
as unknown
as JsonType
1568 `${this.logPrefix()} << Command '${
1569 requestCommandName ?? Constants.UNKNOWN_COMMAND
1570 }' received response payload: ${JSON.stringify(request)}`
1572 responseCallback(commandPayload
, requestPayload
);
1575 case MessageType
.CALL_ERROR_MESSAGE
:
1576 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1577 if (this.requests
.has(messageId
) === false) {
1579 throw new OCPPError(
1580 ErrorType
.INTERNAL_ERROR
,
1581 `Error response for unknown message id ${messageId}`,
1583 { errorType
, errorMessage
, errorDetails
}
1586 cachedRequest
= this.requests
.get(messageId
);
1587 if (Array.isArray(cachedRequest
) === true) {
1588 [, errorCallback
, requestCommandName
] = cachedRequest
;
1590 throw new OCPPError(
1591 ErrorType
.PROTOCOL_ERROR
,
1592 `Cached request for message id ${messageId} error response is not an array`,
1594 cachedRequest
as unknown
as JsonType
1598 `${this.logPrefix()} << Command '${
1599 requestCommandName ?? Constants.UNKNOWN_COMMAND
1600 }' received error response payload: ${JSON.stringify(request)}`
1602 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1606 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1607 errMsg
= `Wrong message type ${messageType}`;
1608 logger
.error(`${this.logPrefix()} ${errMsg}`);
1609 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1611 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1613 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1620 `${this.logPrefix()} Incoming OCPP command '${
1621 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1622 }' message '${data.toString()}'${
1623 messageType !== MessageType.CALL_MESSAGE
1624 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1626 } processing error:`,
1629 if (error
instanceof OCPPError
=== false) {
1631 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1632 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1633 }' message '${data.toString()}' handling is not an OCPPError:`,
1637 switch (messageType
) {
1638 case MessageType
.CALL_MESSAGE
:
1640 await this.ocppRequestService
.sendError(
1644 commandName
?? requestCommandName
?? null
1647 case MessageType
.CALL_RESULT_MESSAGE
:
1648 case MessageType
.CALL_ERROR_MESSAGE
:
1649 if (errorCallback
) {
1650 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1651 errorCallback(error
as OCPPError
, false);
1653 // Remove the request from the cache in case of error at response handling
1654 this.requests
.delete(messageId
);
1661 private onPing(): void {
1662 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1665 private onPong(): void {
1666 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1669 private onError(error
: WSError
): void {
1670 this.closeWSConnection();
1671 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1674 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1675 if (this.getMeteringPerTransaction() === true) {
1678 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1679 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1684 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1685 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1689 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1690 const localStationInfo
= stationInfo
?? this.stationInfo
;
1691 return localStationInfo
?.useConnectorId0
?? true;
1694 private getNumberOfRunningTransactions(): number {
1696 for (const connectorId
of this.connectors
.keys()) {
1697 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1704 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1705 for (const connectorId
of this.connectors
.keys()) {
1706 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1707 await this.stopTransactionOnConnector(connectorId
, reason
);
1713 private getConnectionTimeout(): number {
1715 ChargingStationConfigurationUtils
.getConfigurationKey(
1717 StandardParametersKey
.ConnectionTimeOut
1722 ChargingStationConfigurationUtils
.getConfigurationKey(
1724 StandardParametersKey
.ConnectionTimeOut
1726 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1729 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1732 // -1 for unlimited, 0 for disabling
1733 private getAutoReconnectMaxRetries(): number | undefined {
1734 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1735 return this.stationInfo
.autoReconnectMaxRetries
;
1737 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1738 return Configuration
.getAutoReconnectMaxRetries();
1744 private getRegistrationMaxRetries(): number | undefined {
1745 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1746 return this.stationInfo
.registrationMaxRetries
;
1751 private getPowerDivider(): number {
1752 let powerDivider
= this.getNumberOfConnectors();
1753 if (this.stationInfo
?.powerSharedByConnectors
) {
1754 powerDivider
= this.getNumberOfRunningTransactions();
1756 return powerDivider
;
1759 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1760 const maximumPower
= this.getMaximumPower(stationInfo
);
1761 switch (this.getCurrentOutType(stationInfo
)) {
1762 case CurrentType
.AC
:
1763 return ACElectricUtils
.amperagePerPhaseFromPower(
1764 this.getNumberOfPhases(stationInfo
),
1765 maximumPower
/ this.getNumberOfConnectors(),
1766 this.getVoltageOut(stationInfo
)
1768 case CurrentType
.DC
:
1769 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1773 private getAmperageLimitation(): number | undefined {
1775 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1776 ChargingStationConfigurationUtils
.getConfigurationKey(
1778 this.stationInfo
.amperageLimitationOcppKey
1783 ChargingStationConfigurationUtils
.getConfigurationKey(
1785 this.stationInfo
.amperageLimitationOcppKey
1787 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1792 private async startMessageSequence(): Promise
<void> {
1793 if (this.stationInfo
?.autoRegister
=== true) {
1794 await this.ocppRequestService
.requestHandler
<
1795 BootNotificationRequest
,
1796 BootNotificationResponse
1797 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1798 skipBufferingOnError
: true,
1801 // Start WebSocket ping
1802 this.startWebSocketPing();
1804 this.startHeartbeat();
1805 // Initialize connectors status
1806 for (const connectorId
of this.connectors
.keys()) {
1807 let connectorStatus
: ConnectorStatusEnum
| undefined;
1808 if (connectorId
=== 0) {
1811 !this.getConnectorStatus(connectorId
)?.status &&
1812 (this.isChargingStationAvailable() === false ||
1813 this.isConnectorAvailable(connectorId
) === false)
1815 connectorStatus
= ConnectorStatusEnum
.UNAVAILABLE
;
1817 !this.getConnectorStatus(connectorId
)?.status &&
1818 this.getConnectorStatus(connectorId
)?.bootStatus
1820 // Set boot status in template at startup
1821 connectorStatus
= this.getConnectorStatus(connectorId
)?.bootStatus
;
1822 } else if (this.getConnectorStatus(connectorId
)?.status) {
1823 // Set previous status at startup
1824 connectorStatus
= this.getConnectorStatus(connectorId
)?.status;
1826 // Set default status
1827 connectorStatus
= ConnectorStatusEnum
.AVAILABLE
;
1829 await this.ocppRequestService
.requestHandler
<
1830 StatusNotificationRequest
,
1831 StatusNotificationResponse
1834 RequestCommand
.STATUS_NOTIFICATION
,
1835 OCPPServiceUtils
.buildStatusNotificationRequest(this, connectorId
, connectorStatus
)
1837 this.getConnectorStatus(connectorId
).status = connectorStatus
;
1839 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
1840 await this.ocppRequestService
.requestHandler
<
1841 FirmwareStatusNotificationRequest
,
1842 FirmwareStatusNotificationResponse
1843 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1844 status: FirmwareStatus
.Installed
,
1846 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
1850 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1851 this.startAutomaticTransactionGenerator();
1853 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1856 private async stopMessageSequence(
1857 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1859 // Stop WebSocket ping
1860 this.stopWebSocketPing();
1862 this.stopHeartbeat();
1863 // Stop ongoing transactions
1864 if (this.automaticTransactionGenerator
?.started
=== true) {
1865 this.stopAutomaticTransactionGenerator();
1867 await this.stopRunningTransactions(reason
);
1869 for (const connectorId
of this.connectors
.keys()) {
1870 if (connectorId
> 0) {
1871 await this.ocppRequestService
.requestHandler
<
1872 StatusNotificationRequest
,
1873 StatusNotificationResponse
1876 RequestCommand
.STATUS_NOTIFICATION
,
1877 OCPPServiceUtils
.buildStatusNotificationRequest(
1880 ConnectorStatusEnum
.UNAVAILABLE
1883 this.getConnectorStatus(connectorId
).status = undefined;
1888 private startWebSocketPing(): void {
1889 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1891 StandardParametersKey
.WebSocketPingInterval
1893 ? Utils
.convertToInt(
1894 ChargingStationConfigurationUtils
.getConfigurationKey(
1896 StandardParametersKey
.WebSocketPingInterval
1900 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1901 this.webSocketPingSetInterval
= setInterval(() => {
1902 if (this.isWebSocketConnectionOpened() === true) {
1903 this.wsConnection
?.ping();
1905 }, webSocketPingInterval
* 1000);
1907 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
1908 webSocketPingInterval
1911 } else if (this.webSocketPingSetInterval
) {
1913 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
1914 webSocketPingInterval
1919 `${this.logPrefix()} WebSocket ping interval set to ${
1920 webSocketPingInterval
1921 ? Utils.formatDurationSeconds(webSocketPingInterval)
1922 : webSocketPingInterval
1923 }, not starting the WebSocket ping`
1928 private stopWebSocketPing(): void {
1929 if (this.webSocketPingSetInterval
) {
1930 clearInterval(this.webSocketPingSetInterval
);
1934 private getConfiguredSupervisionUrl(): URL
{
1935 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
1936 if (Utils
.isNotEmptyArray(supervisionUrls
)) {
1937 switch (Configuration
.getSupervisionUrlDistribution()) {
1938 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1940 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1942 case SupervisionUrlDistribution
.RANDOM
:
1943 this.configuredSupervisionUrlIndex
= Math.floor(
1944 Utils
.secureRandom() * supervisionUrls
.length
1947 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1948 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1952 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1953 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1956 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1959 return new URL(supervisionUrls
[this.configuredSupervisionUrlIndex
]);
1961 return new URL(supervisionUrls
as string);
1964 private getHeartbeatInterval(): number {
1965 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1967 StandardParametersKey
.HeartbeatInterval
1969 if (HeartbeatInterval
) {
1970 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1972 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1974 StandardParametersKey
.HeartBeatInterval
1976 if (HeartBeatInterval
) {
1977 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1979 this.stationInfo
?.autoRegister
=== false &&
1981 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1982 Constants.DEFAULT_HEARTBEAT_INTERVAL
1985 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1988 private stopHeartbeat(): void {
1989 if (this.heartbeatSetInterval
) {
1990 clearInterval(this.heartbeatSetInterval
);
1994 private terminateWSConnection(): void {
1995 if (this.isWebSocketConnectionOpened() === true) {
1996 this.wsConnection
?.terminate();
1997 this.wsConnection
= null;
2001 private stopMeterValues(connectorId
: number) {
2002 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2003 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
2007 private getReconnectExponentialDelay(): boolean {
2008 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2011 private async reconnect(): Promise
<void> {
2012 // Stop WebSocket ping
2013 this.stopWebSocketPing();
2015 this.stopHeartbeat();
2016 // Stop the ATG if needed
2017 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2018 this.stopAutomaticTransactionGenerator();
2021 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2022 this.getAutoReconnectMaxRetries() === -1
2024 this.autoReconnectRetryCount
++;
2025 const reconnectDelay
= this.getReconnectExponentialDelay()
2026 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2027 : this.getConnectionTimeout() * 1000;
2028 const reconnectDelayWithdraw
= 1000;
2029 const reconnectTimeout
=
2030 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2031 ? reconnectDelay
- reconnectDelayWithdraw
2034 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2037 )}ms, timeout ${reconnectTimeout}ms`
2039 await Utils
.sleep(reconnectDelay
);
2041 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2043 this.openWSConnection(
2044 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2045 { closeOpened
: true }
2047 this.wsConnectionRestarted
= true;
2048 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2050 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2051 this.autoReconnectRetryCount
2052 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
2057 private getAutomaticTransactionGeneratorConfigurationFromTemplate():
2058 | AutomaticTransactionGeneratorConfiguration
2060 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
2063 private initializeConnectorStatus(connectorId
: number): void {
2064 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2065 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2066 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2067 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2068 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2069 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;