1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
6 BootNotificationRequest
,
10 IncomingRequestCommand
,
13 StatusNotificationRequest
,
14 } from
'../types/ocpp/Requests';
16 BootNotificationResponse
,
22 StatusNotificationResponse
,
23 } from
'../types/ocpp/Responses';
27 ChargingSchedulePeriod
,
28 } from
'../types/ocpp/ChargingProfile';
29 import ChargingStationConfiguration
, { Section
} from
'../types/ChargingStationConfiguration';
30 import ChargingStationOcppConfiguration
, {
32 } from
'../types/ChargingStationOcppConfiguration';
33 import ChargingStationTemplate
, {
39 } from
'../types/ChargingStationTemplate';
41 ConnectorPhaseRotation
,
42 StandardParametersKey
,
43 SupportedFeatureProfiles
,
44 VendorDefaultParametersKey
,
45 } from
'../types/ocpp/Configuration';
46 import { MeterValue
, MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
48 StopTransactionReason
,
49 StopTransactionRequest
,
50 StopTransactionResponse
,
51 } from
'../types/ocpp/Transaction';
52 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
53 import WebSocket
, { Data
, OPEN
, RawData
} from
'ws';
55 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
56 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
57 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
58 import ChargingStationInfo from
'../types/ChargingStationInfo';
59 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
60 import Configuration from
'../utils/Configuration';
61 import { ConnectorStatus
} from
'../types/ConnectorStatus';
62 import Constants from
'../utils/Constants';
63 import { ErrorType
} from
'../types/ocpp/ErrorType';
64 import { FileType
} from
'../types/FileType';
65 import FileUtils from
'../utils/FileUtils';
66 import { JsonType
} from
'../types/JsonType';
67 import { MessageType
} from
'../types/ocpp/MessageType';
68 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
69 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
70 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
71 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
72 import OCPPError from
'../exception/OCPPError';
73 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
74 import OCPPRequestService from
'./ocpp/OCPPRequestService';
75 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
76 import PerformanceStatistics from
'../performance/PerformanceStatistics';
77 import { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
78 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
79 import { URL
} from
'url';
80 import Utils from
'../utils/Utils';
81 import crypto from
'crypto';
83 import logger from
'../utils/Logger';
84 import { parentPort
} from
'worker_threads';
85 import path from
'path';
87 export default class ChargingStation
{
88 public hashId
!: string;
89 public readonly templateFile
: string;
90 public authorizedTags
: string[];
91 public stationInfo
!: ChargingStationInfo
;
92 public readonly connectors
: Map
<number, ConnectorStatus
>;
93 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
94 public wsConnection
!: WebSocket
;
95 public readonly requests
: Map
<string, CachedRequest
>;
96 public performanceStatistics
!: PerformanceStatistics
;
97 public heartbeatSetInterval
!: NodeJS
.Timeout
;
98 public ocppRequestService
!: OCPPRequestService
;
99 public bootNotificationResponse
!: BootNotificationResponse
| null;
100 private readonly index
: number;
101 private configurationFile
!: string;
102 private bootNotificationRequest
!: BootNotificationRequest
;
103 private connectorsConfigurationHash
!: string;
104 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
105 private readonly messageBuffer
: Set
<string>;
106 private wsConfiguredConnectionUrl
!: URL
;
107 private wsConnectionRestarted
: boolean;
108 private stopped
: boolean;
109 private autoReconnectRetryCount
: number;
110 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
111 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
113 constructor(index
: number, templateFile
: string) {
115 this.templateFile
= templateFile
;
116 this.stopped
= false;
117 this.wsConnectionRestarted
= false;
118 this.autoReconnectRetryCount
= 0;
119 this.connectors
= new Map
<number, ConnectorStatus
>();
120 this.requests
= new Map
<string, CachedRequest
>();
121 this.messageBuffer
= new Set
<string>();
123 this.authorizedTags
= this.getAuthorizedTags();
126 private get
wsConnectionUrl(): URL
{
127 return this.getSupervisionUrlOcppConfiguration()
129 this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value
+
131 this.stationInfo
.chargingStationId
133 : this.wsConfiguredConnectionUrl
;
136 public logPrefix(): string {
137 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
140 public getBootNotificationRequest(): BootNotificationRequest
{
141 return this.bootNotificationRequest
;
144 public getRandomIdTag(): string {
145 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
146 return this.authorizedTags
[index
];
149 public hasAuthorizedTags(): boolean {
150 return !Utils
.isEmptyArray(this.authorizedTags
);
153 public getEnableStatistics(): boolean | undefined {
154 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
155 ? this.stationInfo
.enableStatistics
159 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
160 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
163 public getNumberOfPhases(): number | undefined {
164 switch (this.getCurrentOutType()) {
166 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
)
167 ? this.stationInfo
.numberOfPhases
174 public isWebSocketConnectionOpened(): boolean {
175 return this?.wsConnection
?.readyState
=== OPEN
;
178 public getRegistrationStatus(): RegistrationStatus
{
179 return this?.bootNotificationResponse
?.status;
182 public isInUnknownState(): boolean {
183 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
186 public isInPendingState(): boolean {
187 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
190 public isInAcceptedState(): boolean {
191 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
194 public isInRejectedState(): boolean {
195 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
198 public isRegistered(): boolean {
199 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
202 public isChargingStationAvailable(): boolean {
203 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
206 public isConnectorAvailable(id
: number): boolean {
207 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
210 public getNumberOfConnectors(): number {
211 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
214 public getConnectorStatus(id
: number): ConnectorStatus
{
215 return this.connectors
.get(id
);
218 public getCurrentOutType(): CurrentType
| undefined {
219 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
222 public getOcppStrictCompliance(): boolean {
223 return this.stationInfo
.ocppStrictCompliance
?? false;
226 public getVoltageOut(): number | undefined {
227 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
229 }, cannot define default voltage out`;
230 let defaultVoltageOut
: number;
231 switch (this.getCurrentOutType()) {
233 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
236 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
239 logger
.error(errMsg
);
240 throw new Error(errMsg
);
242 return !Utils
.isUndefined(this.stationInfo
.voltageOut
)
243 ? this.stationInfo
.voltageOut
247 public getConnectorMaximumAvailablePower(connectorId
: number): number {
248 let connectorAmperageLimitationPowerLimit
: number;
250 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
251 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
253 connectorAmperageLimitationPowerLimit
=
254 (this.getCurrentOutType() === CurrentType
.AC
255 ? ACElectricUtils
.powerTotal(
256 this.getNumberOfPhases(),
257 this.getVoltageOut(),
258 this.getAmperageLimitation() * this.getNumberOfConnectors()
260 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
261 this.stationInfo
.powerDivider
;
263 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
264 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
266 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
267 isNaN(connectorAmperageLimitationPowerLimit
)
269 : connectorAmperageLimitationPowerLimit
,
270 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
274 public getTransactionIdTag(transactionId
: number): string | undefined {
275 for (const connectorId
of this.connectors
.keys()) {
276 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
277 return this.getConnectorStatus(connectorId
).transactionIdTag
;
282 public getOutOfOrderEndMeterValues(): boolean {
283 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
286 public getBeginEndMeterValues(): boolean {
287 return this.stationInfo
.beginEndMeterValues
?? false;
290 public getMeteringPerTransaction(): boolean {
291 return this.stationInfo
.meteringPerTransaction
?? true;
294 public getTransactionDataMeterValues(): boolean {
295 return this.stationInfo
.transactionDataMeterValues
?? false;
298 public getMainVoltageMeterValues(): boolean {
299 return this.stationInfo
.mainVoltageMeterValues
?? true;
302 public getPhaseLineToLineVoltageMeterValues(): boolean {
303 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
306 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
307 for (const connectorId
of this.connectors
.keys()) {
310 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
317 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
318 const transactionConnectorStatus
= this.getConnectorStatus(
319 this.getConnectorIdByTransactionId(transactionId
)
321 if (this.getMeteringPerTransaction()) {
322 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
324 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
327 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
328 const connectorStatus
= this.getConnectorStatus(connectorId
);
329 if (this.getMeteringPerTransaction()) {
330 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
332 return connectorStatus
?.energyActiveImportRegisterValue
;
335 public getAuthorizeRemoteTxRequests(): boolean {
336 const authorizeRemoteTxRequests
= this.getConfigurationKey(
337 StandardParametersKey
.AuthorizeRemoteTxRequests
339 return authorizeRemoteTxRequests
340 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
344 public getLocalAuthListEnabled(): boolean {
345 const localAuthListEnabled
= this.getConfigurationKey(
346 StandardParametersKey
.LocalAuthListEnabled
348 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
351 public restartWebSocketPing(): void {
352 // Stop WebSocket ping
353 this.stopWebSocketPing();
354 // Start WebSocket ping
355 this.startWebSocketPing();
358 public getSampledValueTemplate(
360 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
361 phase
?: MeterValuePhase
362 ): SampledValueTemplate
| undefined {
363 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
364 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
366 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
371 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
372 !this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
377 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
378 StandardParametersKey.MeterValuesSampledData
383 const sampledValueTemplates
: SampledValueTemplate
[] =
384 this.getConnectorStatus(connectorId
).MeterValues
;
387 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
391 !Constants
.SUPPORTED_MEASURANDS
.includes(
392 sampledValueTemplates
[index
]?.measurand
??
393 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
397 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
401 sampledValueTemplates
[index
]?.phase
=== phase
&&
402 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
403 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
407 return sampledValueTemplates
[index
];
410 !sampledValueTemplates
[index
].phase
&&
411 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
412 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
416 return sampledValueTemplates
[index
];
418 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
419 (!sampledValueTemplates
[index
].measurand
||
420 sampledValueTemplates
[index
].measurand
=== measurand
)
422 return sampledValueTemplates
[index
];
425 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
426 const errorMsg
= `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
427 logger
.error(errorMsg
);
428 throw new Error(errorMsg
);
431 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
435 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
436 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
439 public startHeartbeat(): void {
441 this.getHeartbeatInterval() &&
442 this.getHeartbeatInterval() > 0 &&
443 !this.heartbeatSetInterval
445 // eslint-disable-next-line @typescript-eslint/no-misused-promises
446 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
447 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
448 RequestCommand
.HEARTBEAT
450 }, this.getHeartbeatInterval());
453 ' Heartbeat started every ' +
454 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
456 } else if (this.heartbeatSetInterval
) {
459 ' Heartbeat already started every ' +
460 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
464 `${this.logPrefix()} Heartbeat interval set to ${
465 this.getHeartbeatInterval()
466 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
467 : this.getHeartbeatInterval()
468 }, not starting the heartbeat`
473 public restartHeartbeat(): void {
475 this.stopHeartbeat();
477 this.startHeartbeat();
480 public startMeterValues(connectorId
: number, interval
: number): void {
481 if (connectorId
=== 0) {
483 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
487 if (!this.getConnectorStatus(connectorId
)) {
489 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
493 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
495 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
499 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
500 !this.getConnectorStatus(connectorId
)?.transactionId
503 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
508 // eslint-disable-next-line @typescript-eslint/no-misused-promises
509 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
510 // eslint-disable-next-line @typescript-eslint/no-misused-promises
511 async (): Promise
<void> => {
512 // FIXME: Implement OCPP version agnostic helpers
513 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
516 this.getConnectorStatus(connectorId
).transactionId
,
519 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
520 RequestCommand
.METER_VALUES
,
523 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
524 meterValue
: [meterValue
],
532 `${this.logPrefix()} Charging station ${
533 StandardParametersKey.MeterValueSampleInterval
534 } configuration set to ${
535 interval ? Utils.formatDurationMilliSeconds(interval) : interval
536 }, not sending MeterValues`
541 public start(): void {
542 if (this.getEnableStatistics()) {
543 this.performanceStatistics
.start();
545 this.openWSConnection();
546 // Handle WebSocket message
547 this.wsConnection
.on(
549 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
551 // Handle WebSocket error
552 this.wsConnection
.on(
554 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
556 // Handle WebSocket close
557 this.wsConnection
.on(
559 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
561 // Handle WebSocket open
562 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
563 // Handle WebSocket ping
564 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
565 // Handle WebSocket pong
566 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
567 // Monitor authorization file
568 FileUtils
.watchJsonFile
<string[]>(
570 FileType
.Authorization
,
571 this.getAuthorizationFile(),
574 // Monitor charging station template file
575 FileUtils
.watchJsonFile(
577 FileType
.ChargingStationTemplate
,
580 (event
, filename
): void => {
581 if (filename
&& event
=== 'change') {
584 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
586 } file have changed, reload`
592 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
593 this.automaticTransactionGenerator
595 this.automaticTransactionGenerator
.stop();
597 this.startAutomaticTransactionGenerator();
598 if (this.getEnableStatistics()) {
599 this.performanceStatistics
.restart();
601 this.performanceStatistics
.stop();
603 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
606 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
613 parentPort
.postMessage({
614 id
: ChargingStationWorkerMessageEvents
.STARTED
,
615 data
: { id
: this.stationInfo
.chargingStationId
},
619 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
620 // Stop message sequence
621 await this.stopMessageSequence(reason
);
622 for (const connectorId
of this.connectors
.keys()) {
623 if (connectorId
> 0) {
624 await this.ocppRequestService
.requestHandler
<
625 StatusNotificationRequest
,
626 StatusNotificationResponse
627 >(RequestCommand
.STATUS_NOTIFICATION
, {
629 status: ChargePointStatus
.UNAVAILABLE
,
630 errorCode
: ChargePointErrorCode
.NO_ERROR
,
632 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
635 if (this.isWebSocketConnectionOpened()) {
636 this.wsConnection
.close();
638 if (this.getEnableStatistics()) {
639 this.performanceStatistics
.stop();
641 this.bootNotificationResponse
= null;
642 parentPort
.postMessage({
643 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
644 data
: { id
: this.stationInfo
.chargingStationId
},
649 public getConfigurationKey(
650 key
: string | StandardParametersKey
,
651 caseInsensitive
= false
652 ): ConfigurationKey
| undefined {
653 return this.ocppConfiguration
.configurationKey
.find((configElement
) => {
654 if (caseInsensitive
) {
655 return configElement
.key
.toLowerCase() === key
.toLowerCase();
657 return configElement
.key
=== key
;
661 public addConfigurationKey(
662 key
: string | StandardParametersKey
,
664 options
: { readonly?: boolean; visible
?: boolean; reboot
?: boolean } = {
669 params
: { overwrite
?: boolean; save
?: boolean } = { overwrite
: false, save
: false }
671 options
= options
?? ({} as { readonly?: boolean; visible
?: boolean; reboot
?: boolean });
672 options
.readonly = options
?.readonly ?? false;
673 options
.visible
= options
?.visible
?? true;
674 options
.reboot
= options
?.reboot
?? false;
675 let keyFound
= this.getConfigurationKey(key
);
676 if (keyFound
&& params
?.overwrite
) {
677 this.deleteConfigurationKey(keyFound
.key
, { save
: false });
678 keyFound
= undefined;
681 this.ocppConfiguration
.configurationKey
.push({
683 readonly: options
.readonly,
685 visible
: options
.visible
,
686 reboot
: options
.reboot
,
688 params
?.save
&& this.saveOcppConfiguration();
691 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
697 public setConfigurationKeyValue(
698 key
: string | StandardParametersKey
,
700 caseInsensitive
= false
702 const keyFound
= this.getConfigurationKey(key
, caseInsensitive
);
704 this.ocppConfiguration
.configurationKey
[
705 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
)
707 this.saveOcppConfiguration();
710 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
716 public deleteConfigurationKey(
717 key
: string | StandardParametersKey
,
718 params
: { save
?: boolean; caseInsensitive
?: boolean } = { save
: true, caseInsensitive
: false }
719 ): ConfigurationKey
[] {
720 const keyFound
= this.getConfigurationKey(key
, params
?.caseInsensitive
);
722 const deletedConfigurationKey
= this.ocppConfiguration
.configurationKey
.splice(
723 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
),
726 params
?.save
&& this.saveOcppConfiguration();
727 return deletedConfigurationKey
;
731 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
732 const timestamp
= new Date().getTime();
733 let matchingChargingProfile
: ChargingProfile
;
734 let chargingSchedulePeriods
: ChargingSchedulePeriod
[] = [];
735 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
)?.chargingProfiles
)) {
736 const chargingProfiles
: ChargingProfile
[] = this.getConnectorStatus(
738 ).chargingProfiles
.filter(
740 timestamp
>= chargingProfile
.chargingSchedule
?.startSchedule
.getTime() &&
742 chargingProfile
.chargingSchedule
?.startSchedule
.getTime() +
743 chargingProfile
.chargingSchedule
.duration
* 1000 &&
744 chargingProfile
?.stackLevel
=== Math.max(...chargingProfiles
.map((cp
) => cp
?.stackLevel
))
746 if (!Utils
.isEmptyArray(chargingProfiles
)) {
747 for (const chargingProfile
of chargingProfiles
) {
748 if (!Utils
.isEmptyArray(chargingProfile
.chargingSchedule
.chargingSchedulePeriod
)) {
749 chargingSchedulePeriods
=
750 chargingProfile
.chargingSchedule
.chargingSchedulePeriod
.filter(
751 (chargingSchedulePeriod
, index
) => {
753 chargingProfile
.chargingSchedule
.startSchedule
.getTime() +
754 chargingSchedulePeriod
.startPeriod
* 1000 &&
755 ((chargingProfile
.chargingSchedule
.chargingSchedulePeriod
[index
+ 1] &&
757 chargingProfile
.chargingSchedule
.startSchedule
.getTime() +
758 chargingProfile
.chargingSchedule
.chargingSchedulePeriod
[index
+ 1]
761 !chargingProfile
.chargingSchedule
.chargingSchedulePeriod
[index
+ 1]);
764 if (!Utils
.isEmptyArray(chargingSchedulePeriods
)) {
765 matchingChargingProfile
= chargingProfile
;
773 if (!Utils
.isEmptyArray(chargingSchedulePeriods
)) {
774 switch (this.getCurrentOutType()) {
777 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
=== ChargingRateUnitType
.WATT
778 ? chargingSchedulePeriods
[0].limit
779 : ACElectricUtils
.powerTotal(
780 this.getNumberOfPhases(),
781 this.getVoltageOut(),
782 chargingSchedulePeriods
[0].limit
787 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
=== ChargingRateUnitType
.WATT
788 ? chargingSchedulePeriods
[0].limit
789 : DCElectricUtils
.power(this.getVoltageOut(), chargingSchedulePeriods
[0].limit
);
792 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
793 if (limit
> connectorMaximumPower
) {
795 `${this.logPrefix()} Charging profile id ${
796 matchingChargingProfile.chargingProfileId
797 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
798 this.getConnectorStatus(connectorId
).chargingProfiles
800 limit
= connectorMaximumPower
;
805 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
806 let cpReplaced
= false;
807 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
808 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
809 (chargingProfile
: ChargingProfile
, index
: number) => {
811 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
812 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
813 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
815 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
821 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
824 public resetConnectorStatus(connectorId
: number): void {
825 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
826 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
827 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
828 this.getConnectorStatus(connectorId
).transactionStarted
= false;
829 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
830 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
831 delete this.getConnectorStatus(connectorId
).transactionId
;
832 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
833 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
834 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
835 this.stopMeterValues(connectorId
);
838 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
839 return this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)?.value
.includes(
844 public bufferMessage(message
: string): void {
845 this.messageBuffer
.add(message
);
848 private flushMessageBuffer() {
849 if (this.messageBuffer
.size
> 0) {
850 this.messageBuffer
.forEach((message
) => {
851 // TODO: evaluate the need to track performance
852 this.wsConnection
.send(message
);
853 this.messageBuffer
.delete(message
);
858 private getSupervisionUrlOcppConfiguration(): boolean {
859 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
862 private getSupervisionUrlOcppKey(): string {
863 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
866 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
867 // In case of multiple instances: add instance index to charging station id
868 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
869 const idSuffix
= stationTemplate
.nameSuffix
?? '';
870 const idStr
= '000000000' + this.index
.toString();
871 return stationTemplate
.fixedName
872 ? stationTemplate
.baseName
873 : stationTemplate
.baseName
+
875 instanceIndex
.toString() +
876 idStr
.substring(idStr
.length
- 4) +
880 private getRandomSerialNumberSuffix(params
?: {
881 randomBytesLength
?: number;
884 const randomSerialNumberSuffix
= crypto
885 .randomBytes(params
?.randomBytesLength
?? 16)
887 if (params
?.upperCase
) {
888 return randomSerialNumberSuffix
.toUpperCase();
890 return randomSerialNumberSuffix
;
893 private getTemplateFromFile(): ChargingStationTemplate
| null {
894 let template
: ChargingStationTemplate
= null;
896 const measureId
= `${FileType.ChargingStationTemplate} read`;
897 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
898 template
= JSON
.parse(fs
.readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
899 PerformanceStatistics
.endMeasure(measureId
, beginId
);
901 FileUtils
.handleFileException(
903 FileType
.ChargingStationTemplate
,
905 error
as NodeJS
.ErrnoException
911 private createSerialNumber(
912 stationInfo
: ChargingStationInfo
,
913 existingStationInfo
?: ChargingStationInfo
,
914 params
: { randomSerialNumberUpperCase
?: boolean; randomSerialNumber
?: boolean } = {
915 randomSerialNumberUpperCase
: true,
916 randomSerialNumber
: true,
919 params
= params
?? {};
920 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
921 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
922 if (existingStationInfo
) {
923 existingStationInfo
?.chargePointSerialNumber
&&
924 (stationInfo
.chargePointSerialNumber
= existingStationInfo
.chargePointSerialNumber
);
925 existingStationInfo
?.chargeBoxSerialNumber
&&
926 (stationInfo
.chargeBoxSerialNumber
= existingStationInfo
.chargeBoxSerialNumber
);
927 existingStationInfo
?.meterSerialNumber
&&
928 (stationInfo
.meterSerialNumber
= existingStationInfo
.meterSerialNumber
);
930 const serialNumberSuffix
= params
?.randomSerialNumber
931 ? this.getRandomSerialNumberSuffix({ upperCase
: params
.randomSerialNumberUpperCase
})
933 stationInfo
.chargePointSerialNumber
=
934 stationInfo
?.chargePointSerialNumberPrefix
&&
935 stationInfo
.chargePointSerialNumberPrefix
+ serialNumberSuffix
;
936 stationInfo
.chargeBoxSerialNumber
=
937 stationInfo
?.chargeBoxSerialNumberPrefix
&&
938 stationInfo
.chargeBoxSerialNumberPrefix
+ serialNumberSuffix
;
939 stationInfo
.meterSerialNumber
=
940 stationInfo
?.meterSerialNumberPrefix
&&
941 stationInfo
.meterSerialNumberPrefix
+ serialNumberSuffix
;
945 private getStationInfoFromTemplate(): ChargingStationInfo
{
946 const stationInfo
: ChargingStationInfo
=
947 this.getTemplateFromFile() ?? ({} as ChargingStationInfo
);
948 stationInfo
.hash
= crypto
949 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
950 .update(JSON
.stringify(stationInfo
))
952 const chargingStationId
= this.getChargingStationId(stationInfo
);
953 // Deprecation template keys section
954 this.warnDeprecatedTemplateKey(
958 "Use 'supervisionUrls' instead"
960 this.convertDeprecatedTemplateKey(stationInfo
, 'supervisionUrl', 'supervisionUrls');
961 stationInfo
.wsOptions
= stationInfo
?.wsOptions
?? {};
962 if (!Utils
.isEmptyArray(stationInfo
.power
)) {
963 stationInfo
.power
= stationInfo
.power
as number[];
964 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationInfo
.power
.length
);
965 stationInfo
.maximumPower
=
966 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
967 ? stationInfo
.power
[powerArrayRandomIndex
] * 1000
968 : stationInfo
.power
[powerArrayRandomIndex
];
970 stationInfo
.power
= stationInfo
.power
as number;
971 stationInfo
.maximumPower
=
972 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
973 ? stationInfo
.power
* 1000
976 delete stationInfo
.power
;
977 delete stationInfo
.powerUnit
;
978 stationInfo
.chargingStationId
= chargingStationId
;
979 stationInfo
.resetTime
= stationInfo
.resetTime
980 ? stationInfo
.resetTime
* 1000
981 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
985 private getStationInfoFromFile(): ChargingStationInfo
| null {
986 return this.getConfigurationFromFile()?.stationInfo
?? null;
989 private getStationInfo(): ChargingStationInfo
{
990 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
991 this.hashId
= this.getHashId(stationInfoFromTemplate
);
992 this.configurationFile
= path
.join(
993 path
.resolve(__dirname
, '../'),
996 this.hashId
+ '.json'
998 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
999 if (stationInfoFromFile
?.hash
=== stationInfoFromTemplate
.hash
) {
1000 return stationInfoFromFile
;
1002 this.createSerialNumber(stationInfoFromTemplate
, stationInfoFromFile
);
1003 return stationInfoFromTemplate
;
1006 private saveStationInfo(): void {
1007 this.saveConfiguration(Section
.stationInfo
);
1010 private getOcppVersion(): OCPPVersion
{
1011 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
1014 private getOcppPersistentConfiguration(): boolean {
1015 return this.stationInfo
.ocppPersistentConfiguration
?? true;
1018 private handleUnsupportedVersion(version
: OCPPVersion
) {
1019 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
1022 logger
.error(errMsg
);
1023 throw new Error(errMsg
);
1026 private createBootNotificationRequest(stationInfo
: ChargingStationInfo
): BootNotificationRequest
{
1028 chargePointModel
: stationInfo
.chargePointModel
,
1029 chargePointVendor
: stationInfo
.chargePointVendor
,
1030 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
1031 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
1033 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
1034 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
1036 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
1037 firmwareVersion
: stationInfo
.firmwareVersion
,
1039 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
1040 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
1041 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
1042 meterSerialNumber
: stationInfo
.meterSerialNumber
,
1044 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
1045 meterType
: stationInfo
.meterType
,
1050 private getHashId(stationInfo
: ChargingStationInfo
): string {
1051 const hashBootNotificationRequest
= {
1052 chargePointModel
: stationInfo
.chargePointModel
,
1053 chargePointVendor
: stationInfo
.chargePointVendor
,
1054 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumberPrefix
) && {
1055 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumberPrefix
,
1057 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumberPrefix
) && {
1058 chargePointSerialNumber
: stationInfo
.chargePointSerialNumberPrefix
,
1060 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
1061 firmwareVersion
: stationInfo
.firmwareVersion
,
1063 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
1064 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
1065 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumberPrefix
) && {
1066 meterSerialNumber
: stationInfo
.meterSerialNumberPrefix
,
1068 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
1069 meterType
: stationInfo
.meterType
,
1073 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1074 .update(JSON
.stringify(hashBootNotificationRequest
) + stationInfo
.chargingStationId
)
1078 private initialize(): void {
1079 this.stationInfo
= this.getStationInfo();
1080 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
1081 this.bootNotificationRequest
= this.createBootNotificationRequest(this.stationInfo
);
1082 this.ocppConfiguration
= this.getOcppConfiguration();
1083 delete this.stationInfo
.Configuration
;
1084 this.wsConfiguredConnectionUrl
= new URL(
1085 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
1087 // Build connectors if needed
1088 const maxConnectors
= this.getMaxNumberOfConnectors();
1089 if (maxConnectors
<= 0) {
1091 `${this.logPrefix()} Charging station template ${
1093 } with ${maxConnectors} connectors`
1096 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
1097 if (templateMaxConnectors
<= 0) {
1099 `${this.logPrefix()} Charging station template ${
1101 } with no connector configuration`
1104 if (!this.stationInfo
.Connectors
[0]) {
1106 `${this.logPrefix()} Charging station template ${
1108 } with no connector Id 0 configuration`
1114 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
1115 !this.stationInfo
.randomConnectors
1118 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
1120 }, forcing random connector configurations affectation`
1122 this.stationInfo
.randomConnectors
= true;
1124 const connectorsConfigHash
= crypto
1125 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1126 .update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString())
1128 const connectorsConfigChanged
=
1129 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1130 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1131 connectorsConfigChanged
&& this.connectors
.clear();
1132 this.connectorsConfigurationHash
= connectorsConfigHash
;
1133 // Add connector Id 0
1134 let lastConnector
= '0';
1135 for (lastConnector
in this.stationInfo
.Connectors
) {
1136 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1138 lastConnectorId
=== 0 &&
1139 this.getUseConnectorId0() &&
1140 this.stationInfo
.Connectors
[lastConnector
]
1142 this.connectors
.set(
1144 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
])
1146 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1147 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1148 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1152 // Generate all connectors
1154 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0
1156 for (let index
= 1; index
<= maxConnectors
; index
++) {
1157 const randConnectorId
= this.stationInfo
.randomConnectors
1158 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1160 this.connectors
.set(
1162 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
])
1164 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1165 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1166 this.getConnectorStatus(index
).chargingProfiles
= [];
1171 this.stationInfo
.maximumAmperage
= this.getMaximumAmperage();
1172 this.saveStationInfo();
1173 // Avoid duplication of connectors related information in RAM
1174 delete this.stationInfo
.Connectors
;
1175 // Initialize transaction attributes on connectors
1176 for (const connectorId
of this.connectors
.keys()) {
1177 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1178 this.initializeConnectorStatus(connectorId
);
1181 // OCPP configuration
1182 this.initializeOcppConfiguration();
1183 if (this.getEnableStatistics()) {
1184 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1186 this.stationInfo
.chargingStationId
,
1187 this.wsConnectionUrl
1190 switch (this.getOcppVersion()) {
1191 case OCPPVersion
.VERSION_16
:
1192 this.ocppIncomingRequestService
=
1193 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>(this);
1194 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1196 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(this)
1200 this.handleUnsupportedVersion(this.getOcppVersion());
1203 if (this.stationInfo
.autoRegister
) {
1204 this.bootNotificationResponse
= {
1205 currentTime
: new Date().toISOString(),
1206 interval
: this.getHeartbeatInterval() / 1000,
1207 status: RegistrationStatus
.ACCEPTED
,
1210 this.stationInfo
.powerDivider
= this.getPowerDivider();
1213 private initializeOcppConfiguration(): void {
1215 this.getSupervisionUrlOcppConfiguration() &&
1216 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1218 this.addConfigurationKey(
1219 this.getSupervisionUrlOcppKey(),
1220 this.getConfiguredSupervisionUrl().href
,
1224 !this.getSupervisionUrlOcppConfiguration() &&
1225 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1227 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save
: false });
1230 this.stationInfo
.amperageLimitationOcppKey
&&
1231 !this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1233 this.addConfigurationKey(
1234 this.stationInfo
.amperageLimitationOcppKey
,
1235 (this.stationInfo
.maximumAmperage
* this.getAmperageLimitationUnitDivider()).toString()
1238 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
1239 this.addConfigurationKey(
1240 StandardParametersKey
.SupportedFeatureProfiles
,
1241 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1244 this.addConfigurationKey(
1245 StandardParametersKey
.NumberOfConnectors
,
1246 this.getNumberOfConnectors().toString(),
1250 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
1251 this.addConfigurationKey(
1252 StandardParametersKey
.MeterValuesSampledData
,
1253 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1256 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
1257 const connectorPhaseRotation
= [];
1258 for (const connectorId
of this.connectors
.keys()) {
1260 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1261 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1262 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1263 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1265 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1266 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1267 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1268 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1271 this.addConfigurationKey(
1272 StandardParametersKey
.ConnectorPhaseRotation
,
1273 connectorPhaseRotation
.toString()
1276 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
1277 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1280 !this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
) &&
1281 this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)?.value
.includes(
1282 SupportedFeatureProfiles
.LocalAuthListManagement
1285 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
1287 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1288 this.addConfigurationKey(
1289 StandardParametersKey
.ConnectionTimeOut
,
1290 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1293 this.saveOcppConfiguration();
1296 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1297 let configuration
: ChargingStationConfiguration
= null;
1298 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1300 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1301 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1302 configuration
= JSON
.parse(
1303 fs
.readFileSync(this.configurationFile
, 'utf8')
1304 ) as ChargingStationConfiguration
;
1305 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1307 FileUtils
.handleFileException(
1309 FileType
.ChargingStationConfiguration
,
1310 this.configurationFile
,
1311 error
as NodeJS
.ErrnoException
1315 return configuration
;
1318 private saveConfiguration(section
?: Section
): void {
1319 if (this.configurationFile
) {
1321 const configurationData
: ChargingStationConfiguration
=
1322 this.getConfigurationFromFile() ?? {};
1323 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1324 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1327 case Section
.ocppConfiguration
:
1328 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1330 case Section
.stationInfo
:
1331 configurationData
.stationInfo
= this.stationInfo
;
1334 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1335 configurationData
.stationInfo
= this.stationInfo
;
1338 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1339 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1340 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1341 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1342 fs
.closeSync(fileDescriptor
);
1343 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1345 FileUtils
.handleFileException(
1347 FileType
.ChargingStationConfiguration
,
1348 this.configurationFile
,
1349 error
as NodeJS
.ErrnoException
1354 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
1359 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
{
1360 return this.getTemplateFromFile().Configuration
?? ({} as ChargingStationOcppConfiguration
);
1363 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1364 let configuration
: ChargingStationConfiguration
= null;
1365 if (this.getOcppPersistentConfiguration()) {
1366 const configurationFromFile
= this.getConfigurationFromFile();
1367 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1369 configuration
&& delete configuration
.stationInfo
;
1370 return configuration
;
1373 private getOcppConfiguration(): ChargingStationOcppConfiguration
{
1374 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1375 if (!ocppConfiguration
) {
1376 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1378 return ocppConfiguration
;
1381 private saveOcppConfiguration(): void {
1382 if (this.getOcppPersistentConfiguration()) {
1383 this.saveConfiguration(Section
.ocppConfiguration
);
1387 private async onOpen(): Promise
<void> {
1388 if (this.isWebSocketConnectionOpened()) {
1390 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1392 if (!this.isRegistered()) {
1393 // Send BootNotification
1394 let registrationRetryCount
= 0;
1396 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1397 BootNotificationRequest
,
1398 BootNotificationResponse
1400 RequestCommand
.BOOT_NOTIFICATION
,
1402 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1403 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1404 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1405 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1406 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1407 iccid
: this.bootNotificationRequest
.iccid
,
1408 imsi
: this.bootNotificationRequest
.imsi
,
1409 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1410 meterType
: this.bootNotificationRequest
.meterType
,
1412 { skipBufferingOnError
: true }
1414 if (!this.isRegistered()) {
1415 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1417 this.bootNotificationResponse
?.interval
1418 ? this.bootNotificationResponse
.interval
* 1000
1419 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1423 !this.isRegistered() &&
1424 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1425 this.getRegistrationMaxRetries() === -1)
1428 if (this.isRegistered()) {
1429 if (this.isInAcceptedState()) {
1430 await this.startMessageSequence();
1431 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1435 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1438 this.stopped
&& (this.stopped
= false);
1439 this.autoReconnectRetryCount
= 0;
1440 this.wsConnectionRestarted
= false;
1443 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1448 private async onClose(code
: number, reason
: string): Promise
<void> {
1451 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1452 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1454 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1456 )}' and reason '${reason}'`
1458 this.autoReconnectRetryCount
= 0;
1463 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1465 )}' and reason '${reason}'`
1467 await this.reconnect(code
);
1472 private async onMessage(data
: Data
): Promise
<void> {
1473 let messageType
: number;
1474 let messageId
: string;
1475 let commandName
: IncomingRequestCommand
;
1476 let commandPayload
: JsonType
;
1477 let errorType
: ErrorType
;
1478 let errorMessage
: string;
1479 let errorDetails
: JsonType
;
1480 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1481 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1482 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1483 let requestPayload
: JsonType
;
1484 let cachedRequest
: CachedRequest
;
1487 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1488 if (Utils
.isIterable(request
)) {
1489 [messageType
, messageId
] = request
;
1490 // Check the type of message
1491 switch (messageType
) {
1493 case MessageType
.CALL_MESSAGE
:
1494 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1495 if (this.getEnableStatistics()) {
1496 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1499 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1503 // Process the message
1504 await this.ocppIncomingRequestService
.incomingRequestHandler(
1511 case MessageType
.CALL_RESULT_MESSAGE
:
1512 [, , commandPayload
] = request
as Response
;
1514 cachedRequest
= this.requests
.get(messageId
);
1515 if (Utils
.isIterable(cachedRequest
)) {
1516 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1518 throw new OCPPError(
1519 ErrorType
.PROTOCOL_ERROR
,
1520 `Cached request for message id ${messageId} response is not iterable`,
1522 cachedRequest
as unknown
as JsonType
1526 `${this.logPrefix()} << Command '${
1527 requestCommandName ?? ''
1528 }' received response payload: ${JSON.stringify(request)}`
1530 if (!responseCallback
) {
1532 throw new OCPPError(
1533 ErrorType
.INTERNAL_ERROR
,
1534 `Response for unknown message id ${messageId}`,
1539 responseCallback(commandPayload
, requestPayload
);
1542 case MessageType
.CALL_ERROR_MESSAGE
:
1543 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1544 cachedRequest
= this.requests
.get(messageId
);
1545 if (Utils
.isIterable(cachedRequest
)) {
1546 [, rejectCallback
, requestCommandName
] = cachedRequest
;
1548 throw new OCPPError(
1549 ErrorType
.PROTOCOL_ERROR
,
1550 `Cached request for message id ${messageId} error response is not iterable`,
1552 cachedRequest
as unknown
as JsonType
1556 `${this.logPrefix()} << Command '${
1557 requestCommandName ?? ''
1558 }' received error payload: ${JSON.stringify(request)}`
1560 if (!rejectCallback
) {
1562 throw new OCPPError(
1563 ErrorType
.INTERNAL_ERROR
,
1564 `Error response for unknown message id ${messageId}`,
1566 { errorType
, errorMessage
, errorDetails
}
1570 new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
)
1575 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1576 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1577 logger
.error(errMsg
);
1578 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1581 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1588 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1591 this.requests
.get(messageId
),
1595 messageType
=== MessageType
.CALL_MESSAGE
&&
1596 (await this.ocppRequestService
.sendError(
1599 Utils
.isString(commandName
) ? commandName
: requestCommandName
?? null
1604 private onPing(): void {
1605 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1608 private onPong(): void {
1609 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1612 private onError(error
: WSError
): void {
1613 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1616 private getAuthorizationFile(): string | undefined {
1618 this.stationInfo
.authorizationFile
&&
1620 path
.resolve(__dirname
, '../'),
1622 path
.basename(this.stationInfo
.authorizationFile
)
1627 private getAuthorizedTags(): string[] {
1628 let authorizedTags
: string[] = [];
1629 const authorizationFile
= this.getAuthorizationFile();
1630 if (authorizationFile
) {
1632 // Load authorization file
1633 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
1635 FileUtils
.handleFileException(
1637 FileType
.Authorization
,
1639 error
as NodeJS
.ErrnoException
1644 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1647 return authorizedTags
;
1650 private getUseConnectorId0(): boolean | undefined {
1651 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1652 ? this.stationInfo
.useConnectorId0
1656 private getNumberOfRunningTransactions(): number {
1658 for (const connectorId
of this.connectors
.keys()) {
1659 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1667 private getConnectionTimeout(): number | undefined {
1668 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1670 parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ??
1671 Constants
.DEFAULT_CONNECTION_TIMEOUT
1674 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1677 // -1 for unlimited, 0 for disabling
1678 private getAutoReconnectMaxRetries(): number | undefined {
1679 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1680 return this.stationInfo
.autoReconnectMaxRetries
;
1682 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1683 return Configuration
.getAutoReconnectMaxRetries();
1689 private getRegistrationMaxRetries(): number | undefined {
1690 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1691 return this.stationInfo
.registrationMaxRetries
;
1696 private getPowerDivider(): number {
1697 let powerDivider
= this.getNumberOfConnectors();
1698 if (this.stationInfo
.powerSharedByConnectors
) {
1699 powerDivider
= this.getNumberOfRunningTransactions();
1701 return powerDivider
;
1704 private getTemplateMaxNumberOfConnectors(): number {
1705 return Object.keys(this.stationInfo
.Connectors
).length
;
1708 private getMaxNumberOfConnectors(): number {
1709 let maxConnectors
: number;
1710 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1711 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1712 // Distribute evenly the number of connectors
1713 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1714 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1715 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1717 maxConnectors
= this.stationInfo
.Connectors
[0]
1718 ? this.getTemplateMaxNumberOfConnectors() - 1
1719 : this.getTemplateMaxNumberOfConnectors();
1721 return maxConnectors
;
1724 private getMaximumPower(): number {
1725 return (this.stationInfo
['maxPower'] as number) ?? this.stationInfo
.maximumPower
;
1728 private getMaximumAmperage(): number | undefined {
1729 const maximumPower
= this.getMaximumPower();
1730 switch (this.getCurrentOutType()) {
1731 case CurrentType
.AC
:
1732 return ACElectricUtils
.amperagePerPhaseFromPower(
1733 this.getNumberOfPhases(),
1734 maximumPower
/ this.getNumberOfConnectors(),
1735 this.getVoltageOut()
1737 case CurrentType
.DC
:
1738 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut());
1742 private getAmperageLimitationUnitDivider(): number {
1743 let unitDivider
= 1;
1744 switch (this.stationInfo
.amperageLimitationUnit
) {
1745 case AmpereUnits
.DECI_AMPERE
:
1748 case AmpereUnits
.CENTI_AMPERE
:
1751 case AmpereUnits
.MILLI_AMPERE
:
1758 private getAmperageLimitation(): number | undefined {
1760 this.stationInfo
.amperageLimitationOcppKey
&&
1761 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1765 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
).value
1766 ) / this.getAmperageLimitationUnitDivider()
1771 private async startMessageSequence(): Promise
<void> {
1772 if (this.stationInfo
.autoRegister
) {
1773 await this.ocppRequestService
.requestHandler
<
1774 BootNotificationRequest
,
1775 BootNotificationResponse
1777 RequestCommand
.BOOT_NOTIFICATION
,
1779 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1780 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1781 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1782 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1783 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1784 iccid
: this.bootNotificationRequest
.iccid
,
1785 imsi
: this.bootNotificationRequest
.imsi
,
1786 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1787 meterType
: this.bootNotificationRequest
.meterType
,
1789 { skipBufferingOnError
: true }
1792 // Start WebSocket ping
1793 this.startWebSocketPing();
1795 this.startHeartbeat();
1796 // Initialize connectors status
1797 for (const connectorId
of this.connectors
.keys()) {
1798 if (connectorId
=== 0) {
1802 !this.getConnectorStatus(connectorId
)?.status &&
1803 this.getConnectorStatus(connectorId
)?.bootStatus
1805 // Send status in template at startup
1806 await this.ocppRequestService
.requestHandler
<
1807 StatusNotificationRequest
,
1808 StatusNotificationResponse
1809 >(RequestCommand
.STATUS_NOTIFICATION
, {
1811 status: this.getConnectorStatus(connectorId
).bootStatus
,
1812 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1814 this.getConnectorStatus(connectorId
).status =
1815 this.getConnectorStatus(connectorId
).bootStatus
;
1818 this.getConnectorStatus(connectorId
)?.status &&
1819 this.getConnectorStatus(connectorId
)?.bootStatus
1821 // Send status in template after reset
1822 await this.ocppRequestService
.requestHandler
<
1823 StatusNotificationRequest
,
1824 StatusNotificationResponse
1825 >(RequestCommand
.STATUS_NOTIFICATION
, {
1827 status: this.getConnectorStatus(connectorId
).bootStatus
,
1828 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1830 this.getConnectorStatus(connectorId
).status =
1831 this.getConnectorStatus(connectorId
).bootStatus
;
1832 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1833 // Send previous status at template reload
1834 await this.ocppRequestService
.requestHandler
<
1835 StatusNotificationRequest
,
1836 StatusNotificationResponse
1837 >(RequestCommand
.STATUS_NOTIFICATION
, {
1839 status: this.getConnectorStatus(connectorId
).status,
1840 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1843 // Send default status
1844 await this.ocppRequestService
.requestHandler
<
1845 StatusNotificationRequest
,
1846 StatusNotificationResponse
1847 >(RequestCommand
.STATUS_NOTIFICATION
, {
1849 status: ChargePointStatus
.AVAILABLE
,
1850 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1852 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1856 this.startAutomaticTransactionGenerator();
1859 private startAutomaticTransactionGenerator() {
1860 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1861 if (!this.automaticTransactionGenerator
) {
1862 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1864 if (!this.automaticTransactionGenerator
.started
) {
1865 this.automaticTransactionGenerator
.start();
1870 private async stopMessageSequence(
1871 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1873 // Stop WebSocket ping
1874 this.stopWebSocketPing();
1876 this.stopHeartbeat();
1879 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1880 this.automaticTransactionGenerator
?.started
1882 this.automaticTransactionGenerator
.stop();
1884 for (const connectorId
of this.connectors
.keys()) {
1885 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1886 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1888 this.getBeginEndMeterValues() &&
1889 this.getOcppStrictCompliance() &&
1890 !this.getOutOfOrderEndMeterValues()
1892 // FIXME: Implement OCPP version agnostic helpers
1893 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1896 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1898 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1899 RequestCommand
.METER_VALUES
,
1903 meterValue
: transactionEndMeterValue
,
1907 await this.ocppRequestService
.requestHandler
<
1908 StopTransactionRequest
,
1909 StopTransactionResponse
1910 >(RequestCommand
.STOP_TRANSACTION
, {
1912 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1913 idTag
: this.getTransactionIdTag(transactionId
),
1921 private startWebSocketPing(): void {
1922 const webSocketPingInterval
: number = this.getConfigurationKey(
1923 StandardParametersKey
.WebSocketPingInterval
1925 ? Utils
.convertToInt(
1926 this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
1929 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1930 this.webSocketPingSetInterval
= setInterval(() => {
1931 if (this.isWebSocketConnectionOpened()) {
1932 this.wsConnection
.ping((): void => {
1933 /* This is intentional */
1936 }, webSocketPingInterval
* 1000);
1939 ' WebSocket ping started every ' +
1940 Utils
.formatDurationSeconds(webSocketPingInterval
)
1942 } else if (this.webSocketPingSetInterval
) {
1945 ' WebSocket ping every ' +
1946 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1951 `${this.logPrefix()} WebSocket ping interval set to ${
1952 webSocketPingInterval
1953 ? Utils.formatDurationSeconds(webSocketPingInterval)
1954 : webSocketPingInterval
1955 }, not starting the WebSocket ping`
1960 private stopWebSocketPing(): void {
1961 if (this.webSocketPingSetInterval
) {
1962 clearInterval(this.webSocketPingSetInterval
);
1966 private warnDeprecatedTemplateKey(
1967 template
: ChargingStationTemplate
,
1969 chargingStationId
: string,
1972 if (!Utils
.isUndefined(template
[key
])) {
1973 const logPrefixStr
= ` ${chargingStationId} |`;
1975 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1977 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1982 private convertDeprecatedTemplateKey(
1983 template
: ChargingStationTemplate
,
1984 deprecatedKey
: string,
1987 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
1988 template
[key
] = template
[deprecatedKey
] as unknown
;
1989 delete template
[deprecatedKey
];
1993 private getConfiguredSupervisionUrl(): URL
{
1994 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1995 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1997 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1999 switch (Configuration
.getSupervisionUrlDistribution()) {
2000 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2001 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2003 case SupervisionUrlDistribution
.RANDOM
:
2005 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
2007 case SupervisionUrlDistribution
.SEQUENTIAL
:
2008 if (this.index
<= supervisionUrls
.length
) {
2009 urlIndex
= this.index
- 1;
2012 `${this.logPrefix()} No more configured supervision urls available, using the first one`
2018 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2019 SupervisionUrlDistribution.ROUND_ROBIN
2022 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2025 return new URL(supervisionUrls
[urlIndex
]);
2027 return new URL(supervisionUrls
as string);
2030 private getHeartbeatInterval(): number | undefined {
2031 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
2032 if (HeartbeatInterval
) {
2033 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
2035 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
2036 if (HeartBeatInterval
) {
2037 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
2039 !this.stationInfo
.autoRegister
&&
2041 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
2042 Constants.DEFAULT_HEARTBEAT_INTERVAL
2045 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
2048 private stopHeartbeat(): void {
2049 if (this.heartbeatSetInterval
) {
2050 clearInterval(this.heartbeatSetInterval
);
2054 private openWSConnection(
2055 options
: WsOptions
= this.stationInfo
.wsOptions
,
2056 forceCloseOpened
= false
2058 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
2060 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
2061 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
2063 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
2065 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
2066 this.wsConnection
.close();
2068 let protocol
: string;
2069 switch (this.getOcppVersion()) {
2070 case OCPPVersion
.VERSION_16
:
2071 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
2074 this.handleUnsupportedVersion(this.getOcppVersion());
2077 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
2079 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
2083 private stopMeterValues(connectorId
: number) {
2084 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2085 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
2089 private getReconnectExponentialDelay(): boolean | undefined {
2090 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
2091 ? this.stationInfo
.reconnectExponentialDelay
2095 private async reconnect(code
: number): Promise
<void> {
2096 // Stop WebSocket ping
2097 this.stopWebSocketPing();
2099 this.stopHeartbeat();
2100 // Stop the ATG if needed
2102 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
2103 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
2104 this.automaticTransactionGenerator
?.started
2106 this.automaticTransactionGenerator
.stop();
2109 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2110 this.getAutoReconnectMaxRetries() === -1
2112 this.autoReconnectRetryCount
++;
2113 const reconnectDelay
= this.getReconnectExponentialDelay()
2114 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2115 : this.getConnectionTimeout() * 1000;
2116 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
2118 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2121 )}ms, timeout ${reconnectTimeout}ms`
2123 await Utils
.sleep(reconnectDelay
);
2126 ' WebSocket: reconnecting try #' +
2127 this.autoReconnectRetryCount
.toString()
2129 this.openWSConnection(
2130 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
2133 this.wsConnectionRestarted
= true;
2134 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2136 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2137 this.autoReconnectRetryCount
2138 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2143 private initializeConnectorStatus(connectorId
: number): void {
2144 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2145 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2146 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2147 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2148 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2149 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;