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
,
20 StatusNotificationResponse
,
21 } from
'../types/ocpp/Responses';
25 ChargingSchedulePeriod
,
26 } from
'../types/ocpp/ChargingProfile';
27 import ChargingStationConfiguration
, { Section
} from
'../types/ChargingStationConfiguration';
28 import ChargingStationOcppConfiguration
, {
30 } from
'../types/ChargingStationOcppConfiguration';
31 import ChargingStationTemplate
, {
37 } from
'../types/ChargingStationTemplate';
39 ConnectorPhaseRotation
,
40 StandardParametersKey
,
41 SupportedFeatureProfiles
,
42 VendorDefaultParametersKey
,
43 } from
'../types/ocpp/Configuration';
44 import { MeterValue
, MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
46 StopTransactionReason
,
47 StopTransactionRequest
,
48 StopTransactionResponse
,
49 } from
'../types/ocpp/Transaction';
50 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
51 import WebSocket
, { Data
, OPEN
, RawData
} from
'ws';
53 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
54 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
55 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
56 import ChargingStationInfo from
'../types/ChargingStationInfo';
57 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
58 import Configuration from
'../utils/Configuration';
59 import { ConnectorStatus
} from
'../types/ConnectorStatus';
60 import Constants from
'../utils/Constants';
61 import { ErrorType
} from
'../types/ocpp/ErrorType';
62 import { FileType
} from
'../types/FileType';
63 import FileUtils from
'../utils/FileUtils';
64 import { JsonType
} from
'../types/JsonType';
65 import { MessageType
} from
'../types/ocpp/MessageType';
66 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
67 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
68 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
69 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
70 import OCPPError from
'../exception/OCPPError';
71 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
72 import OCPPRequestService from
'./ocpp/OCPPRequestService';
73 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
74 import PerformanceStatistics from
'../performance/PerformanceStatistics';
75 import { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
76 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
77 import { URL
} from
'url';
78 import Utils from
'../utils/Utils';
79 import crypto from
'crypto';
81 import logger from
'../utils/Logger';
82 import { parentPort
} from
'worker_threads';
83 import path from
'path';
85 export default class ChargingStation
{
86 public hashId
!: string;
87 public readonly templateFile
: string;
88 public authorizedTags
: string[];
89 public stationInfo
!: ChargingStationInfo
;
90 public readonly connectors
: Map
<number, ConnectorStatus
>;
91 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
92 public wsConnection
!: WebSocket
;
93 public readonly requests
: Map
<string, CachedRequest
>;
94 public performanceStatistics
!: PerformanceStatistics
;
95 public heartbeatSetInterval
!: NodeJS
.Timeout
;
96 public ocppRequestService
!: OCPPRequestService
;
97 public bootNotificationResponse
!: BootNotificationResponse
| null;
98 private readonly index
: number;
99 private configurationFile
!: string;
100 private bootNotificationRequest
!: BootNotificationRequest
;
101 private connectorsConfigurationHash
!: string;
102 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
103 private readonly messageBuffer
: Set
<string>;
104 private wsConfiguredConnectionUrl
!: URL
;
105 private wsConnectionRestarted
: boolean;
106 private stopped
: boolean;
107 private autoReconnectRetryCount
: number;
108 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
109 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
111 constructor(index
: number, templateFile
: string) {
113 this.templateFile
= templateFile
;
114 this.stopped
= false;
115 this.wsConnectionRestarted
= false;
116 this.autoReconnectRetryCount
= 0;
117 this.connectors
= new Map
<number, ConnectorStatus
>();
118 this.requests
= new Map
<string, CachedRequest
>();
119 this.messageBuffer
= new Set
<string>();
121 this.authorizedTags
= this.getAuthorizedTags();
124 private get
wsConnectionUrl(): URL
{
125 return this.getSupervisionUrlOcppConfiguration()
127 this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value
+
129 this.stationInfo
.chargingStationId
131 : this.wsConfiguredConnectionUrl
;
134 public logPrefix(): string {
135 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
138 public getBootNotificationRequest(): BootNotificationRequest
{
139 return this.bootNotificationRequest
;
142 public getRandomIdTag(): string {
143 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
144 return this.authorizedTags
[index
];
147 public hasAuthorizedTags(): boolean {
148 return !Utils
.isEmptyArray(this.authorizedTags
);
151 public getEnableStatistics(): boolean | undefined {
152 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
153 ? this.stationInfo
.enableStatistics
157 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
158 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
161 public getNumberOfPhases(): number | undefined {
162 switch (this.getCurrentOutType()) {
164 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
)
165 ? this.stationInfo
.numberOfPhases
172 public isWebSocketConnectionOpened(): boolean {
173 return this?.wsConnection
?.readyState
=== OPEN
;
176 public getRegistrationStatus(): RegistrationStatus
{
177 return this?.bootNotificationResponse
?.status;
180 public isInUnknownState(): boolean {
181 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
184 public isInPendingState(): boolean {
185 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
188 public isInAcceptedState(): boolean {
189 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
192 public isInRejectedState(): boolean {
193 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
196 public isRegistered(): boolean {
197 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
200 public isChargingStationAvailable(): boolean {
201 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
204 public isConnectorAvailable(id
: number): boolean {
205 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
208 public getNumberOfConnectors(): number {
209 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
212 public getConnectorStatus(id
: number): ConnectorStatus
{
213 return this.connectors
.get(id
);
216 public getCurrentOutType(): CurrentType
| undefined {
217 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
220 public getOcppStrictCompliance(): boolean {
221 return this.stationInfo
.ocppStrictCompliance
?? false;
224 public getVoltageOut(): number | undefined {
225 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
227 }, cannot define default voltage out`;
228 let defaultVoltageOut
: number;
229 switch (this.getCurrentOutType()) {
231 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
234 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
237 logger
.error(errMsg
);
238 throw new Error(errMsg
);
240 return !Utils
.isUndefined(this.stationInfo
.voltageOut
)
241 ? this.stationInfo
.voltageOut
245 public getConnectorMaximumAvailablePower(connectorId
: number): number {
246 let connectorAmperageLimitationPowerLimit
: number;
248 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
249 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
251 connectorAmperageLimitationPowerLimit
=
252 (this.getCurrentOutType() === CurrentType
.AC
253 ? ACElectricUtils
.powerTotal(
254 this.getNumberOfPhases(),
255 this.getVoltageOut(),
256 this.getAmperageLimitation() * this.getNumberOfConnectors()
258 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
259 this.stationInfo
.powerDivider
;
261 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
262 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
264 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
265 isNaN(connectorAmperageLimitationPowerLimit
)
267 : connectorAmperageLimitationPowerLimit
,
268 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
272 public getTransactionIdTag(transactionId
: number): string | undefined {
273 for (const connectorId
of this.connectors
.keys()) {
274 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
275 return this.getConnectorStatus(connectorId
).transactionIdTag
;
280 public getOutOfOrderEndMeterValues(): boolean {
281 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
284 public getBeginEndMeterValues(): boolean {
285 return this.stationInfo
.beginEndMeterValues
?? false;
288 public getMeteringPerTransaction(): boolean {
289 return this.stationInfo
.meteringPerTransaction
?? true;
292 public getTransactionDataMeterValues(): boolean {
293 return this.stationInfo
.transactionDataMeterValues
?? false;
296 public getMainVoltageMeterValues(): boolean {
297 return this.stationInfo
.mainVoltageMeterValues
?? true;
300 public getPhaseLineToLineVoltageMeterValues(): boolean {
301 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
304 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
305 for (const connectorId
of this.connectors
.keys()) {
308 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
315 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
316 const transactionConnectorStatus
= this.getConnectorStatus(
317 this.getConnectorIdByTransactionId(transactionId
)
319 if (this.getMeteringPerTransaction()) {
320 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
322 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
325 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
326 const connectorStatus
= this.getConnectorStatus(connectorId
);
327 if (this.getMeteringPerTransaction()) {
328 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
330 return connectorStatus
?.energyActiveImportRegisterValue
;
333 public getAuthorizeRemoteTxRequests(): boolean {
334 const authorizeRemoteTxRequests
= this.getConfigurationKey(
335 StandardParametersKey
.AuthorizeRemoteTxRequests
337 return authorizeRemoteTxRequests
338 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
342 public getLocalAuthListEnabled(): boolean {
343 const localAuthListEnabled
= this.getConfigurationKey(
344 StandardParametersKey
.LocalAuthListEnabled
346 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
349 public restartWebSocketPing(): void {
350 // Stop WebSocket ping
351 this.stopWebSocketPing();
352 // Start WebSocket ping
353 this.startWebSocketPing();
356 public getSampledValueTemplate(
358 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
359 phase
?: MeterValuePhase
360 ): SampledValueTemplate
| undefined {
361 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
362 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
364 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
369 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
370 !this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
375 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
376 StandardParametersKey.MeterValuesSampledData
381 const sampledValueTemplates
: SampledValueTemplate
[] =
382 this.getConnectorStatus(connectorId
).MeterValues
;
385 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
389 !Constants
.SUPPORTED_MEASURANDS
.includes(
390 sampledValueTemplates
[index
]?.measurand
??
391 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
395 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
399 sampledValueTemplates
[index
]?.phase
=== phase
&&
400 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
401 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
405 return sampledValueTemplates
[index
];
408 !sampledValueTemplates
[index
].phase
&&
409 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
410 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
414 return sampledValueTemplates
[index
];
416 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
417 (!sampledValueTemplates
[index
].measurand
||
418 sampledValueTemplates
[index
].measurand
=== measurand
)
420 return sampledValueTemplates
[index
];
423 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
424 const errorMsg
= `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
425 logger
.error(errorMsg
);
426 throw new Error(errorMsg
);
429 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
433 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
434 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
437 public startHeartbeat(): void {
439 this.getHeartbeatInterval() &&
440 this.getHeartbeatInterval() > 0 &&
441 !this.heartbeatSetInterval
443 // eslint-disable-next-line @typescript-eslint/no-misused-promises
444 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
445 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
446 RequestCommand
.HEARTBEAT
448 }, this.getHeartbeatInterval());
451 ' Heartbeat started every ' +
452 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
454 } else if (this.heartbeatSetInterval
) {
457 ' Heartbeat already started every ' +
458 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
462 `${this.logPrefix()} Heartbeat interval set to ${
463 this.getHeartbeatInterval()
464 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
465 : this.getHeartbeatInterval()
466 }, not starting the heartbeat`
471 public restartHeartbeat(): void {
473 this.stopHeartbeat();
475 this.startHeartbeat();
478 public startMeterValues(connectorId
: number, interval
: number): void {
479 if (connectorId
=== 0) {
481 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
485 if (!this.getConnectorStatus(connectorId
)) {
487 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
491 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
493 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
497 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
498 !this.getConnectorStatus(connectorId
)?.transactionId
501 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
506 // eslint-disable-next-line @typescript-eslint/no-misused-promises
507 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
508 // eslint-disable-next-line @typescript-eslint/no-misused-promises
509 async (): Promise
<void> => {
510 // FIXME: Implement OCPP version agnostic helpers
511 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
514 this.getConnectorStatus(connectorId
).transactionId
,
517 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
518 RequestCommand
.METER_VALUES
,
521 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
522 meterValue
: [meterValue
],
530 `${this.logPrefix()} Charging station ${
531 StandardParametersKey.MeterValueSampleInterval
532 } configuration set to ${
533 interval ? Utils.formatDurationMilliSeconds(interval) : interval
534 }, not sending MeterValues`
539 public start(): void {
540 if (this.getEnableStatistics()) {
541 this.performanceStatistics
.start();
543 this.openWSConnection();
544 // Handle WebSocket message
545 this.wsConnection
.on(
547 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
549 // Handle WebSocket error
550 this.wsConnection
.on(
552 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
554 // Handle WebSocket close
555 this.wsConnection
.on(
557 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
559 // Handle WebSocket open
560 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
561 // Handle WebSocket ping
562 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
563 // Handle WebSocket pong
564 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
565 // Monitor authorization file
566 FileUtils
.watchJsonFile
<string[]>(
568 FileType
.Authorization
,
569 this.getAuthorizationFile(),
572 // Monitor charging station template file
573 FileUtils
.watchJsonFile(
575 FileType
.ChargingStationTemplate
,
578 (event
, filename
): void => {
579 if (filename
&& event
=== 'change') {
582 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
584 } file have changed, reload`
590 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
591 this.automaticTransactionGenerator
593 this.automaticTransactionGenerator
.stop();
595 this.startAutomaticTransactionGenerator();
596 if (this.getEnableStatistics()) {
597 this.performanceStatistics
.restart();
599 this.performanceStatistics
.stop();
601 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
604 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
611 parentPort
.postMessage({
612 id
: ChargingStationWorkerMessageEvents
.STARTED
,
613 data
: { id
: this.stationInfo
.chargingStationId
},
617 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
618 // Stop message sequence
619 await this.stopMessageSequence(reason
);
620 for (const connectorId
of this.connectors
.keys()) {
621 if (connectorId
> 0) {
622 await this.ocppRequestService
.requestHandler
<
623 StatusNotificationRequest
,
624 StatusNotificationResponse
625 >(RequestCommand
.STATUS_NOTIFICATION
, {
627 status: ChargePointStatus
.UNAVAILABLE
,
628 errorCode
: ChargePointErrorCode
.NO_ERROR
,
630 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
633 if (this.isWebSocketConnectionOpened()) {
634 this.wsConnection
.close();
636 if (this.getEnableStatistics()) {
637 this.performanceStatistics
.stop();
639 this.bootNotificationResponse
= null;
640 parentPort
.postMessage({
641 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
642 data
: { id
: this.stationInfo
.chargingStationId
},
647 public getConfigurationKey(
648 key
: string | StandardParametersKey
,
649 caseInsensitive
= false
650 ): ConfigurationKey
| undefined {
651 return this.ocppConfiguration
.configurationKey
.find((configElement
) => {
652 if (caseInsensitive
) {
653 return configElement
.key
.toLowerCase() === key
.toLowerCase();
655 return configElement
.key
=== key
;
659 public addConfigurationKey(
660 key
: string | StandardParametersKey
,
662 options
: { readonly?: boolean; visible
?: boolean; reboot
?: boolean } = {
667 params
: { overwrite
?: boolean; save
?: boolean } = { overwrite
: false, save
: false }
669 options
= options
?? ({} as { readonly?: boolean; visible
?: boolean; reboot
?: boolean });
670 options
.readonly = options
?.readonly ?? false;
671 options
.visible
= options
?.visible
?? true;
672 options
.reboot
= options
?.reboot
?? false;
673 let keyFound
= this.getConfigurationKey(key
);
674 if (keyFound
&& params
?.overwrite
) {
675 this.deleteConfigurationKey(keyFound
.key
, { save
: false });
676 keyFound
= undefined;
679 this.ocppConfiguration
.configurationKey
.push({
681 readonly: options
.readonly,
683 visible
: options
.visible
,
684 reboot
: options
.reboot
,
686 params
?.save
&& this.saveOcppConfiguration();
689 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
695 public setConfigurationKeyValue(
696 key
: string | StandardParametersKey
,
698 caseInsensitive
= false
700 const keyFound
= this.getConfigurationKey(key
, caseInsensitive
);
702 this.ocppConfiguration
.configurationKey
[
703 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
)
705 this.saveOcppConfiguration();
708 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
714 public deleteConfigurationKey(
715 key
: string | StandardParametersKey
,
716 params
: { save
?: boolean; caseInsensitive
?: boolean } = { save
: true, caseInsensitive
: false }
717 ): ConfigurationKey
[] {
718 const keyFound
= this.getConfigurationKey(key
, params
?.caseInsensitive
);
720 const deletedConfigurationKey
= this.ocppConfiguration
.configurationKey
.splice(
721 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
),
724 params
?.save
&& this.saveOcppConfiguration();
725 return deletedConfigurationKey
;
729 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
730 const timestamp
= new Date().getTime();
731 let matchingChargingProfile
: ChargingProfile
;
732 let chargingSchedulePeriods
: ChargingSchedulePeriod
[] = [];
733 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
)?.chargingProfiles
)) {
734 const chargingProfiles
: ChargingProfile
[] = this.getConnectorStatus(
736 ).chargingProfiles
.filter(
738 timestamp
>= chargingProfile
.chargingSchedule
?.startSchedule
.getTime() &&
740 chargingProfile
.chargingSchedule
?.startSchedule
.getTime() +
741 chargingProfile
.chargingSchedule
.duration
* 1000 &&
742 chargingProfile
?.stackLevel
=== Math.max(...chargingProfiles
.map((cp
) => cp
?.stackLevel
))
744 if (!Utils
.isEmptyArray(chargingProfiles
)) {
745 for (const chargingProfile
of chargingProfiles
) {
746 if (!Utils
.isEmptyArray(chargingProfile
.chargingSchedule
.chargingSchedulePeriod
)) {
747 chargingSchedulePeriods
=
748 chargingProfile
.chargingSchedule
.chargingSchedulePeriod
.filter(
749 (chargingSchedulePeriod
, index
) => {
751 chargingProfile
.chargingSchedule
.startSchedule
.getTime() +
752 chargingSchedulePeriod
.startPeriod
* 1000 &&
753 ((chargingProfile
.chargingSchedule
.chargingSchedulePeriod
[index
+ 1] &&
755 chargingProfile
.chargingSchedule
.startSchedule
.getTime() +
756 chargingProfile
.chargingSchedule
.chargingSchedulePeriod
[index
+ 1]
759 !chargingProfile
.chargingSchedule
.chargingSchedulePeriod
[index
+ 1]);
762 if (!Utils
.isEmptyArray(chargingSchedulePeriods
)) {
763 matchingChargingProfile
= chargingProfile
;
771 if (!Utils
.isEmptyArray(chargingSchedulePeriods
)) {
772 switch (this.getCurrentOutType()) {
775 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
=== ChargingRateUnitType
.WATT
776 ? chargingSchedulePeriods
[0].limit
777 : ACElectricUtils
.powerTotal(
778 this.getNumberOfPhases(),
779 this.getVoltageOut(),
780 chargingSchedulePeriods
[0].limit
785 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
=== ChargingRateUnitType
.WATT
786 ? chargingSchedulePeriods
[0].limit
787 : DCElectricUtils
.power(this.getVoltageOut(), chargingSchedulePeriods
[0].limit
);
790 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
791 if (limit
> connectorMaximumPower
) {
793 `${this.logPrefix()} Charging profile id ${
794 matchingChargingProfile.chargingProfileId
795 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
796 this.getConnectorStatus(connectorId
).chargingProfiles
798 limit
= connectorMaximumPower
;
803 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
804 let cpReplaced
= false;
805 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
806 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
807 (chargingProfile
: ChargingProfile
, index
: number) => {
809 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
810 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
811 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
813 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
819 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
822 public resetConnectorStatus(connectorId
: number): void {
823 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
824 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
825 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
826 this.getConnectorStatus(connectorId
).transactionStarted
= false;
827 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
828 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
829 delete this.getConnectorStatus(connectorId
).transactionId
;
830 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
831 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
832 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
833 this.stopMeterValues(connectorId
);
836 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
837 return this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)?.value
.includes(
842 public bufferMessage(message
: string): void {
843 this.messageBuffer
.add(message
);
846 private flushMessageBuffer() {
847 if (this.messageBuffer
.size
> 0) {
848 this.messageBuffer
.forEach((message
) => {
849 // TODO: evaluate the need to track performance
850 this.wsConnection
.send(message
);
851 this.messageBuffer
.delete(message
);
856 private getSupervisionUrlOcppConfiguration(): boolean {
857 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
860 private getSupervisionUrlOcppKey(): string {
861 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
864 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
865 // In case of multiple instances: add instance index to charging station id
866 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
867 const idSuffix
= stationTemplate
.nameSuffix
?? '';
868 const idStr
= '000000000' + this.index
.toString();
869 return stationTemplate
.fixedName
870 ? stationTemplate
.baseName
871 : stationTemplate
.baseName
+
873 instanceIndex
.toString() +
874 idStr
.substring(idStr
.length
- 4) +
878 private getRandomSerialNumberSuffix(params
?: {
879 randomBytesLength
?: number;
882 const randomSerialNumberSuffix
= crypto
883 .randomBytes(params
?.randomBytesLength
?? 16)
885 if (params
?.upperCase
) {
886 return randomSerialNumberSuffix
.toUpperCase();
888 return randomSerialNumberSuffix
;
891 private getTemplateFromFile(): ChargingStationTemplate
| null {
892 let template
: ChargingStationTemplate
= null;
894 const measureId
= `${FileType.ChargingStationTemplate} read`;
895 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
896 template
= JSON
.parse(fs
.readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
897 PerformanceStatistics
.endMeasure(measureId
, beginId
);
899 FileUtils
.handleFileException(
901 FileType
.ChargingStationTemplate
,
903 error
as NodeJS
.ErrnoException
909 private createSerialNumber(
910 stationInfo
: ChargingStationInfo
,
911 existingStationInfo
?: ChargingStationInfo
,
912 params
: { randomSerialNumberUpperCase
?: boolean; randomSerialNumber
?: boolean } = {
913 randomSerialNumberUpperCase
: true,
914 randomSerialNumber
: true,
917 params
= params
?? {};
918 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
919 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
920 if (existingStationInfo
) {
921 existingStationInfo
?.chargePointSerialNumber
&&
922 (stationInfo
.chargePointSerialNumber
= existingStationInfo
.chargePointSerialNumber
);
923 existingStationInfo
?.chargeBoxSerialNumber
&&
924 (stationInfo
.chargeBoxSerialNumber
= existingStationInfo
.chargeBoxSerialNumber
);
925 existingStationInfo
?.meterSerialNumber
&&
926 (stationInfo
.meterSerialNumber
= existingStationInfo
.meterSerialNumber
);
928 const serialNumberSuffix
= params
?.randomSerialNumber
929 ? this.getRandomSerialNumberSuffix({ upperCase
: params
.randomSerialNumberUpperCase
})
931 stationInfo
.chargePointSerialNumber
=
932 stationInfo
?.chargePointSerialNumberPrefix
&&
933 stationInfo
.chargePointSerialNumberPrefix
+ serialNumberSuffix
;
934 stationInfo
.chargeBoxSerialNumber
=
935 stationInfo
?.chargeBoxSerialNumberPrefix
&&
936 stationInfo
.chargeBoxSerialNumberPrefix
+ serialNumberSuffix
;
937 stationInfo
.meterSerialNumber
=
938 stationInfo
?.meterSerialNumberPrefix
&&
939 stationInfo
.meterSerialNumberPrefix
+ serialNumberSuffix
;
943 private getStationInfoFromTemplate(): ChargingStationInfo
{
944 const stationInfo
: ChargingStationInfo
=
945 this.getTemplateFromFile() ?? ({} as ChargingStationInfo
);
946 stationInfo
.hash
= crypto
947 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
948 .update(JSON
.stringify(stationInfo
))
950 const chargingStationId
= this.getChargingStationId(stationInfo
);
951 // Deprecation template keys section
952 this.warnDeprecatedTemplateKey(
956 "Use 'supervisionUrls' instead"
958 this.convertDeprecatedTemplateKey(stationInfo
, 'supervisionUrl', 'supervisionUrls');
959 stationInfo
.wsOptions
= stationInfo
?.wsOptions
?? {};
960 if (!Utils
.isEmptyArray(stationInfo
.power
)) {
961 stationInfo
.power
= stationInfo
.power
as number[];
962 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationInfo
.power
.length
);
963 stationInfo
.maximumPower
=
964 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
965 ? stationInfo
.power
[powerArrayRandomIndex
] * 1000
966 : stationInfo
.power
[powerArrayRandomIndex
];
968 stationInfo
.power
= stationInfo
.power
as number;
969 stationInfo
.maximumPower
=
970 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
971 ? stationInfo
.power
* 1000
974 delete stationInfo
.power
;
975 delete stationInfo
.powerUnit
;
976 stationInfo
.chargingStationId
= chargingStationId
;
977 stationInfo
.resetTime
= stationInfo
.resetTime
978 ? stationInfo
.resetTime
* 1000
979 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
983 private getStationInfoFromFile(): ChargingStationInfo
| null {
984 return this.getConfigurationFromFile()?.stationInfo
?? null;
987 private getStationInfo(): ChargingStationInfo
{
988 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
989 this.hashId
= this.getHashId(stationInfoFromTemplate
);
990 this.configurationFile
= path
.join(
991 path
.resolve(__dirname
, '../'),
994 this.hashId
+ '.json'
996 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
997 if (stationInfoFromFile
?.hash
=== stationInfoFromTemplate
.hash
) {
998 return stationInfoFromFile
;
1000 this.createSerialNumber(stationInfoFromTemplate
, stationInfoFromFile
);
1001 return stationInfoFromTemplate
;
1004 private saveStationInfo(): void {
1005 this.saveConfiguration(Section
.stationInfo
);
1008 private getOcppVersion(): OCPPVersion
{
1009 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
1012 private getOcppPersistentConfiguration(): boolean {
1013 return this.stationInfo
.ocppPersistentConfiguration
?? true;
1016 private handleUnsupportedVersion(version
: OCPPVersion
) {
1017 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
1020 logger
.error(errMsg
);
1021 throw new Error(errMsg
);
1024 private createBootNotificationRequest(stationInfo
: ChargingStationInfo
): BootNotificationRequest
{
1026 chargePointModel
: stationInfo
.chargePointModel
,
1027 chargePointVendor
: stationInfo
.chargePointVendor
,
1028 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
1029 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
1031 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
1032 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
1034 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
1035 firmwareVersion
: stationInfo
.firmwareVersion
,
1037 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
1038 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
1039 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
1040 meterSerialNumber
: stationInfo
.meterSerialNumber
,
1042 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
1043 meterType
: stationInfo
.meterType
,
1048 private getHashId(stationInfo
: ChargingStationInfo
): string {
1049 const hashBootNotificationRequest
= {
1050 chargePointModel
: stationInfo
.chargePointModel
,
1051 chargePointVendor
: stationInfo
.chargePointVendor
,
1052 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumberPrefix
) && {
1053 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumberPrefix
,
1055 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumberPrefix
) && {
1056 chargePointSerialNumber
: stationInfo
.chargePointSerialNumberPrefix
,
1058 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
1059 firmwareVersion
: stationInfo
.firmwareVersion
,
1061 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
1062 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
1063 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumberPrefix
) && {
1064 meterSerialNumber
: stationInfo
.meterSerialNumberPrefix
,
1066 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
1067 meterType
: stationInfo
.meterType
,
1071 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1072 .update(JSON
.stringify(hashBootNotificationRequest
) + stationInfo
.chargingStationId
)
1076 private initialize(): void {
1077 this.stationInfo
= this.getStationInfo();
1078 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
1079 this.bootNotificationRequest
= this.createBootNotificationRequest(this.stationInfo
);
1080 this.ocppConfiguration
= this.getOcppConfiguration();
1081 delete this.stationInfo
.Configuration
;
1082 this.wsConfiguredConnectionUrl
= new URL(
1083 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
1085 // Build connectors if needed
1086 const maxConnectors
= this.getMaxNumberOfConnectors();
1087 if (maxConnectors
<= 0) {
1089 `${this.logPrefix()} Charging station template ${
1091 } with ${maxConnectors} connectors`
1094 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
1095 if (templateMaxConnectors
<= 0) {
1097 `${this.logPrefix()} Charging station template ${
1099 } with no connector configuration`
1102 if (!this.stationInfo
.Connectors
[0]) {
1104 `${this.logPrefix()} Charging station template ${
1106 } with no connector Id 0 configuration`
1112 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
1113 !this.stationInfo
.randomConnectors
1116 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
1118 }, forcing random connector configurations affectation`
1120 this.stationInfo
.randomConnectors
= true;
1122 const connectorsConfigHash
= crypto
1123 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1124 .update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString())
1126 const connectorsConfigChanged
=
1127 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1128 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1129 connectorsConfigChanged
&& this.connectors
.clear();
1130 this.connectorsConfigurationHash
= connectorsConfigHash
;
1131 // Add connector Id 0
1132 let lastConnector
= '0';
1133 for (lastConnector
in this.stationInfo
.Connectors
) {
1134 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1136 lastConnectorId
=== 0 &&
1137 this.getUseConnectorId0() &&
1138 this.stationInfo
.Connectors
[lastConnector
]
1140 this.connectors
.set(
1142 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
])
1144 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1145 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1146 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1150 // Generate all connectors
1152 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0
1154 for (let index
= 1; index
<= maxConnectors
; index
++) {
1155 const randConnectorId
= this.stationInfo
.randomConnectors
1156 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1158 this.connectors
.set(
1160 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
])
1162 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1163 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1164 this.getConnectorStatus(index
).chargingProfiles
= [];
1169 this.stationInfo
.maximumAmperage
= this.getMaximumAmperage();
1170 this.saveStationInfo();
1171 // Avoid duplication of connectors related information in RAM
1172 delete this.stationInfo
.Connectors
;
1173 // Initialize transaction attributes on connectors
1174 for (const connectorId
of this.connectors
.keys()) {
1175 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1176 this.initializeConnectorStatus(connectorId
);
1179 // OCPP configuration
1180 this.initializeOcppConfiguration();
1181 if (this.getEnableStatistics()) {
1182 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1184 this.stationInfo
.chargingStationId
,
1185 this.wsConnectionUrl
1188 switch (this.getOcppVersion()) {
1189 case OCPPVersion
.VERSION_16
:
1190 this.ocppIncomingRequestService
=
1191 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>(this);
1192 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1194 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(this)
1198 this.handleUnsupportedVersion(this.getOcppVersion());
1201 if (this.stationInfo
.autoRegister
) {
1202 this.bootNotificationResponse
= {
1203 currentTime
: new Date().toISOString(),
1204 interval
: this.getHeartbeatInterval() / 1000,
1205 status: RegistrationStatus
.ACCEPTED
,
1208 this.stationInfo
.powerDivider
= this.getPowerDivider();
1211 private initializeOcppConfiguration(): void {
1213 this.getSupervisionUrlOcppConfiguration() &&
1214 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1216 this.addConfigurationKey(
1217 this.getSupervisionUrlOcppKey(),
1218 this.getConfiguredSupervisionUrl().href
,
1222 !this.getSupervisionUrlOcppConfiguration() &&
1223 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1225 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save
: false });
1228 this.stationInfo
.amperageLimitationOcppKey
&&
1229 !this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1231 this.addConfigurationKey(
1232 this.stationInfo
.amperageLimitationOcppKey
,
1233 (this.stationInfo
.maximumAmperage
* this.getAmperageLimitationUnitDivider()).toString()
1236 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
1237 this.addConfigurationKey(
1238 StandardParametersKey
.SupportedFeatureProfiles
,
1239 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1242 this.addConfigurationKey(
1243 StandardParametersKey
.NumberOfConnectors
,
1244 this.getNumberOfConnectors().toString(),
1248 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
1249 this.addConfigurationKey(
1250 StandardParametersKey
.MeterValuesSampledData
,
1251 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1254 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
1255 const connectorPhaseRotation
= [];
1256 for (const connectorId
of this.connectors
.keys()) {
1258 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1259 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1260 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1261 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1263 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1264 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1265 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1266 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1269 this.addConfigurationKey(
1270 StandardParametersKey
.ConnectorPhaseRotation
,
1271 connectorPhaseRotation
.toString()
1274 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
1275 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1278 !this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
) &&
1279 this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)?.value
.includes(
1280 SupportedFeatureProfiles
.LocalAuthListManagement
1283 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
1285 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1286 this.addConfigurationKey(
1287 StandardParametersKey
.ConnectionTimeOut
,
1288 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1291 this.saveOcppConfiguration();
1294 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1295 let configuration
: ChargingStationConfiguration
= null;
1296 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1298 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1299 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1300 configuration
= JSON
.parse(
1301 fs
.readFileSync(this.configurationFile
, 'utf8')
1302 ) as ChargingStationConfiguration
;
1303 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1305 FileUtils
.handleFileException(
1307 FileType
.ChargingStationConfiguration
,
1308 this.configurationFile
,
1309 error
as NodeJS
.ErrnoException
1313 return configuration
;
1316 private saveConfiguration(section
?: Section
): void {
1317 if (this.configurationFile
) {
1319 const configurationData
: ChargingStationConfiguration
=
1320 this.getConfigurationFromFile() ?? {};
1321 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1322 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1325 case Section
.ocppConfiguration
:
1326 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1328 case Section
.stationInfo
:
1329 configurationData
.stationInfo
= this.stationInfo
;
1332 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1333 configurationData
.stationInfo
= this.stationInfo
;
1336 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1337 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1338 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1339 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1340 fs
.closeSync(fileDescriptor
);
1341 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1343 FileUtils
.handleFileException(
1345 FileType
.ChargingStationConfiguration
,
1346 this.configurationFile
,
1347 error
as NodeJS
.ErrnoException
1352 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
1357 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
{
1358 return this.getTemplateFromFile().Configuration
?? ({} as ChargingStationOcppConfiguration
);
1361 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1362 let configuration
: ChargingStationConfiguration
= null;
1363 if (this.getOcppPersistentConfiguration()) {
1364 const configurationFromFile
= this.getConfigurationFromFile();
1365 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1367 configuration
&& delete configuration
.stationInfo
;
1368 return configuration
;
1371 private getOcppConfiguration(): ChargingStationOcppConfiguration
{
1372 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1373 if (!ocppConfiguration
) {
1374 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1376 return ocppConfiguration
;
1379 private saveOcppConfiguration(): void {
1380 if (this.getOcppPersistentConfiguration()) {
1381 this.saveConfiguration(Section
.ocppConfiguration
);
1385 private async onOpen(): Promise
<void> {
1386 if (this.isWebSocketConnectionOpened()) {
1388 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1390 if (!this.isRegistered()) {
1391 // Send BootNotification
1392 let registrationRetryCount
= 0;
1394 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1395 BootNotificationRequest
,
1396 BootNotificationResponse
1398 RequestCommand
.BOOT_NOTIFICATION
,
1400 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1401 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1402 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1403 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1404 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1405 iccid
: this.bootNotificationRequest
.iccid
,
1406 imsi
: this.bootNotificationRequest
.imsi
,
1407 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1408 meterType
: this.bootNotificationRequest
.meterType
,
1410 { skipBufferingOnError
: true }
1412 if (!this.isRegistered()) {
1413 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1415 this.bootNotificationResponse
?.interval
1416 ? this.bootNotificationResponse
.interval
* 1000
1417 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1421 !this.isRegistered() &&
1422 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1423 this.getRegistrationMaxRetries() === -1)
1426 if (this.isRegistered()) {
1427 if (this.isInAcceptedState()) {
1428 await this.startMessageSequence();
1429 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1433 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1436 this.stopped
&& (this.stopped
= false);
1437 this.autoReconnectRetryCount
= 0;
1438 this.wsConnectionRestarted
= false;
1441 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1446 private async onClose(code
: number, reason
: string): Promise
<void> {
1449 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1450 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1452 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1454 )}' and reason '${reason}'`
1456 this.autoReconnectRetryCount
= 0;
1461 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1463 )}' and reason '${reason}'`
1465 await this.reconnect(code
);
1470 private async onMessage(data
: Data
): Promise
<void> {
1471 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [
1474 '' as IncomingRequestCommand
,
1478 let responseCallback
: (
1479 payload
: JsonType
| string,
1480 requestPayload
: JsonType
| OCPPError
1482 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1483 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1484 let requestPayload
: JsonType
| OCPPError
;
1485 let cachedRequest
: CachedRequest
;
1488 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
1489 if (Utils
.isIterable(request
)) {
1490 // Parse the message
1491 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
1493 throw new OCPPError(
1494 ErrorType
.PROTOCOL_ERROR
,
1495 'Incoming message is not iterable',
1496 Utils
.isString(commandName
) && commandName
,
1497 { payload
: request
}
1500 // Check the Type of message
1501 switch (messageType
) {
1503 case MessageType
.CALL_MESSAGE
:
1504 if (this.getEnableStatistics()) {
1505 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1508 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1513 await this.ocppIncomingRequestService
.incomingRequestHandler(
1520 case MessageType
.CALL_RESULT_MESSAGE
:
1522 cachedRequest
= this.requests
.get(messageId
);
1523 if (Utils
.isIterable(cachedRequest
)) {
1524 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1526 throw new OCPPError(
1527 ErrorType
.PROTOCOL_ERROR
,
1528 `Cached request for message id ${messageId} response is not iterable`,
1533 `${this.logPrefix()} << Command '${requestCommandName}' received response payload: ${JSON.stringify(
1537 if (!responseCallback
) {
1539 throw new OCPPError(
1540 ErrorType
.INTERNAL_ERROR
,
1541 `Response for unknown message id ${messageId}`,
1545 responseCallback(commandName
, requestPayload
);
1548 case MessageType
.CALL_ERROR_MESSAGE
:
1549 cachedRequest
= this.requests
.get(messageId
);
1550 if (Utils
.isIterable(cachedRequest
)) {
1551 [, rejectCallback
, requestCommandName
] = cachedRequest
;
1553 throw new OCPPError(
1554 ErrorType
.PROTOCOL_ERROR
,
1555 `Cached request for message id ${messageId} error response is not iterable`
1559 `${this.logPrefix()} << Command '${requestCommandName}' received error payload: ${JSON.stringify(
1563 if (!rejectCallback
) {
1565 throw new OCPPError(
1566 ErrorType
.INTERNAL_ERROR
,
1567 `Error response for unknown message id ${messageId}`,
1572 new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
)
1577 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1578 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1579 logger
.error(errMsg
);
1580 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1585 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1588 this.requests
.get(messageId
),
1592 messageType
=== MessageType
.CALL_MESSAGE
&&
1593 (await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
));
1597 private onPing(): void {
1598 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1601 private onPong(): void {
1602 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1605 private onError(error
: WSError
): void {
1606 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1609 private getAuthorizationFile(): string | undefined {
1611 this.stationInfo
.authorizationFile
&&
1613 path
.resolve(__dirname
, '../'),
1615 path
.basename(this.stationInfo
.authorizationFile
)
1620 private getAuthorizedTags(): string[] {
1621 let authorizedTags
: string[] = [];
1622 const authorizationFile
= this.getAuthorizationFile();
1623 if (authorizationFile
) {
1625 // Load authorization file
1626 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
1628 FileUtils
.handleFileException(
1630 FileType
.Authorization
,
1632 error
as NodeJS
.ErrnoException
1637 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1640 return authorizedTags
;
1643 private getUseConnectorId0(): boolean | undefined {
1644 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1645 ? this.stationInfo
.useConnectorId0
1649 private getNumberOfRunningTransactions(): number {
1651 for (const connectorId
of this.connectors
.keys()) {
1652 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1660 private getConnectionTimeout(): number | undefined {
1661 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1663 parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ??
1664 Constants
.DEFAULT_CONNECTION_TIMEOUT
1667 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1670 // -1 for unlimited, 0 for disabling
1671 private getAutoReconnectMaxRetries(): number | undefined {
1672 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1673 return this.stationInfo
.autoReconnectMaxRetries
;
1675 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1676 return Configuration
.getAutoReconnectMaxRetries();
1682 private getRegistrationMaxRetries(): number | undefined {
1683 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1684 return this.stationInfo
.registrationMaxRetries
;
1689 private getPowerDivider(): number {
1690 let powerDivider
= this.getNumberOfConnectors();
1691 if (this.stationInfo
.powerSharedByConnectors
) {
1692 powerDivider
= this.getNumberOfRunningTransactions();
1694 return powerDivider
;
1697 private getTemplateMaxNumberOfConnectors(): number {
1698 return Object.keys(this.stationInfo
.Connectors
).length
;
1701 private getMaxNumberOfConnectors(): number {
1702 let maxConnectors
: number;
1703 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1704 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1705 // Distribute evenly the number of connectors
1706 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1707 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1708 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1710 maxConnectors
= this.stationInfo
.Connectors
[0]
1711 ? this.getTemplateMaxNumberOfConnectors() - 1
1712 : this.getTemplateMaxNumberOfConnectors();
1714 return maxConnectors
;
1717 private getMaximumPower(): number {
1718 return (this.stationInfo
['maxPower'] as number) ?? this.stationInfo
.maximumPower
;
1721 private getMaximumAmperage(): number | undefined {
1722 const maximumPower
= this.getMaximumPower();
1723 switch (this.getCurrentOutType()) {
1724 case CurrentType
.AC
:
1725 return ACElectricUtils
.amperagePerPhaseFromPower(
1726 this.getNumberOfPhases(),
1727 maximumPower
/ this.getNumberOfConnectors(),
1728 this.getVoltageOut()
1730 case CurrentType
.DC
:
1731 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut());
1735 private getAmperageLimitationUnitDivider(): number {
1736 let unitDivider
= 1;
1737 switch (this.stationInfo
.amperageLimitationUnit
) {
1738 case AmpereUnits
.DECI_AMPERE
:
1741 case AmpereUnits
.CENTI_AMPERE
:
1744 case AmpereUnits
.MILLI_AMPERE
:
1751 private getAmperageLimitation(): number | undefined {
1753 this.stationInfo
.amperageLimitationOcppKey
&&
1754 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1758 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
).value
1759 ) / this.getAmperageLimitationUnitDivider()
1764 private async startMessageSequence(): Promise
<void> {
1765 if (this.stationInfo
.autoRegister
) {
1766 await this.ocppRequestService
.requestHandler
<
1767 BootNotificationRequest
,
1768 BootNotificationResponse
1770 RequestCommand
.BOOT_NOTIFICATION
,
1772 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1773 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1774 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1775 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1776 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1777 iccid
: this.bootNotificationRequest
.iccid
,
1778 imsi
: this.bootNotificationRequest
.imsi
,
1779 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1780 meterType
: this.bootNotificationRequest
.meterType
,
1782 { skipBufferingOnError
: true }
1785 // Start WebSocket ping
1786 this.startWebSocketPing();
1788 this.startHeartbeat();
1789 // Initialize connectors status
1790 for (const connectorId
of this.connectors
.keys()) {
1791 if (connectorId
=== 0) {
1795 !this.getConnectorStatus(connectorId
)?.status &&
1796 this.getConnectorStatus(connectorId
)?.bootStatus
1798 // Send status in template at startup
1799 await this.ocppRequestService
.requestHandler
<
1800 StatusNotificationRequest
,
1801 StatusNotificationResponse
1802 >(RequestCommand
.STATUS_NOTIFICATION
, {
1804 status: this.getConnectorStatus(connectorId
).bootStatus
,
1805 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1807 this.getConnectorStatus(connectorId
).status =
1808 this.getConnectorStatus(connectorId
).bootStatus
;
1811 this.getConnectorStatus(connectorId
)?.status &&
1812 this.getConnectorStatus(connectorId
)?.bootStatus
1814 // Send status in template after reset
1815 await this.ocppRequestService
.requestHandler
<
1816 StatusNotificationRequest
,
1817 StatusNotificationResponse
1818 >(RequestCommand
.STATUS_NOTIFICATION
, {
1820 status: this.getConnectorStatus(connectorId
).bootStatus
,
1821 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1823 this.getConnectorStatus(connectorId
).status =
1824 this.getConnectorStatus(connectorId
).bootStatus
;
1825 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1826 // Send previous status at template reload
1827 await this.ocppRequestService
.requestHandler
<
1828 StatusNotificationRequest
,
1829 StatusNotificationResponse
1830 >(RequestCommand
.STATUS_NOTIFICATION
, {
1832 status: this.getConnectorStatus(connectorId
).status,
1833 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1836 // Send default status
1837 await this.ocppRequestService
.requestHandler
<
1838 StatusNotificationRequest
,
1839 StatusNotificationResponse
1840 >(RequestCommand
.STATUS_NOTIFICATION
, {
1842 status: ChargePointStatus
.AVAILABLE
,
1843 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1845 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1849 this.startAutomaticTransactionGenerator();
1852 private startAutomaticTransactionGenerator() {
1853 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1854 if (!this.automaticTransactionGenerator
) {
1855 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1857 if (!this.automaticTransactionGenerator
.started
) {
1858 this.automaticTransactionGenerator
.start();
1863 private async stopMessageSequence(
1864 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1866 // Stop WebSocket ping
1867 this.stopWebSocketPing();
1869 this.stopHeartbeat();
1872 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1873 this.automaticTransactionGenerator
?.started
1875 this.automaticTransactionGenerator
.stop();
1877 for (const connectorId
of this.connectors
.keys()) {
1878 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1879 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1881 this.getBeginEndMeterValues() &&
1882 this.getOcppStrictCompliance() &&
1883 !this.getOutOfOrderEndMeterValues()
1885 // FIXME: Implement OCPP version agnostic helpers
1886 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1889 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1891 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1892 RequestCommand
.METER_VALUES
,
1896 meterValue
: transactionEndMeterValue
,
1900 await this.ocppRequestService
.requestHandler
<
1901 StopTransactionRequest
,
1902 StopTransactionResponse
1903 >(RequestCommand
.STOP_TRANSACTION
, {
1905 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1906 idTag
: this.getTransactionIdTag(transactionId
),
1914 private startWebSocketPing(): void {
1915 const webSocketPingInterval
: number = this.getConfigurationKey(
1916 StandardParametersKey
.WebSocketPingInterval
1918 ? Utils
.convertToInt(
1919 this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
1922 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1923 this.webSocketPingSetInterval
= setInterval(() => {
1924 if (this.isWebSocketConnectionOpened()) {
1925 this.wsConnection
.ping((): void => {
1926 /* This is intentional */
1929 }, webSocketPingInterval
* 1000);
1932 ' WebSocket ping started every ' +
1933 Utils
.formatDurationSeconds(webSocketPingInterval
)
1935 } else if (this.webSocketPingSetInterval
) {
1938 ' WebSocket ping every ' +
1939 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1944 `${this.logPrefix()} WebSocket ping interval set to ${
1945 webSocketPingInterval
1946 ? Utils.formatDurationSeconds(webSocketPingInterval)
1947 : webSocketPingInterval
1948 }, not starting the WebSocket ping`
1953 private stopWebSocketPing(): void {
1954 if (this.webSocketPingSetInterval
) {
1955 clearInterval(this.webSocketPingSetInterval
);
1959 private warnDeprecatedTemplateKey(
1960 template
: ChargingStationTemplate
,
1962 chargingStationId
: string,
1965 if (!Utils
.isUndefined(template
[key
])) {
1966 const logPrefixStr
= ` ${chargingStationId} |`;
1968 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1970 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1975 private convertDeprecatedTemplateKey(
1976 template
: ChargingStationTemplate
,
1977 deprecatedKey
: string,
1980 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
1981 template
[key
] = template
[deprecatedKey
] as unknown
;
1982 delete template
[deprecatedKey
];
1986 private getConfiguredSupervisionUrl(): URL
{
1987 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1988 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1990 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1992 switch (Configuration
.getSupervisionUrlDistribution()) {
1993 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1994 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1996 case SupervisionUrlDistribution
.RANDOM
:
1998 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
2000 case SupervisionUrlDistribution
.SEQUENTIAL
:
2001 if (this.index
<= supervisionUrls
.length
) {
2002 urlIndex
= this.index
- 1;
2005 `${this.logPrefix()} No more configured supervision urls available, using the first one`
2011 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2012 SupervisionUrlDistribution.ROUND_ROBIN
2015 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2018 return new URL(supervisionUrls
[urlIndex
]);
2020 return new URL(supervisionUrls
as string);
2023 private getHeartbeatInterval(): number | undefined {
2024 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
2025 if (HeartbeatInterval
) {
2026 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
2028 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
2029 if (HeartBeatInterval
) {
2030 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
2032 !this.stationInfo
.autoRegister
&&
2034 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
2035 Constants.DEFAULT_HEARTBEAT_INTERVAL
2038 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
2041 private stopHeartbeat(): void {
2042 if (this.heartbeatSetInterval
) {
2043 clearInterval(this.heartbeatSetInterval
);
2047 private openWSConnection(
2048 options
: WsOptions
= this.stationInfo
.wsOptions
,
2049 forceCloseOpened
= false
2051 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
2053 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
2054 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
2056 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
2058 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
2059 this.wsConnection
.close();
2061 let protocol
: string;
2062 switch (this.getOcppVersion()) {
2063 case OCPPVersion
.VERSION_16
:
2064 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
2067 this.handleUnsupportedVersion(this.getOcppVersion());
2070 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
2072 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
2076 private stopMeterValues(connectorId
: number) {
2077 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2078 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
2082 private getReconnectExponentialDelay(): boolean | undefined {
2083 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
2084 ? this.stationInfo
.reconnectExponentialDelay
2088 private async reconnect(code
: number): Promise
<void> {
2089 // Stop WebSocket ping
2090 this.stopWebSocketPing();
2092 this.stopHeartbeat();
2093 // Stop the ATG if needed
2095 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
2096 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
2097 this.automaticTransactionGenerator
?.started
2099 this.automaticTransactionGenerator
.stop();
2102 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2103 this.getAutoReconnectMaxRetries() === -1
2105 this.autoReconnectRetryCount
++;
2106 const reconnectDelay
= this.getReconnectExponentialDelay()
2107 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2108 : this.getConnectionTimeout() * 1000;
2109 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
2111 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2114 )}ms, timeout ${reconnectTimeout}ms`
2116 await Utils
.sleep(reconnectDelay
);
2119 ' WebSocket: reconnecting try #' +
2120 this.autoReconnectRetryCount
.toString()
2122 this.openWSConnection(
2123 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
2126 this.wsConnectionRestarted
= true;
2127 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2129 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2130 this.autoReconnectRetryCount
2131 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2136 private initializeConnectorStatus(connectorId
: number): void {
2137 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2138 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2139 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2140 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2141 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2142 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;