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 FileUtils from
'../utils/FileUtils';
18 import { MessageType
} from
'../types/ocpp/MessageType';
19 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
20 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
21 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
22 import OCPPError from
'./OCPPError';
23 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
24 import OCPPRequestService from
'./ocpp/OCPPRequestService';
25 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
26 import PerformanceStatistics from
'../utils/PerformanceStatistics';
27 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
28 import { URL
} from
'url';
29 import Utils from
'../utils/Utils';
30 import { WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
31 import crypto from
'crypto';
33 import logger from
'../utils/Logger';
34 import path from
'path';
36 export default class ChargingStation
{
37 public stationTemplateFile
: string;
38 public authorizedTags
: string[];
39 public stationInfo
!: ChargingStationInfo
;
40 public connectors
: Connectors
;
41 public configuration
!: ChargingStationConfiguration
;
42 public hasStopped
: boolean;
43 public wsConnection
!: WebSocket
;
44 public requests
: Requests
;
45 public messageQueue
: string[];
46 public performanceStatistics
!: PerformanceStatistics
;
47 public heartbeatSetInterval
!: NodeJS
.Timeout
;
48 public ocppIncomingRequestService
!: OCPPIncomingRequestService
;
49 public ocppRequestService
!: OCPPRequestService
;
50 private index
: number;
51 private bootNotificationRequest
!: BootNotificationRequest
;
52 private bootNotificationResponse
!: BootNotificationResponse
| null;
53 private connectorsConfigurationHash
!: string;
54 private wsConnectionUrl
!: URL
;
55 private hasSocketRestarted
: boolean;
56 private autoReconnectRetryCount
: number;
57 private automaticTransactionGeneration
!: AutomaticTransactionGenerator
;
58 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
60 constructor(index
: number, stationTemplateFile
: string) {
62 this.stationTemplateFile
= stationTemplateFile
;
63 this.connectors
= {} as Connectors
;
66 this.hasStopped
= false;
67 this.hasSocketRestarted
= false;
68 this.autoReconnectRetryCount
= 0;
70 this.requests
= {} as Requests
;
71 this.messageQueue
= [] as string[];
73 this.authorizedTags
= this.getAuthorizedTags();
76 public logPrefix(): string {
77 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
80 public getRandomTagId(): string {
81 const index
= Math.floor(Math.random() * this.authorizedTags
.length
);
82 return this.authorizedTags
[index
];
85 public hasAuthorizedTags(): boolean {
86 return !Utils
.isEmptyArray(this.authorizedTags
);
89 public getEnableStatistics(): boolean | undefined {
90 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
93 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
94 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
97 public getNumberOfPhases(): number | undefined {
98 switch (this.getCurrentOutType()) {
100 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
106 public isWebSocketConnectionOpened(): boolean {
107 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
;
110 public isRegistered(): boolean {
111 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
114 public isChargingStationAvailable(): boolean {
115 return this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
;
118 public isConnectorAvailable(id
: number): boolean {
119 return this.getConnector(id
).availability
=== AvailabilityType
.OPERATIVE
;
122 public getConnector(id
: number): Connector
{
123 return this.connectors
[id
];
126 public getCurrentOutType(): CurrentType
| undefined {
127 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
130 public getVoltageOut(): number | undefined {
131 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
132 let defaultVoltageOut
: number;
133 switch (this.getCurrentOutType()) {
135 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
138 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
141 logger
.error(errMsg
);
142 throw new Error(errMsg
);
144 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
147 public getTransactionIdTag(transactionId
: number): string | undefined {
148 for (const connector
in this.connectors
) {
149 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
150 return this.getConnector(Utils
.convertToInt(connector
)).transactionIdTag
;
155 public getOutOfOrderEndMeterValues(): boolean {
156 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
159 public getBeginEndMeterValues(): boolean {
160 return this.stationInfo
.beginEndMeterValues
?? false;
163 public getMeteringPerTransaction(): boolean {
164 return this.stationInfo
.meteringPerTransaction
?? true;
167 public getTransactionDataMeterValues(): boolean {
168 return this.stationInfo
.transactionDataMeterValues
?? false;
171 public getMainVoltageMeterValues(): boolean {
172 return this.stationInfo
.mainVoltageMeterValues
?? true;
175 public getPhaseLineToLineVoltageMeterValues(): boolean {
176 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
179 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
180 if (this.getMeteringPerTransaction()) {
181 for (const connector
in this.connectors
) {
182 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
183 return this.getConnector(Utils
.convertToInt(connector
)).transactionEnergyActiveImportRegisterValue
;
187 for (const connector
in this.connectors
) {
188 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
189 return this.getConnector(Utils
.convertToInt(connector
)).energyActiveImportRegisterValue
;
194 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
195 if (this.getMeteringPerTransaction()) {
196 return this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
;
198 return this.getConnector(connectorId
).energyActiveImportRegisterValue
;
201 public getAuthorizeRemoteTxRequests(): boolean {
202 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
203 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
206 public getLocalAuthListEnabled(): boolean {
207 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
208 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
211 public restartWebSocketPing(): void {
212 // Stop WebSocket ping
213 this.stopWebSocketPing();
214 // Start WebSocket ping
215 this.startWebSocketPing();
218 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
219 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
220 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
221 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
224 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
225 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`);
228 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnector(connectorId
).MeterValues
;
229 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
230 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
231 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
233 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
234 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
235 return sampledValueTemplates[index];
236 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
237 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
238 return sampledValueTemplates[index];
239 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
240 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
241 return sampledValueTemplates[index];
244 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
245 logger.error(`${this.logPrefix()} Missing MeterValues
for default measurand ${measurand}
in template on connectorId ${connectorId}
`);
247 logger.debug(`${this.logPrefix()} No MeterValues
for measurand ${measurand} ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
250 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
251 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
254 public startHeartbeat(): void {
255 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
256 // eslint-disable-next-line @typescript-eslint/no-misused-promises
257 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
258 await this.ocppRequestService
.sendHeartbeat();
259 }, this.getHeartbeatInterval());
260 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
261 } else if (this.heartbeatSetInterval
) {
262 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
264 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
268 public restartHeartbeat(): void {
270 this.stopHeartbeat();
272 this.startHeartbeat();
275 public startMeterValues(connectorId
: number, interval
: number): void {
276 if (connectorId
=== 0) {
277 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
280 if (!this.getConnector(connectorId
)) {
281 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
284 if (!this.getConnector(connectorId
)?.transactionStarted
) {
285 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
287 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
288 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
292 // eslint-disable-next-line @typescript-eslint/no-misused-promises
293 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
294 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
);
297 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
301 public start(): void {
302 if (this.getEnableStatistics()) {
303 this.performanceStatistics
.start();
305 this.openWSConnection();
306 // Monitor authorization file
307 this.startAuthorizationFileMonitoring();
308 // Monitor station template file
309 this.startStationTemplateFileMonitoring();
310 // Handle Socket incoming messages
311 this.wsConnection
.on('message', this.onMessage
.bind(this));
312 // Handle Socket error
313 this.wsConnection
.on('error', this.onError
.bind(this));
314 // Handle Socket close
315 this.wsConnection
.on('close', this.onClose
.bind(this));
316 // Handle Socket opening connection
317 this.wsConnection
.on('open', this.onOpen
.bind(this));
318 // Handle Socket ping
319 this.wsConnection
.on('ping', this.onPing
.bind(this));
320 // Handle Socket pong
321 this.wsConnection
.on('pong', this.onPong
.bind(this));
324 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
325 // Stop message sequence
326 await this.stopMessageSequence(reason
);
327 for (const connector
in this.connectors
) {
328 if (Utils
.convertToInt(connector
) > 0) {
329 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
330 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.UNAVAILABLE
;
333 if (this.isWebSocketConnectionOpened()) {
334 this.wsConnection
.close();
336 if (this.getEnableStatistics()) {
337 this.performanceStatistics
.stop();
339 this.bootNotificationResponse
= null;
340 this.hasStopped
= true;
343 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
344 return this.configuration
.configurationKey
.find((configElement
) => {
345 if (caseInsensitive
) {
346 return configElement
.key
.toLowerCase() === key
.toLowerCase();
348 return configElement
.key
=== key
;
352 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
353 const keyFound
= this.getConfigurationKey(key
);
355 this.configuration
.configurationKey
.push({
363 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
367 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
368 const keyFound
= this.getConfigurationKey(key
);
370 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
371 this.configuration
.configurationKey
[keyIndex
].value
= value
;
373 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
377 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
378 let cpReplaced
= false;
379 if (!Utils
.isEmptyArray(this.getConnector(connectorId
).chargingProfiles
)) {
380 this.getConnector(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
381 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
382 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
383 this.getConnector(connectorId
).chargingProfiles
[index
] = cp
;
388 !cpReplaced
&& this.getConnector(connectorId
).chargingProfiles
?.push(cp
);
391 public resetTransactionOnConnector(connectorId
: number): void {
392 this.getConnector(connectorId
).authorized
= false;
393 this.getConnector(connectorId
).transactionStarted
= false;
394 delete this.getConnector(connectorId
).authorizeIdTag
;
395 delete this.getConnector(connectorId
).transactionId
;
396 delete this.getConnector(connectorId
).transactionIdTag
;
397 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
398 delete this.getConnector(connectorId
).transactionBeginMeterValue
;
399 this.stopMeterValues(connectorId
);
402 public addToMessageQueue(message
: string): void {
404 // Handle dups in message queue
405 for (const bufferedMessage
of this.messageQueue
) {
406 // Message already in the queue
407 if (message
=== bufferedMessage
) {
414 this.messageQueue
.push(message
);
418 private flushMessageQueue() {
419 if (!Utils
.isEmptyArray(this.messageQueue
)) {
420 this.messageQueue
.forEach((message
, index
) => {
421 this.messageQueue
.splice(index
, 1);
422 // TODO: evaluate the need to track performance
423 this.wsConnection
.send(message
);
428 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
429 // In case of multiple instances: add instance index to charging station id
430 let instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
431 instanceIndex
= instanceIndex
> 0 ? instanceIndex
: '';
432 const idSuffix
= stationTemplate
.nameSuffix
?? '';
433 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
436 private buildStationInfo(): ChargingStationInfo
{
437 let stationTemplateFromFile
: ChargingStationTemplate
;
439 // Load template file
440 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
441 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
442 fs
.closeSync(fileDescriptor
);
444 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
446 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
447 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
448 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
449 const powerArrayRandomIndex
= Math.floor(Math.random() * stationTemplateFromFile
.power
.length
);
450 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
451 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
452 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
454 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
455 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
456 ? stationTemplateFromFile
.power
* 1000
457 : stationTemplateFromFile
.power
;
459 delete stationInfo
.power
;
460 delete stationInfo
.powerUnit
;
461 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
462 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
466 private getOCPPVersion(): OCPPVersion
{
467 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
470 private handleUnsupportedVersion(version
: OCPPVersion
) {
471 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
472 logger
.error(errMsg
);
473 throw new Error(errMsg
);
476 private initialize(): void {
477 this.stationInfo
= this.buildStationInfo();
478 this.bootNotificationRequest
= {
479 chargePointModel
: this.stationInfo
.chargePointModel
,
480 chargePointVendor
: this.stationInfo
.chargePointVendor
,
481 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
482 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
484 this.configuration
= this.getTemplateChargingStationConfiguration();
485 this.wsConnectionUrl
= new URL(this.getSupervisionURL().href
+ '/' + this.stationInfo
.chargingStationId
);
486 // Build connectors if needed
487 const maxConnectors
= this.getMaxNumberOfConnectors();
488 if (maxConnectors
<= 0) {
489 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
491 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
492 if (templateMaxConnectors
<= 0) {
493 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
495 if (!this.stationInfo
.Connectors
[0]) {
496 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
499 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
500 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
501 this.stationInfo
.randomConnectors
= true;
503 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
504 // FIXME: Handle shrinking the number of connectors
505 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
506 this.connectorsConfigurationHash
= connectorsConfigHash
;
507 // Add connector Id 0
508 let lastConnector
= '0';
509 for (lastConnector
in this.stationInfo
.Connectors
) {
510 if (Utils
.convertToInt(lastConnector
) === 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
511 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
512 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
513 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
514 this.connectors
[lastConnector
].chargingProfiles
= [];
518 // Generate all connectors
519 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
520 for (let index
= 1; index
<= maxConnectors
; index
++) {
521 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
522 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorId
]);
523 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
524 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
525 this.connectors
[index
].chargingProfiles
= [];
530 // Avoid duplication of connectors related information
531 delete this.stationInfo
.Connectors
;
532 // Initialize transaction attributes on connectors
533 for (const connector
in this.connectors
) {
534 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
535 this.initTransactionAttributesOnConnector(Utils
.convertToInt(connector
));
538 switch (this.getOCPPVersion()) {
539 case OCPPVersion
.VERSION_16
:
540 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
541 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
544 this.handleUnsupportedVersion(this.getOCPPVersion());
548 this.initOCPPParameters();
549 if (this.stationInfo
.autoRegister
) {
550 this.bootNotificationResponse
= {
551 currentTime
: new Date().toISOString(),
552 interval
: this.getHeartbeatInterval() / 1000,
553 status: RegistrationStatus
.ACCEPTED
556 this.stationInfo
.powerDivider
= this.getPowerDivider();
557 if (this.getEnableStatistics()) {
558 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
);
562 private initOCPPParameters(): void {
563 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
564 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
566 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
567 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
568 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
570 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
571 const connectorPhaseRotation
= [];
572 for (const connector
in this.connectors
) {
574 if (Utils
.convertToInt(connector
) === 0 && this.getNumberOfPhases() === 0) {
575 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
576 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 0) {
577 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
579 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 1) {
580 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
581 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 3) {
582 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
585 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
587 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
588 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
590 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
591 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
592 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
594 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
595 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
599 private async onOpen(): Promise
<void> {
600 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
601 if (!this.isRegistered()) {
602 // Send BootNotification
603 let registrationRetryCount
= 0;
605 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
606 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
607 if (!this.isRegistered()) {
608 registrationRetryCount
++;
609 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
611 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
613 if (this.isRegistered()) {
614 await this.startMessageSequence();
615 this.hasStopped
&& (this.hasStopped
= false);
616 if (this.hasSocketRestarted
&& this.isWebSocketConnectionOpened()) {
617 this.flushMessageQueue();
620 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
622 this.autoReconnectRetryCount
= 0;
623 this.hasSocketRestarted
= false;
626 private async onClose(closeEvent
: any): Promise
<void> {
627 switch (closeEvent
) {
628 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
629 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
630 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
631 this.autoReconnectRetryCount
= 0;
633 default: // Abnormal close
634 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
635 await this.reconnect(closeEvent
);
640 private async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
641 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
642 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
643 let rejectCallback
: (error
: OCPPError
) => void;
644 let requestPayload
: Record
<string, unknown
>;
647 const request
= JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
648 if (Utils
.isIterable(request
)) {
650 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
652 throw new Error('Incoming request is not iterable');
654 // Check the Type of message
655 switch (messageType
) {
657 case MessageType
.CALL_MESSAGE
:
658 if (this.getEnableStatistics()) {
659 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
662 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
665 case MessageType
.CALL_RESULT_MESSAGE
:
667 if (Utils
.isIterable(this.requests
[messageId
])) {
668 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
670 throw new Error(`Response request for message id ${messageId} is not iterable`);
672 if (!responseCallback
) {
674 throw new Error(`Response request for unknown message id ${messageId}`);
676 delete this.requests
[messageId
];
677 responseCallback(commandName
, requestPayload
);
680 case MessageType
.CALL_ERROR_MESSAGE
:
681 if (!this.requests
[messageId
]) {
683 throw new Error(`Error request for unknown message id ${messageId}`);
685 if (Utils
.isIterable(this.requests
[messageId
])) {
686 [, rejectCallback
] = this.requests
[messageId
];
688 throw new Error(`Error request for message id ${messageId} is not iterable`);
690 delete this.requests
[messageId
];
691 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), errorDetails
));
695 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
696 logger
.error(errMsg
);
697 throw new Error(errMsg
);
701 logger
.error('%s Incoming request message %j processing error %j on content type %j', this.logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
703 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
707 private onPing(): void {
708 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
711 private onPong(): void {
712 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
715 private async onError(errorEvent
: any): Promise
<void> {
716 logger
.error(this.logPrefix() + ' Socket error: %j', errorEvent
);
717 // switch (errorEvent.code) {
718 // case 'ECONNREFUSED':
719 // await this._reconnect(errorEvent);
724 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
725 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
728 private getAuthorizationFile(): string | undefined {
729 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
732 private getAuthorizedTags(): string[] {
733 let authorizedTags
: string[] = [];
734 const authorizationFile
= this.getAuthorizationFile();
735 if (authorizationFile
) {
737 // Load authorization file
738 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
739 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
740 fs
.closeSync(fileDescriptor
);
742 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
745 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
747 return authorizedTags
;
750 private getUseConnectorId0(): boolean | undefined {
751 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
754 private getNumberOfRunningTransactions(): number {
756 for (const connector
in this.connectors
) {
757 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
765 private getConnectionTimeout(): number | undefined {
766 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
767 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
769 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
772 // -1 for unlimited, 0 for disabling
773 private getAutoReconnectMaxRetries(): number | undefined {
774 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
775 return this.stationInfo
.autoReconnectMaxRetries
;
777 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
778 return Configuration
.getAutoReconnectMaxRetries();
784 private getRegistrationMaxRetries(): number | undefined {
785 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
786 return this.stationInfo
.registrationMaxRetries
;
791 private getPowerDivider(): number {
792 let powerDivider
= this.getNumberOfConnectors();
793 if (this.stationInfo
.powerSharedByConnectors
) {
794 powerDivider
= this.getNumberOfRunningTransactions();
799 private getTemplateMaxNumberOfConnectors(): number {
800 return Object.keys(this.stationInfo
.Connectors
).length
;
803 private getMaxNumberOfConnectors(): number {
804 let maxConnectors
= 0;
805 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
806 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
807 // Distribute evenly the number of connectors
808 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
809 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
810 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
812 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
814 return maxConnectors
;
817 private getNumberOfConnectors(): number {
818 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
821 private async startMessageSequence(): Promise
<void> {
822 // Start WebSocket ping
823 this.startWebSocketPing();
825 this.startHeartbeat();
826 // Initialize connectors status
827 for (const connector
in this.connectors
) {
828 if (Utils
.convertToInt(connector
) === 0) {
830 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
831 // Send status in template at startup
832 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
833 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
834 } else if (this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
835 // Send status in template after reset
836 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
837 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
838 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
839 // Send previous status at template reload
840 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
842 // Send default status
843 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
844 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
848 this.startAutomaticTransactionGenerator();
851 private startAutomaticTransactionGenerator() {
852 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
853 if (!this.automaticTransactionGeneration
) {
854 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
856 if (this.automaticTransactionGeneration
.timeToStop
) {
857 // The ATG might sleep
858 void this.automaticTransactionGeneration
.start();
863 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
864 // Stop WebSocket ping
865 this.stopWebSocketPing();
867 this.stopHeartbeat();
869 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
870 this.automaticTransactionGeneration
&&
871 !this.automaticTransactionGeneration
.timeToStop
) {
872 await this.automaticTransactionGeneration
.stop(reason
);
874 for (const connector
in this.connectors
) {
875 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
876 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
877 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
878 this.getTransactionIdTag(transactionId
), reason
);
884 private startWebSocketPing(): void {
885 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
886 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
888 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
889 this.webSocketPingSetInterval
= setInterval(() => {
890 if (this.isWebSocketConnectionOpened()) {
891 this.wsConnection
.ping((): void => { });
893 }, webSocketPingInterval
* 1000);
894 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
895 } else if (this.webSocketPingSetInterval
) {
896 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
898 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
902 private stopWebSocketPing(): void {
903 if (this.webSocketPingSetInterval
) {
904 clearInterval(this.webSocketPingSetInterval
);
908 private getSupervisionURL(): URL
{
909 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
911 if (!Utils
.isEmptyArray(supervisionUrls
)) {
912 if (Configuration
.getDistributeStationsToTenantsEqually()) {
913 indexUrl
= this.index
% supervisionUrls
.length
;
916 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
918 return new URL(supervisionUrls
[indexUrl
]);
920 return new URL(supervisionUrls
as string);
923 private getHeartbeatInterval(): number | undefined {
924 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
925 if (HeartbeatInterval
) {
926 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
928 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
929 if (HeartBeatInterval
) {
930 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
932 !this.stationInfo
.autoRegister
&& logger
.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
933 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
936 private stopHeartbeat(): void {
937 if (this.heartbeatSetInterval
) {
938 clearInterval(this.heartbeatSetInterval
);
942 private openWSConnection(options
?: ClientOptions
& ClientRequestArgs
, forceCloseOpened
= false): void {
943 options
= options
?? {};
944 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
945 if (!Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) && !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)) {
946 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
948 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
949 this.wsConnection
.close();
952 switch (this.getOCPPVersion()) {
953 case OCPPVersion
.VERSION_16
:
954 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
957 this.handleUnsupportedVersion(this.getOCPPVersion());
960 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
961 logger
.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString());
964 private stopMeterValues(connectorId
: number) {
965 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
966 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
970 private startAuthorizationFileMonitoring(): void {
971 const authorizationFile
= this.getAuthorizationFile();
972 if (authorizationFile
) {
974 fs
.watch(authorizationFile
).on('change', () => {
976 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
977 // Initialize authorizedTags
978 this.authorizedTags
= this.getAuthorizedTags();
980 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
984 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
987 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
991 private startStationTemplateFileMonitoring(): void {
993 // eslint-disable-next-line @typescript-eslint/no-misused-promises
994 fs
.watch(this.stationTemplateFile
).on('change', async (): Promise
<void> => {
996 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
1000 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1001 this.automaticTransactionGeneration
) {
1002 await this.automaticTransactionGeneration
.stop();
1004 this.startAutomaticTransactionGenerator();
1005 if (this.getEnableStatistics()) {
1006 this.performanceStatistics
.restart();
1008 this.performanceStatistics
.stop();
1010 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1012 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
1016 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
1020 private getReconnectExponentialDelay(): boolean | undefined {
1021 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
1024 private async reconnect(error
: any): Promise
<void> {
1025 // Stop WebSocket ping
1026 this.stopWebSocketPing();
1028 this.stopHeartbeat();
1029 // Stop the ATG if needed
1030 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1031 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1032 this.automaticTransactionGeneration
&&
1033 !this.automaticTransactionGeneration
.timeToStop
) {
1034 await this.automaticTransactionGeneration
.stop();
1036 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1037 this.autoReconnectRetryCount
++;
1038 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
1039 logger
.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
1040 await Utils
.sleep(reconnectDelay
);
1041 logger
.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
1042 this.openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
1043 this.hasSocketRestarted
= true;
1044 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1045 logger
.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1049 private initTransactionAttributesOnConnector(connectorId
: number): void {
1050 this.getConnector(connectorId
).authorized
= false;
1051 this.getConnector(connectorId
).transactionStarted
= false;
1052 this.getConnector(connectorId
).energyActiveImportRegisterValue
= 0;
1053 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;