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
=
262 ((this.stationInfo
['maxPower'] as number) ?? this.stationInfo
.maximumPower
) /
263 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
.sendMessageHandler
<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
.sendMessageHandler
<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 // Monitor authorization file
547 FileUtils
.watchJsonFile
<string[]>(
549 FileType
.Authorization
,
550 this.getAuthorizationFile(),
553 // Monitor charging station template file
554 FileUtils
.watchJsonFile(
556 FileType
.ChargingStationTemplate
,
559 (event
, filename
): void => {
560 if (filename
&& event
=== 'change') {
563 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
565 } file have changed, reload`
571 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
572 this.automaticTransactionGenerator
574 this.automaticTransactionGenerator
.stop();
576 this.startAutomaticTransactionGenerator();
577 if (this.getEnableStatistics()) {
578 this.performanceStatistics
.restart();
580 this.performanceStatistics
.stop();
582 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
585 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
592 // Handle WebSocket message
593 this.wsConnection
.on(
595 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
597 // Handle WebSocket error
598 this.wsConnection
.on(
600 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
602 // Handle WebSocket close
603 this.wsConnection
.on(
605 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
607 // Handle WebSocket open
608 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
609 // Handle WebSocket ping
610 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
611 // Handle WebSocket pong
612 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
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
.sendMessageHandler
<
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
=
793 ((this.stationInfo
['maxPower'] as number) ?? this.stationInfo
.maximumPower
) /
794 this.stationInfo
.powerDivider
;
795 if (limit
> connectorMaximumPower
) {
797 `${this.logPrefix()} Charging profile id ${
798 matchingChargingProfile.chargingProfileId
799 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
800 this.getConnectorStatus(connectorId
).chargingProfiles
802 limit
= connectorMaximumPower
;
807 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
808 let cpReplaced
= false;
809 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
810 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
811 (chargingProfile
: ChargingProfile
, index
: number) => {
813 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
814 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
815 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
817 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
823 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
826 public resetConnectorStatus(connectorId
: number): void {
827 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
828 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
829 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
830 this.getConnectorStatus(connectorId
).transactionStarted
= false;
831 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
832 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
833 delete this.getConnectorStatus(connectorId
).transactionId
;
834 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
835 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
836 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
837 this.stopMeterValues(connectorId
);
840 public bufferMessage(message
: string): void {
841 this.messageBuffer
.add(message
);
844 private flushMessageBuffer() {
845 if (this.messageBuffer
.size
> 0) {
846 this.messageBuffer
.forEach((message
) => {
847 // TODO: evaluate the need to track performance
848 this.wsConnection
.send(message
);
849 this.messageBuffer
.delete(message
);
854 private getSupervisionUrlOcppConfiguration(): boolean {
855 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
858 private getSupervisionUrlOcppKey(): string {
859 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
862 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
863 // In case of multiple instances: add instance index to charging station id
864 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
865 const idSuffix
= stationTemplate
.nameSuffix
?? '';
866 const idStr
= '000000000' + this.index
.toString();
867 return stationTemplate
.fixedName
868 ? stationTemplate
.baseName
869 : stationTemplate
.baseName
+
871 instanceIndex
.toString() +
872 idStr
.substring(idStr
.length
- 4) +
876 private getRandomSerialNumberSuffix(params
?: {
877 randomBytesLength
?: number;
880 const randomSerialNumberSuffix
= crypto
881 .randomBytes(params
?.randomBytesLength
?? 16)
883 if (params
?.upperCase
) {
884 return randomSerialNumberSuffix
.toUpperCase();
886 return randomSerialNumberSuffix
;
889 private getTemplateFromFile(): ChargingStationTemplate
| null {
890 let template
: ChargingStationTemplate
= null;
892 const measureId
= `${FileType.ChargingStationTemplate} read`;
893 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
894 template
= JSON
.parse(fs
.readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
895 PerformanceStatistics
.endMeasure(measureId
, beginId
);
897 FileUtils
.handleFileException(
899 FileType
.ChargingStationTemplate
,
901 error
as NodeJS
.ErrnoException
907 private createSerialNumber(
908 stationInfo
: ChargingStationInfo
,
909 existingStationInfo
?: ChargingStationInfo
,
910 params
: { randomSerialNumberUpperCase
?: boolean; randomSerialNumber
?: boolean } = {
911 randomSerialNumberUpperCase
: true,
912 randomSerialNumber
: true,
915 params
= params
?? {};
916 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
917 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
918 if (existingStationInfo
) {
919 existingStationInfo
?.chargePointSerialNumber
&&
920 (stationInfo
.chargePointSerialNumber
= existingStationInfo
.chargePointSerialNumber
);
921 existingStationInfo
?.chargeBoxSerialNumber
&&
922 (stationInfo
.chargeBoxSerialNumber
= existingStationInfo
.chargeBoxSerialNumber
);
924 const serialNumberSuffix
= params
?.randomSerialNumber
925 ? this.getRandomSerialNumberSuffix({ upperCase
: params
.randomSerialNumberUpperCase
})
927 stationInfo
.chargePointSerialNumber
=
928 stationInfo
?.chargePointSerialNumberPrefix
&&
929 stationInfo
.chargePointSerialNumberPrefix
+ serialNumberSuffix
;
930 stationInfo
.chargeBoxSerialNumber
=
931 stationInfo
?.chargeBoxSerialNumberPrefix
&&
932 stationInfo
.chargeBoxSerialNumberPrefix
+ serialNumberSuffix
;
936 private getStationInfoFromTemplate(): ChargingStationInfo
{
937 const stationInfo
: ChargingStationInfo
=
938 this.getTemplateFromFile() ?? ({} as ChargingStationInfo
);
939 stationInfo
.hash
= crypto
940 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
941 .update(JSON
.stringify(stationInfo
))
943 const chargingStationId
= this.getChargingStationId(stationInfo
);
944 // Deprecation template keys section
945 this.warnDeprecatedTemplateKey(
949 "Use 'supervisionUrls' instead"
951 this.convertDeprecatedTemplateKey(stationInfo
, 'supervisionUrl', 'supervisionUrls');
952 stationInfo
.wsOptions
= stationInfo
?.wsOptions
?? {};
953 if (!Utils
.isEmptyArray(stationInfo
.power
)) {
954 stationInfo
.power
= stationInfo
.power
as number[];
955 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationInfo
.power
.length
);
956 stationInfo
.maximumPower
=
957 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
958 ? stationInfo
.power
[powerArrayRandomIndex
] * 1000
959 : stationInfo
.power
[powerArrayRandomIndex
];
961 stationInfo
.power
= stationInfo
.power
as number;
962 stationInfo
.maximumPower
=
963 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
964 ? stationInfo
.power
* 1000
967 delete stationInfo
.power
;
968 delete stationInfo
.powerUnit
;
969 stationInfo
.chargingStationId
= chargingStationId
;
970 stationInfo
.resetTime
= stationInfo
.resetTime
971 ? stationInfo
.resetTime
* 1000
972 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
976 private getStationInfoFromFile(): ChargingStationInfo
| null {
977 return this.getConfigurationFromFile()?.stationInfo
?? null;
980 private getStationInfo(): ChargingStationInfo
{
981 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
982 this.hashId
= this.getHashId(stationInfoFromTemplate
);
983 this.configurationFile
= path
.join(
984 path
.resolve(__dirname
, '../'),
987 this.hashId
+ '.json'
989 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
990 if (stationInfoFromFile
?.hash
=== stationInfoFromTemplate
.hash
) {
991 return stationInfoFromFile
;
993 this.createSerialNumber(stationInfoFromTemplate
, stationInfoFromFile
);
994 return stationInfoFromTemplate
;
997 private saveStationInfo(): void {
998 this.saveConfiguration(Section
.stationInfo
);
1001 private getOcppVersion(): OCPPVersion
{
1002 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
1005 private getOcppPersistentConfiguration(): boolean {
1006 return this.stationInfo
.ocppPersistentConfiguration
?? true;
1009 private handleUnsupportedVersion(version
: OCPPVersion
) {
1010 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
1013 logger
.error(errMsg
);
1014 throw new Error(errMsg
);
1017 private createBootNotificationRequest(stationInfo
: ChargingStationInfo
): BootNotificationRequest
{
1019 chargePointModel
: stationInfo
.chargePointModel
,
1020 chargePointVendor
: stationInfo
.chargePointVendor
,
1021 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
1022 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
1024 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
1025 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
1027 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
1028 firmwareVersion
: stationInfo
.firmwareVersion
,
1030 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
1031 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
1032 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
1033 meterSerialNumber
: stationInfo
.meterSerialNumber
,
1035 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
1036 meterType
: stationInfo
.meterType
,
1041 private getHashId(stationInfo
: ChargingStationInfo
): string {
1042 const hashBootNotificationRequest
= {
1043 chargePointModel
: stationInfo
.chargePointModel
,
1044 chargePointVendor
: stationInfo
.chargePointVendor
,
1045 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumberPrefix
) && {
1046 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumberPrefix
,
1048 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumberPrefix
) && {
1049 chargePointSerialNumber
: stationInfo
.chargePointSerialNumberPrefix
,
1051 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
1052 firmwareVersion
: stationInfo
.firmwareVersion
,
1054 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
1055 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
1056 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
1057 meterSerialNumber
: stationInfo
.meterSerialNumber
,
1059 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
1060 meterType
: stationInfo
.meterType
,
1064 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1065 .update(JSON
.stringify(hashBootNotificationRequest
) + stationInfo
.chargingStationId
)
1069 private initialize(): void {
1070 this.stationInfo
= this.getStationInfo();
1071 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
1072 this.bootNotificationRequest
= this.createBootNotificationRequest(this.stationInfo
);
1073 this.ocppConfiguration
= this.getOcppConfiguration();
1074 delete this.stationInfo
.Configuration
;
1075 // Build connectors if needed
1076 const maxConnectors
= this.getMaxNumberOfConnectors();
1077 if (maxConnectors
<= 0) {
1079 `${this.logPrefix()} Charging station template ${
1081 } with ${maxConnectors} connectors`
1084 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
1085 if (templateMaxConnectors
<= 0) {
1087 `${this.logPrefix()} Charging station template ${
1089 } with no connector configuration`
1092 if (!this.stationInfo
.Connectors
[0]) {
1094 `${this.logPrefix()} Charging station template ${
1096 } with no connector Id 0 configuration`
1102 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
1103 !this.stationInfo
.randomConnectors
1106 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
1108 }, forcing random connector configurations affectation`
1110 this.stationInfo
.randomConnectors
= true;
1112 const connectorsConfigHash
= crypto
1113 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1114 .update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString())
1116 const connectorsConfigChanged
=
1117 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1118 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1119 connectorsConfigChanged
&& this.connectors
.clear();
1120 this.connectorsConfigurationHash
= connectorsConfigHash
;
1121 // Add connector Id 0
1122 let lastConnector
= '0';
1123 for (lastConnector
in this.stationInfo
.Connectors
) {
1124 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1126 lastConnectorId
=== 0 &&
1127 this.getUseConnectorId0() &&
1128 this.stationInfo
.Connectors
[lastConnector
]
1130 this.connectors
.set(
1132 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
])
1134 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1135 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1136 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1140 // Generate all connectors
1142 (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0
1144 for (let index
= 1; index
<= maxConnectors
; index
++) {
1145 const randConnectorId
= this.stationInfo
.randomConnectors
1146 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1148 this.connectors
.set(
1150 Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
])
1152 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1153 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1154 this.getConnectorStatus(index
).chargingProfiles
= [];
1159 // The connectors attribute need to be initialized
1160 this.stationInfo
.maximumAmperage
= this.getMaximumAmperage();
1161 this.saveStationInfo();
1162 // Avoid duplication of connectors related information in RAM
1163 delete this.stationInfo
.Connectors
;
1164 // Initialize transaction attributes on connectors
1165 for (const connectorId
of this.connectors
.keys()) {
1166 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1167 this.initializeConnectorStatus(connectorId
);
1170 this.wsConfiguredConnectionUrl
= new URL(
1171 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
1173 // OCPP configuration
1174 this.initializeOcppConfiguration();
1175 switch (this.getOcppVersion()) {
1176 case OCPPVersion
.VERSION_16
:
1177 this.ocppIncomingRequestService
=
1178 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>(this);
1179 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1181 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(this)
1185 this.handleUnsupportedVersion(this.getOcppVersion());
1188 if (this.stationInfo
.autoRegister
) {
1189 this.bootNotificationResponse
= {
1190 currentTime
: new Date().toISOString(),
1191 interval
: this.getHeartbeatInterval() / 1000,
1192 status: RegistrationStatus
.ACCEPTED
,
1195 this.stationInfo
.powerDivider
= this.getPowerDivider();
1196 if (this.getEnableStatistics()) {
1197 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1199 this.stationInfo
.chargingStationId
,
1200 this.wsConnectionUrl
1205 private initializeOcppConfiguration(): void {
1207 this.getSupervisionUrlOcppConfiguration() &&
1208 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1210 this.addConfigurationKey(
1211 this.getSupervisionUrlOcppKey(),
1212 this.getConfiguredSupervisionUrl().href
,
1216 !this.getSupervisionUrlOcppConfiguration() &&
1217 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1219 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save
: false });
1222 this.stationInfo
.amperageLimitationOcppKey
&&
1223 !this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1225 this.addConfigurationKey(
1226 this.stationInfo
.amperageLimitationOcppKey
,
1227 (this.stationInfo
.maximumAmperage
* this.getAmperageLimitationUnitDivider()).toString()
1230 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
1231 this.addConfigurationKey(
1232 StandardParametersKey
.SupportedFeatureProfiles
,
1233 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`
1236 this.addConfigurationKey(
1237 StandardParametersKey
.NumberOfConnectors
,
1238 this.getNumberOfConnectors().toString(),
1242 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
1243 this.addConfigurationKey(
1244 StandardParametersKey
.MeterValuesSampledData
,
1245 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1248 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
1249 const connectorPhaseRotation
= [];
1250 for (const connectorId
of this.connectors
.keys()) {
1252 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1253 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1254 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1255 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1257 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1258 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1259 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1260 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1263 this.addConfigurationKey(
1264 StandardParametersKey
.ConnectorPhaseRotation
,
1265 connectorPhaseRotation
.toString()
1268 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
1269 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1272 !this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
) &&
1273 this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(
1274 SupportedFeatureProfiles
.Local_Auth_List_Management
1277 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
1279 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1280 this.addConfigurationKey(
1281 StandardParametersKey
.ConnectionTimeOut
,
1282 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1285 this.saveOcppConfiguration();
1288 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1289 let configuration
: ChargingStationConfiguration
= null;
1290 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1292 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1293 const beginId
= PerformanceStatistics
.beginMeasure(
1294 `${FileType.ChargingStationConfiguration} read`
1296 configuration
= JSON
.parse(
1297 fs
.readFileSync(this.configurationFile
, 'utf8')
1298 ) as ChargingStationConfiguration
;
1299 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1301 FileUtils
.handleFileException(
1303 FileType
.ChargingStationConfiguration
,
1304 this.configurationFile
,
1305 error
as NodeJS
.ErrnoException
1309 return configuration
;
1312 private saveConfiguration(section
?: Section
): void {
1313 if (this.configurationFile
) {
1315 const configurationData
: ChargingStationConfiguration
=
1316 this.getConfigurationFromFile() ?? {};
1317 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1318 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1321 case Section
.ocppConfiguration
:
1322 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1324 case Section
.stationInfo
:
1325 configurationData
.stationInfo
= this.stationInfo
;
1328 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1329 configurationData
.stationInfo
= this.stationInfo
;
1332 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1333 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1334 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1335 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1336 fs
.closeSync(fileDescriptor
);
1337 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1339 FileUtils
.handleFileException(
1341 FileType
.ChargingStationConfiguration
,
1342 this.configurationFile
,
1343 error
as NodeJS
.ErrnoException
1348 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
1353 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
{
1354 return this.getTemplateFromFile().Configuration
?? ({} as ChargingStationOcppConfiguration
);
1357 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1358 let configuration
: ChargingStationConfiguration
= null;
1359 if (this.getOcppPersistentConfiguration()) {
1360 const configurationFromFile
= this.getConfigurationFromFile();
1361 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1363 configuration
&& delete configuration
.stationInfo
;
1364 return configuration
;
1367 private getOcppConfiguration(): ChargingStationOcppConfiguration
{
1368 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1369 if (!ocppConfiguration
) {
1370 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1372 return ocppConfiguration
;
1375 private saveOcppConfiguration(): void {
1376 if (this.getOcppPersistentConfiguration()) {
1377 this.saveConfiguration(Section
.ocppConfiguration
);
1381 private async onOpen(): Promise
<void> {
1383 `${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`
1385 if (!this.isInAcceptedState()) {
1386 // Send BootNotification
1387 let registrationRetryCount
= 0;
1389 this.bootNotificationResponse
= await this.ocppRequestService
.sendMessageHandler
<
1390 BootNotificationRequest
,
1391 BootNotificationResponse
1393 RequestCommand
.BOOT_NOTIFICATION
,
1395 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1396 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1397 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1398 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1399 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1400 iccid
: this.bootNotificationRequest
.iccid
,
1401 imsi
: this.bootNotificationRequest
.imsi
,
1402 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1403 meterType
: this.bootNotificationRequest
.meterType
,
1405 { skipBufferingOnError
: true }
1407 if (!this.isInAcceptedState()) {
1408 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1410 this.bootNotificationResponse
?.interval
1411 ? this.bootNotificationResponse
.interval
* 1000
1412 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1416 !this.isInAcceptedState() &&
1417 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1418 this.getRegistrationMaxRetries() === -1)
1421 if (this.isInAcceptedState()) {
1422 await this.startMessageSequence();
1423 this.stopped
&& (this.stopped
= false);
1424 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
1425 this.flushMessageBuffer();
1429 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1432 this.autoReconnectRetryCount
= 0;
1433 this.wsConnectionRestarted
= false;
1436 private async onClose(code
: number, reason
: string): Promise
<void> {
1439 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1440 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1442 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1444 )}' and reason '${reason}'`
1446 this.autoReconnectRetryCount
= 0;
1451 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1453 )}' and reason '${reason}'`
1455 await this.reconnect(code
);
1460 private async onMessage(data
: Data
): Promise
<void> {
1461 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [
1464 '' as IncomingRequestCommand
,
1468 let responseCallback
: (
1469 payload
: JsonType
| string,
1470 requestPayload
: JsonType
| OCPPError
1472 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1473 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1474 let requestPayload
: JsonType
| OCPPError
;
1475 let cachedRequest
: CachedRequest
;
1478 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
1479 if (Utils
.isIterable(request
)) {
1480 // Parse the message
1481 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
1483 throw new OCPPError(
1484 ErrorType
.PROTOCOL_ERROR
,
1485 'Incoming request is not iterable',
1489 // Check the Type of message
1490 switch (messageType
) {
1492 case MessageType
.CALL_MESSAGE
:
1493 if (this.getEnableStatistics()) {
1494 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1497 await this.ocppIncomingRequestService
.handleRequest(
1504 case MessageType
.CALL_RESULT_MESSAGE
:
1506 cachedRequest
= this.requests
.get(messageId
);
1507 if (Utils
.isIterable(cachedRequest
)) {
1508 [responseCallback
, , , requestPayload
] = cachedRequest
;
1510 throw new OCPPError(
1511 ErrorType
.PROTOCOL_ERROR
,
1512 `Cached request for message id ${messageId} response is not iterable`,
1516 if (!responseCallback
) {
1518 throw new OCPPError(
1519 ErrorType
.INTERNAL_ERROR
,
1520 `Response for unknown message id ${messageId}`,
1524 responseCallback(commandName
, requestPayload
);
1527 case MessageType
.CALL_ERROR_MESSAGE
:
1528 cachedRequest
= this.requests
.get(messageId
);
1529 if (Utils
.isIterable(cachedRequest
)) {
1530 [, rejectCallback
, requestCommandName
] = cachedRequest
;
1532 throw new OCPPError(
1533 ErrorType
.PROTOCOL_ERROR
,
1534 `Cached request for message id ${messageId} error response is not iterable`
1537 if (!rejectCallback
) {
1539 throw new OCPPError(
1540 ErrorType
.INTERNAL_ERROR
,
1541 `Error response for unknown message id ${messageId}`,
1546 new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
)
1551 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1552 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1553 logger
.error(errMsg
);
1554 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1559 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1562 this.requests
.get(messageId
),
1566 messageType
=== MessageType
.CALL_MESSAGE
&&
1567 (await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
));
1571 private onPing(): void {
1572 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1575 private onPong(): void {
1576 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1579 private onError(error
: WSError
): void {
1580 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1583 private getAuthorizationFile(): string | undefined {
1585 this.stationInfo
.authorizationFile
&&
1587 path
.resolve(__dirname
, '../'),
1589 path
.basename(this.stationInfo
.authorizationFile
)
1594 private getAuthorizedTags(): string[] {
1595 let authorizedTags
: string[] = [];
1596 const authorizationFile
= this.getAuthorizationFile();
1597 if (authorizationFile
) {
1599 // Load authorization file
1600 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
1602 FileUtils
.handleFileException(
1604 FileType
.Authorization
,
1606 error
as NodeJS
.ErrnoException
1611 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1614 return authorizedTags
;
1617 private getUseConnectorId0(): boolean | undefined {
1618 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1619 ? this.stationInfo
.useConnectorId0
1623 private getNumberOfRunningTransactions(): number {
1625 for (const connectorId
of this.connectors
.keys()) {
1626 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1634 private getConnectionTimeout(): number | undefined {
1635 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1637 parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ??
1638 Constants
.DEFAULT_CONNECTION_TIMEOUT
1641 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1644 // -1 for unlimited, 0 for disabling
1645 private getAutoReconnectMaxRetries(): number | undefined {
1646 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1647 return this.stationInfo
.autoReconnectMaxRetries
;
1649 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1650 return Configuration
.getAutoReconnectMaxRetries();
1656 private getRegistrationMaxRetries(): number | undefined {
1657 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1658 return this.stationInfo
.registrationMaxRetries
;
1663 private getPowerDivider(): number {
1664 let powerDivider
= this.getNumberOfConnectors();
1665 if (this.stationInfo
.powerSharedByConnectors
) {
1666 powerDivider
= this.getNumberOfRunningTransactions();
1668 return powerDivider
;
1671 private getTemplateMaxNumberOfConnectors(): number {
1672 return Object.keys(this.stationInfo
.Connectors
).length
;
1675 private getMaxNumberOfConnectors(): number {
1676 let maxConnectors
: number;
1677 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1678 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1679 // Distribute evenly the number of connectors
1680 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1681 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1682 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1684 maxConnectors
= this.stationInfo
.Connectors
[0]
1685 ? this.getTemplateMaxNumberOfConnectors() - 1
1686 : this.getTemplateMaxNumberOfConnectors();
1688 return maxConnectors
;
1691 private getMaximumAmperage(): number | undefined {
1692 const maximumPower
= (this.stationInfo
['maxPower'] as number) ?? this.stationInfo
.maximumPower
;
1693 switch (this.getCurrentOutType()) {
1694 case CurrentType
.AC
:
1695 return ACElectricUtils
.amperagePerPhaseFromPower(
1696 this.getNumberOfPhases(),
1697 maximumPower
/ this.getNumberOfConnectors(),
1698 this.getVoltageOut()
1700 case CurrentType
.DC
:
1701 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut());
1705 private getAmperageLimitationUnitDivider(): number {
1706 let unitDivider
= 1;
1707 switch (this.stationInfo
.amperageLimitationUnit
) {
1708 case AmpereUnits
.DECI_AMPERE
:
1711 case AmpereUnits
.CENTI_AMPERE
:
1714 case AmpereUnits
.MILLI_AMPERE
:
1721 private getAmperageLimitation(): number | undefined {
1723 this.stationInfo
.amperageLimitationOcppKey
&&
1724 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1728 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
).value
1729 ) / this.getAmperageLimitationUnitDivider()
1734 private async startMessageSequence(): Promise
<void> {
1735 if (this.stationInfo
.autoRegister
) {
1736 await this.ocppRequestService
.sendMessageHandler
<
1737 BootNotificationRequest
,
1738 BootNotificationResponse
1740 RequestCommand
.BOOT_NOTIFICATION
,
1742 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1743 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1744 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1745 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1746 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1747 iccid
: this.bootNotificationRequest
.iccid
,
1748 imsi
: this.bootNotificationRequest
.imsi
,
1749 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1750 meterType
: this.bootNotificationRequest
.meterType
,
1752 { skipBufferingOnError
: true }
1755 // Start WebSocket ping
1756 this.startWebSocketPing();
1758 this.startHeartbeat();
1759 // Initialize connectors status
1760 for (const connectorId
of this.connectors
.keys()) {
1761 if (connectorId
=== 0) {
1765 !this.getConnectorStatus(connectorId
)?.status &&
1766 this.getConnectorStatus(connectorId
)?.bootStatus
1768 // Send status in template at startup
1769 await this.ocppRequestService
.sendMessageHandler
<
1770 StatusNotificationRequest
,
1771 StatusNotificationResponse
1772 >(RequestCommand
.STATUS_NOTIFICATION
, {
1774 status: this.getConnectorStatus(connectorId
).bootStatus
,
1775 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1777 this.getConnectorStatus(connectorId
).status =
1778 this.getConnectorStatus(connectorId
).bootStatus
;
1781 this.getConnectorStatus(connectorId
)?.status &&
1782 this.getConnectorStatus(connectorId
)?.bootStatus
1784 // Send status in template after reset
1785 await this.ocppRequestService
.sendMessageHandler
<
1786 StatusNotificationRequest
,
1787 StatusNotificationResponse
1788 >(RequestCommand
.STATUS_NOTIFICATION
, {
1790 status: this.getConnectorStatus(connectorId
).bootStatus
,
1791 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1793 this.getConnectorStatus(connectorId
).status =
1794 this.getConnectorStatus(connectorId
).bootStatus
;
1795 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1796 // Send previous status at template reload
1797 await this.ocppRequestService
.sendMessageHandler
<
1798 StatusNotificationRequest
,
1799 StatusNotificationResponse
1800 >(RequestCommand
.STATUS_NOTIFICATION
, {
1802 status: this.getConnectorStatus(connectorId
).status,
1803 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1806 // Send default status
1807 await this.ocppRequestService
.sendMessageHandler
<
1808 StatusNotificationRequest
,
1809 StatusNotificationResponse
1810 >(RequestCommand
.STATUS_NOTIFICATION
, {
1812 status: ChargePointStatus
.AVAILABLE
,
1813 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1815 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1819 this.startAutomaticTransactionGenerator();
1822 private startAutomaticTransactionGenerator() {
1823 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1824 if (!this.automaticTransactionGenerator
) {
1825 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1827 if (!this.automaticTransactionGenerator
.started
) {
1828 this.automaticTransactionGenerator
.start();
1833 private async stopMessageSequence(
1834 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1836 // Stop WebSocket ping
1837 this.stopWebSocketPing();
1839 this.stopHeartbeat();
1842 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1843 this.automaticTransactionGenerator
?.started
1845 this.automaticTransactionGenerator
.stop();
1847 for (const connectorId
of this.connectors
.keys()) {
1848 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1849 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1851 this.getBeginEndMeterValues() &&
1852 this.getOcppStrictCompliance() &&
1853 !this.getOutOfOrderEndMeterValues()
1855 // FIXME: Implement OCPP version agnostic helpers
1856 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1859 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1861 await this.ocppRequestService
.sendMessageHandler
<
1864 >(RequestCommand
.METER_VALUES
, {
1867 meterValue
: transactionEndMeterValue
,
1870 await this.ocppRequestService
.sendMessageHandler
<
1871 StopTransactionRequest
,
1872 StopTransactionResponse
1873 >(RequestCommand
.STOP_TRANSACTION
, {
1875 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1876 idTag
: this.getTransactionIdTag(transactionId
),
1884 private startWebSocketPing(): void {
1885 const webSocketPingInterval
: number = this.getConfigurationKey(
1886 StandardParametersKey
.WebSocketPingInterval
1888 ? Utils
.convertToInt(
1889 this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
1892 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1893 this.webSocketPingSetInterval
= setInterval(() => {
1894 if (this.isWebSocketConnectionOpened()) {
1895 this.wsConnection
.ping((): void => {
1896 /* This is intentional */
1899 }, webSocketPingInterval
* 1000);
1902 ' WebSocket ping started every ' +
1903 Utils
.formatDurationSeconds(webSocketPingInterval
)
1905 } else if (this.webSocketPingSetInterval
) {
1908 ' WebSocket ping every ' +
1909 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1914 `${this.logPrefix()} WebSocket ping interval set to ${
1915 webSocketPingInterval
1916 ? Utils.formatDurationSeconds(webSocketPingInterval)
1917 : webSocketPingInterval
1918 }, not starting the WebSocket ping`
1923 private stopWebSocketPing(): void {
1924 if (this.webSocketPingSetInterval
) {
1925 clearInterval(this.webSocketPingSetInterval
);
1929 private warnDeprecatedTemplateKey(
1930 template
: ChargingStationTemplate
,
1932 chargingStationId
: string,
1935 if (!Utils
.isUndefined(template
[key
])) {
1936 const logPrefixStr
= ` ${chargingStationId} |`;
1938 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1940 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1945 private convertDeprecatedTemplateKey(
1946 template
: ChargingStationTemplate
,
1947 deprecatedKey
: string,
1950 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
1951 template
[key
] = template
[deprecatedKey
] as unknown
;
1952 delete template
[deprecatedKey
];
1956 private getConfiguredSupervisionUrl(): URL
{
1957 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1958 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1960 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1962 switch (Configuration
.getSupervisionUrlDistribution()) {
1963 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1964 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1966 case SupervisionUrlDistribution
.RANDOM
:
1968 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1970 case SupervisionUrlDistribution
.SEQUENTIAL
:
1971 if (this.index
<= supervisionUrls
.length
) {
1972 urlIndex
= this.index
- 1;
1975 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1981 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1982 SupervisionUrlDistribution.ROUND_ROBIN
1985 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1988 return new URL(supervisionUrls
[urlIndex
]);
1990 return new URL(supervisionUrls
as string);
1993 private getHeartbeatInterval(): number | undefined {
1994 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
1995 if (HeartbeatInterval
) {
1996 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1998 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
1999 if (HeartBeatInterval
) {
2000 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
2002 !this.stationInfo
.autoRegister
&&
2004 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
2005 Constants.DEFAULT_HEARTBEAT_INTERVAL
2008 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
2011 private stopHeartbeat(): void {
2012 if (this.heartbeatSetInterval
) {
2013 clearInterval(this.heartbeatSetInterval
);
2017 private openWSConnection(
2018 options
: WsOptions
= this.stationInfo
.wsOptions
,
2019 forceCloseOpened
= false
2021 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
2023 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
2024 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
2026 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
2028 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
2029 this.wsConnection
.close();
2031 let protocol
: string;
2032 switch (this.getOcppVersion()) {
2033 case OCPPVersion
.VERSION_16
:
2034 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
2037 this.handleUnsupportedVersion(this.getOcppVersion());
2040 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
2042 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
2046 private stopMeterValues(connectorId
: number) {
2047 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2048 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
2052 private getReconnectExponentialDelay(): boolean | undefined {
2053 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
2054 ? this.stationInfo
.reconnectExponentialDelay
2058 private async reconnect(code
: number): Promise
<void> {
2059 // Stop WebSocket ping
2060 this.stopWebSocketPing();
2062 this.stopHeartbeat();
2063 // Stop the ATG if needed
2065 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
2066 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
2067 this.automaticTransactionGenerator
?.started
2069 this.automaticTransactionGenerator
.stop();
2072 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2073 this.getAutoReconnectMaxRetries() === -1
2075 this.autoReconnectRetryCount
++;
2076 const reconnectDelay
= this.getReconnectExponentialDelay()
2077 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2078 : this.getConnectionTimeout() * 1000;
2079 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
2081 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2084 )}ms, timeout ${reconnectTimeout}ms`
2086 await Utils
.sleep(reconnectDelay
);
2089 ' WebSocket: reconnecting try #' +
2090 this.autoReconnectRetryCount
.toString()
2092 this.openWSConnection(
2093 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
2096 this.wsConnectionRestarted
= true;
2097 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2099 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2100 this.autoReconnectRetryCount
2101 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2106 private initializeConnectorStatus(connectorId
: number): void {
2107 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2108 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2109 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2110 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2111 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2112 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;