1 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/Responses';
2 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
3 import ChargingStationTemplate
, { CurrentType
, PowerUnits
, Voltage
} from
'../types/ChargingStationTemplate';
4 import { ConnectorPhaseRotation
, StandardParametersKey
, SupportedFeatureProfiles
} from
'../types/ocpp/Configuration';
5 import Connectors
, { Connector
, SampledValueTemplate
} from
'../types/Connectors';
6 import { MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
7 import Requests
, { AvailabilityType
, BootNotificationRequest
, IncomingRequest
, IncomingRequestCommand
} from
'../types/ocpp/Requests';
8 import WebSocket
, { ClientOptions
, MessageEvent
} from
'ws';
10 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
11 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
12 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
13 import ChargingStationInfo from
'../types/ChargingStationInfo';
14 import { ClientRequestArgs
} from
'http';
15 import Configuration from
'../utils/Configuration';
16 import Constants from
'../utils/Constants';
17 import { ErrorType
} from
'../types/ocpp/ErrorType';
18 import FileUtils from
'../utils/FileUtils';
19 import { MessageType
} from
'../types/ocpp/MessageType';
20 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
21 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
22 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
23 import OCPPError from
'./ocpp/OCPPError';
24 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
25 import OCPPRequestService from
'./ocpp/OCPPRequestService';
26 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
27 import PerformanceStatistics from
'../performance/PerformanceStatistics';
28 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
29 import { URL
} from
'url';
30 import Utils from
'../utils/Utils';
31 import { WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
32 import crypto from
'crypto';
34 import logger from
'../utils/Logger';
35 import path from
'path';
37 export default class ChargingStation
{
38 public stationTemplateFile
: string;
39 public authorizedTags
: string[];
40 public stationInfo
!: ChargingStationInfo
;
41 public connectors
: Connectors
;
42 public configuration
!: ChargingStationConfiguration
;
43 public hasStopped
: boolean;
44 public wsConnection
!: WebSocket
;
45 public requests
: Requests
;
46 public messageQueue
: string[];
47 public performanceStatistics
!: PerformanceStatistics
;
48 public heartbeatSetInterval
!: NodeJS
.Timeout
;
49 public ocppIncomingRequestService
!: OCPPIncomingRequestService
;
50 public ocppRequestService
!: OCPPRequestService
;
51 private index
: number;
52 private bootNotificationRequest
!: BootNotificationRequest
;
53 private bootNotificationResponse
!: BootNotificationResponse
| null;
54 private connectorsConfigurationHash
!: string;
55 private wsConnectionUrl
!: URL
;
56 private hasSocketRestarted
: boolean;
57 private autoReconnectRetryCount
: number;
58 private automaticTransactionGeneration
!: AutomaticTransactionGenerator
;
59 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
61 constructor(index
: number, stationTemplateFile
: string) {
63 this.stationTemplateFile
= stationTemplateFile
;
64 this.connectors
= {} as Connectors
;
67 this.hasStopped
= false;
68 this.hasSocketRestarted
= false;
69 this.autoReconnectRetryCount
= 0;
71 this.requests
= {} as Requests
;
72 this.messageQueue
= [] as string[];
74 this.authorizedTags
= this.getAuthorizedTags();
77 public logPrefix(): string {
78 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
81 public getBootNotificationRequest(): BootNotificationRequest
{
82 return this.bootNotificationRequest
;
85 public getRandomTagId(): string {
86 const index
= Math.floor(Math.random() * this.authorizedTags
.length
);
87 return this.authorizedTags
[index
];
90 public hasAuthorizedTags(): boolean {
91 return !Utils
.isEmptyArray(this.authorizedTags
);
94 public getEnableStatistics(): boolean | undefined {
95 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
98 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
99 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
102 public getNumberOfPhases(): number | undefined {
103 switch (this.getCurrentOutType()) {
105 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
111 public isWebSocketConnectionOpened(): boolean {
112 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
;
115 public isRegistered(): boolean {
116 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
119 public isChargingStationAvailable(): boolean {
120 return this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
;
123 public isConnectorAvailable(id
: number): boolean {
124 return this.getConnector(id
).availability
=== AvailabilityType
.OPERATIVE
;
127 public getConnector(id
: number): Connector
{
128 return this.connectors
[id
];
131 public getCurrentOutType(): CurrentType
| undefined {
132 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
135 public getVoltageOut(): number | undefined {
136 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
137 let defaultVoltageOut
: number;
138 switch (this.getCurrentOutType()) {
140 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
143 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
146 logger
.error(errMsg
);
147 throw new Error(errMsg
);
149 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
152 public getTransactionIdTag(transactionId
: number): string | undefined {
153 for (const connector
in this.connectors
) {
154 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
155 return this.getConnector(Utils
.convertToInt(connector
)).transactionIdTag
;
160 public getOutOfOrderEndMeterValues(): boolean {
161 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
164 public getBeginEndMeterValues(): boolean {
165 return this.stationInfo
.beginEndMeterValues
?? false;
168 public getMeteringPerTransaction(): boolean {
169 return this.stationInfo
.meteringPerTransaction
?? true;
172 public getTransactionDataMeterValues(): boolean {
173 return this.stationInfo
.transactionDataMeterValues
?? false;
176 public getMainVoltageMeterValues(): boolean {
177 return this.stationInfo
.mainVoltageMeterValues
?? true;
180 public getPhaseLineToLineVoltageMeterValues(): boolean {
181 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
184 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
185 if (this.getMeteringPerTransaction()) {
186 for (const connector
in this.connectors
) {
187 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
188 return this.getConnector(Utils
.convertToInt(connector
)).transactionEnergyActiveImportRegisterValue
;
192 for (const connector
in this.connectors
) {
193 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
194 return this.getConnector(Utils
.convertToInt(connector
)).energyActiveImportRegisterValue
;
199 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
200 if (this.getMeteringPerTransaction()) {
201 return this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
;
203 return this.getConnector(connectorId
).energyActiveImportRegisterValue
;
206 public getAuthorizeRemoteTxRequests(): boolean {
207 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
208 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
211 public getLocalAuthListEnabled(): boolean {
212 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
213 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
216 public restartWebSocketPing(): void {
217 // Stop WebSocket ping
218 this.stopWebSocketPing();
219 // Start WebSocket ping
220 this.startWebSocketPing();
223 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
224 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
225 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
226 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
229 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
230 logger.debug(`${this.logPrefix()} Trying to get MeterValues measurand ${measurand} ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId} not found in '${StandardParametersKey.MeterValuesSampledData}' OCPP parameter`);
233 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnector(connectorId
).MeterValues
;
234 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
235 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
236 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
238 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
239 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
240 return sampledValueTemplates[index];
241 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
242 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
243 return sampledValueTemplates[index];
244 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
245 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
246 return sampledValueTemplates[index];
249 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
250 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand ${measurand}
in template on connectorId ${connectorId}
`;
251 logger.error(errorMsg);
252 throw new Error(errorMsg);
254 logger.debug(`${this.logPrefix()} No MeterValues
for measurand ${measurand} ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
257 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
258 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
261 public startHeartbeat(): void {
262 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
263 // eslint-disable-next-line @typescript-eslint/no-misused-promises
264 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
265 await this.ocppRequestService
.sendHeartbeat();
266 }, this.getHeartbeatInterval());
267 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
268 } else if (this.heartbeatSetInterval
) {
269 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
271 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
275 public restartHeartbeat(): void {
277 this.stopHeartbeat();
279 this.startHeartbeat();
282 public startMeterValues(connectorId
: number, interval
: number): void {
283 if (connectorId
=== 0) {
284 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
287 if (!this.getConnector(connectorId
)) {
288 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
291 if (!this.getConnector(connectorId
)?.transactionStarted
) {
292 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
294 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
295 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
299 // eslint-disable-next-line @typescript-eslint/no-misused-promises
300 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
301 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
);
304 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
308 public start(): void {
309 if (this.getEnableStatistics()) {
310 this.performanceStatistics
.start();
312 this.openWSConnection();
313 // Monitor authorization file
314 this.startAuthorizationFileMonitoring();
315 // Monitor station template file
316 this.startStationTemplateFileMonitoring();
317 // Handle Socket incoming messages
318 this.wsConnection
.on('message', this.onMessage
.bind(this));
319 // Handle Socket error
320 this.wsConnection
.on('error', this.onError
.bind(this));
321 // Handle Socket close
322 this.wsConnection
.on('close', this.onClose
.bind(this));
323 // Handle Socket opening connection
324 this.wsConnection
.on('open', this.onOpen
.bind(this));
325 // Handle Socket ping
326 this.wsConnection
.on('ping', this.onPing
.bind(this));
327 // Handle Socket pong
328 this.wsConnection
.on('pong', this.onPong
.bind(this));
331 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
332 // Stop message sequence
333 await this.stopMessageSequence(reason
);
334 for (const connector
in this.connectors
) {
335 if (Utils
.convertToInt(connector
) > 0) {
336 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
337 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.UNAVAILABLE
;
340 if (this.isWebSocketConnectionOpened()) {
341 this.wsConnection
.close();
343 if (this.getEnableStatistics()) {
344 this.performanceStatistics
.stop();
346 this.bootNotificationResponse
= null;
347 this.hasStopped
= true;
350 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
351 return this.configuration
.configurationKey
.find((configElement
) => {
352 if (caseInsensitive
) {
353 return configElement
.key
.toLowerCase() === key
.toLowerCase();
355 return configElement
.key
=== key
;
359 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
360 const keyFound
= this.getConfigurationKey(key
);
362 this.configuration
.configurationKey
.push({
370 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
374 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
375 const keyFound
= this.getConfigurationKey(key
);
377 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
378 this.configuration
.configurationKey
[keyIndex
].value
= value
;
380 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
384 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
385 let cpReplaced
= false;
386 if (!Utils
.isEmptyArray(this.getConnector(connectorId
).chargingProfiles
)) {
387 this.getConnector(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
388 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
389 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
390 this.getConnector(connectorId
).chargingProfiles
[index
] = cp
;
395 !cpReplaced
&& this.getConnector(connectorId
).chargingProfiles
?.push(cp
);
398 public resetTransactionOnConnector(connectorId
: number): void {
399 this.getConnector(connectorId
).authorized
= false;
400 this.getConnector(connectorId
).transactionStarted
= false;
401 delete this.getConnector(connectorId
).authorizeIdTag
;
402 delete this.getConnector(connectorId
).transactionId
;
403 delete this.getConnector(connectorId
).transactionIdTag
;
404 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
405 delete this.getConnector(connectorId
).transactionBeginMeterValue
;
406 this.stopMeterValues(connectorId
);
409 public addToMessageQueue(message
: string): void {
411 // Handle dups in message queue
412 for (const bufferedMessage
of this.messageQueue
) {
413 // Message already in the queue
414 if (message
=== bufferedMessage
) {
421 this.messageQueue
.push(message
);
425 private flushMessageQueue() {
426 if (!Utils
.isEmptyArray(this.messageQueue
)) {
427 this.messageQueue
.forEach((message
, index
) => {
428 this.messageQueue
.splice(index
, 1);
429 // TODO: evaluate the need to track performance
430 this.wsConnection
.send(message
);
435 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
436 // In case of multiple instances: add instance index to charging station id
437 let instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
438 instanceIndex
= instanceIndex
> 0 ? instanceIndex
: '';
439 const idSuffix
= stationTemplate
.nameSuffix
?? '';
440 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
443 private buildStationInfo(): ChargingStationInfo
{
444 let stationTemplateFromFile
: ChargingStationTemplate
;
446 // Load template file
447 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
448 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
449 fs
.closeSync(fileDescriptor
);
451 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
453 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
454 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
455 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
456 const powerArrayRandomIndex
= Math.floor(Math.random() * stationTemplateFromFile
.power
.length
);
457 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
458 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
459 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
461 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
462 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
463 ? stationTemplateFromFile
.power
* 1000
464 : stationTemplateFromFile
.power
;
466 delete stationInfo
.power
;
467 delete stationInfo
.powerUnit
;
468 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
469 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
473 private getOCPPVersion(): OCPPVersion
{
474 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
477 private handleUnsupportedVersion(version
: OCPPVersion
) {
478 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
479 logger
.error(errMsg
);
480 throw new Error(errMsg
);
483 private initialize(): void {
484 this.stationInfo
= this.buildStationInfo();
485 this.bootNotificationRequest
= {
486 chargePointModel
: this.stationInfo
.chargePointModel
,
487 chargePointVendor
: this.stationInfo
.chargePointVendor
,
488 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
489 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
491 this.configuration
= this.getTemplateChargingStationConfiguration();
492 this.wsConnectionUrl
= new URL(this.getSupervisionURL().href
+ '/' + this.stationInfo
.chargingStationId
);
493 // Build connectors if needed
494 const maxConnectors
= this.getMaxNumberOfConnectors();
495 if (maxConnectors
<= 0) {
496 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
498 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
499 if (templateMaxConnectors
<= 0) {
500 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
502 if (!this.stationInfo
.Connectors
[0]) {
503 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
506 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
507 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
508 this.stationInfo
.randomConnectors
= true;
510 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
511 // FIXME: Handle shrinking the number of connectors
512 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
513 this.connectorsConfigurationHash
= connectorsConfigHash
;
514 // Add connector Id 0
515 let lastConnector
= '0';
516 for (lastConnector
in this.stationInfo
.Connectors
) {
517 if (Utils
.convertToInt(lastConnector
) === 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
518 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
519 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
520 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
521 this.connectors
[lastConnector
].chargingProfiles
= [];
525 // Generate all connectors
526 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
527 for (let index
= 1; index
<= maxConnectors
; index
++) {
528 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
529 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorId
]);
530 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
531 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
532 this.connectors
[index
].chargingProfiles
= [];
537 // Avoid duplication of connectors related information
538 delete this.stationInfo
.Connectors
;
539 // Initialize transaction attributes on connectors
540 for (const connector
in this.connectors
) {
541 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
542 this.initTransactionAttributesOnConnector(Utils
.convertToInt(connector
));
545 switch (this.getOCPPVersion()) {
546 case OCPPVersion
.VERSION_16
:
547 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
548 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
551 this.handleUnsupportedVersion(this.getOCPPVersion());
555 this.initOCPPParameters();
556 if (this.stationInfo
.autoRegister
) {
557 this.bootNotificationResponse
= {
558 currentTime
: new Date().toISOString(),
559 interval
: this.getHeartbeatInterval() / 1000,
560 status: RegistrationStatus
.ACCEPTED
563 this.stationInfo
.powerDivider
= this.getPowerDivider();
564 if (this.getEnableStatistics()) {
565 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
569 private initOCPPParameters(): void {
570 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
571 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
573 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
574 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
575 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
577 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
578 const connectorPhaseRotation
= [];
579 for (const connector
in this.connectors
) {
581 if (Utils
.convertToInt(connector
) === 0 && this.getNumberOfPhases() === 0) {
582 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
583 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 0) {
584 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
586 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 1) {
587 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
588 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 3) {
589 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
592 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
594 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
595 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
597 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
598 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
599 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
601 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
602 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
606 private async onOpen(): Promise
<void> {
607 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
608 if (!this.isRegistered()) {
609 // Send BootNotification
610 let registrationRetryCount
= 0;
612 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
613 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
614 if (!this.isRegistered()) {
615 registrationRetryCount
++;
616 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
618 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
620 if (this.isRegistered()) {
621 await this.startMessageSequence();
622 this.hasStopped
&& (this.hasStopped
= false);
623 if (this.hasSocketRestarted
&& this.isWebSocketConnectionOpened()) {
624 this.flushMessageQueue();
627 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
629 this.autoReconnectRetryCount
= 0;
630 this.hasSocketRestarted
= false;
633 private async onClose(closeEvent
: any): Promise
<void> {
634 switch (closeEvent
) {
635 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
636 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
637 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
638 this.autoReconnectRetryCount
= 0;
640 default: // Abnormal close
641 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
642 await this.reconnect(closeEvent
);
647 private async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
648 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
649 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
650 let rejectCallback
: (error
: OCPPError
) => void;
651 let requestPayload
: Record
<string, unknown
>;
654 const request
= JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
655 if (Utils
.isIterable(request
)) {
657 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
659 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
661 // Check the Type of message
662 switch (messageType
) {
664 case MessageType
.CALL_MESSAGE
:
665 if (this.getEnableStatistics()) {
666 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
669 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
672 case MessageType
.CALL_RESULT_MESSAGE
:
674 if (Utils
.isIterable(this.requests
[messageId
])) {
675 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
677 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Response request for message id ${messageId} is not iterable`, commandName
);
679 if (!responseCallback
) {
681 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response request for unknown message id ${messageId}`, commandName
);
683 delete this.requests
[messageId
];
684 responseCallback(commandName
, requestPayload
);
687 case MessageType
.CALL_ERROR_MESSAGE
:
688 if (!this.requests
[messageId
]) {
690 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error request for unknown message id ${messageId}`);
692 if (Utils
.isIterable(this.requests
[messageId
])) {
693 [, rejectCallback
] = this.requests
[messageId
];
695 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Error request for message id ${messageId} is not iterable`);
697 delete this.requests
[messageId
];
698 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), null, errorDetails
));
702 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
703 logger
.error(errMsg
);
704 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
708 logger
.error('%s Incoming request message %j processing error %j on content type %j', this.logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
710 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
714 private onPing(): void {
715 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
718 private onPong(): void {
719 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
722 private async onError(errorEvent
: any): Promise
<void> {
723 logger
.error(this.logPrefix() + ' Socket error: %j', errorEvent
);
724 // switch (errorEvent.code) {
725 // case 'ECONNREFUSED':
726 // await this._reconnect(errorEvent);
731 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
732 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
735 private getAuthorizationFile(): string | undefined {
736 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
739 private getAuthorizedTags(): string[] {
740 let authorizedTags
: string[] = [];
741 const authorizationFile
= this.getAuthorizationFile();
742 if (authorizationFile
) {
744 // Load authorization file
745 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
746 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
747 fs
.closeSync(fileDescriptor
);
749 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
752 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
754 return authorizedTags
;
757 private getUseConnectorId0(): boolean | undefined {
758 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
761 private getNumberOfRunningTransactions(): number {
763 for (const connector
in this.connectors
) {
764 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
772 private getConnectionTimeout(): number | undefined {
773 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
774 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
776 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
779 // -1 for unlimited, 0 for disabling
780 private getAutoReconnectMaxRetries(): number | undefined {
781 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
782 return this.stationInfo
.autoReconnectMaxRetries
;
784 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
785 return Configuration
.getAutoReconnectMaxRetries();
791 private getRegistrationMaxRetries(): number | undefined {
792 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
793 return this.stationInfo
.registrationMaxRetries
;
798 private getPowerDivider(): number {
799 let powerDivider
= this.getNumberOfConnectors();
800 if (this.stationInfo
.powerSharedByConnectors
) {
801 powerDivider
= this.getNumberOfRunningTransactions();
806 private getTemplateMaxNumberOfConnectors(): number {
807 return Object.keys(this.stationInfo
.Connectors
).length
;
810 private getMaxNumberOfConnectors(): number {
811 let maxConnectors
= 0;
812 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
813 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
814 // Distribute evenly the number of connectors
815 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
816 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
817 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
819 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
821 return maxConnectors
;
824 private getNumberOfConnectors(): number {
825 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
828 private async startMessageSequence(): Promise
<void> {
829 // Start WebSocket ping
830 this.startWebSocketPing();
832 this.startHeartbeat();
833 // Initialize connectors status
834 for (const connector
in this.connectors
) {
835 if (Utils
.convertToInt(connector
) === 0) {
837 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
838 // Send status in template at startup
839 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
840 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
841 } else if (this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
842 // Send status in template after reset
843 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
844 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
845 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
846 // Send previous status at template reload
847 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
849 // Send default status
850 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
851 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
855 this.startAutomaticTransactionGenerator();
858 private startAutomaticTransactionGenerator() {
859 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
860 if (!this.automaticTransactionGeneration
) {
861 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
863 if (this.automaticTransactionGeneration
.timeToStop
) {
864 // The ATG might sleep
865 void this.automaticTransactionGeneration
.start();
870 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
871 // Stop WebSocket ping
872 this.stopWebSocketPing();
874 this.stopHeartbeat();
876 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
877 this.automaticTransactionGeneration
&&
878 !this.automaticTransactionGeneration
.timeToStop
) {
879 await this.automaticTransactionGeneration
.stop(reason
);
881 for (const connector
in this.connectors
) {
882 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
883 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
884 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
885 this.getTransactionIdTag(transactionId
), reason
);
891 private startWebSocketPing(): void {
892 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
893 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
895 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
896 this.webSocketPingSetInterval
= setInterval(() => {
897 if (this.isWebSocketConnectionOpened()) {
898 this.wsConnection
.ping((): void => { });
900 }, webSocketPingInterval
* 1000);
901 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
902 } else if (this.webSocketPingSetInterval
) {
903 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
905 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
909 private stopWebSocketPing(): void {
910 if (this.webSocketPingSetInterval
) {
911 clearInterval(this.webSocketPingSetInterval
);
915 private getSupervisionURL(): URL
{
916 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
918 if (!Utils
.isEmptyArray(supervisionUrls
)) {
919 if (Configuration
.getDistributeStationsToTenantsEqually()) {
920 indexUrl
= this.index
% supervisionUrls
.length
;
923 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
925 return new URL(supervisionUrls
[indexUrl
]);
927 return new URL(supervisionUrls
as string);
930 private getHeartbeatInterval(): number | undefined {
931 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
932 if (HeartbeatInterval
) {
933 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
935 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
936 if (HeartBeatInterval
) {
937 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
939 !this.stationInfo
.autoRegister
&& logger
.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
940 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
943 private stopHeartbeat(): void {
944 if (this.heartbeatSetInterval
) {
945 clearInterval(this.heartbeatSetInterval
);
949 private openWSConnection(options
?: ClientOptions
& ClientRequestArgs
, forceCloseOpened
= false): void {
950 options
= options
?? {};
951 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
952 if (!Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) && !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)) {
953 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
955 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
956 this.wsConnection
.close();
959 switch (this.getOCPPVersion()) {
960 case OCPPVersion
.VERSION_16
:
961 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
964 this.handleUnsupportedVersion(this.getOCPPVersion());
967 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
968 logger
.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString());
971 private stopMeterValues(connectorId
: number) {
972 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
973 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
977 private startAuthorizationFileMonitoring(): void {
978 const authorizationFile
= this.getAuthorizationFile();
979 if (authorizationFile
) {
981 fs
.watch(authorizationFile
).on('change', () => {
983 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
984 // Initialize authorizedTags
985 this.authorizedTags
= this.getAuthorizedTags();
987 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
991 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
994 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
998 private startStationTemplateFileMonitoring(): void {
1000 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1001 fs
.watch(this.stationTemplateFile
).on('change', async (): Promise
<void> => {
1003 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
1007 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1008 this.automaticTransactionGeneration
) {
1009 await this.automaticTransactionGeneration
.stop();
1011 this.startAutomaticTransactionGenerator();
1012 if (this.getEnableStatistics()) {
1013 this.performanceStatistics
.restart();
1015 this.performanceStatistics
.stop();
1017 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1019 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
1023 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
1027 private getReconnectExponentialDelay(): boolean | undefined {
1028 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
1031 private async reconnect(error
: unknown
): Promise
<void> {
1032 // Stop WebSocket ping
1033 this.stopWebSocketPing();
1035 this.stopHeartbeat();
1036 // Stop the ATG if needed
1037 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1038 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1039 this.automaticTransactionGeneration
&&
1040 !this.automaticTransactionGeneration
.timeToStop
) {
1041 await this.automaticTransactionGeneration
.stop();
1043 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1044 this.autoReconnectRetryCount
++;
1045 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
1046 logger
.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
1047 await Utils
.sleep(reconnectDelay
);
1048 logger
.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
1049 this.openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
1050 this.hasSocketRestarted
= true;
1051 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1052 logger
.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1056 private initTransactionAttributesOnConnector(connectorId
: number): void {
1057 this.getConnector(connectorId
).authorized
= false;
1058 this.getConnector(connectorId
).transactionStarted
= false;
1059 this.getConnector(connectorId
).energyActiveImportRegisterValue
= 0;
1060 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;