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 { PerformanceObserver
, performance
} from
'perf_hooks';
8 import Requests
, { AvailabilityType
, BootNotificationRequest
, IncomingRequest
, IncomingRequestCommand
} from
'../types/ocpp/Requests';
9 import WebSocket
, { MessageEvent
} from
'ws';
11 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
12 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
13 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
14 import ChargingStationInfo from
'../types/ChargingStationInfo';
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/OCCP16IncomingRequestService';
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 Utils from
'../utils/Utils';
29 import { WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
30 import crypto from
'crypto';
32 import logger from
'../utils/Logger';
33 import path from
'path';
35 export default class ChargingStation
{
36 public stationTemplateFile
: string;
37 public authorizedTags
: string[];
38 public stationInfo
!: ChargingStationInfo
;
39 public connectors
: Connectors
;
40 public configuration
!: ChargingStationConfiguration
;
41 public hasStopped
: boolean;
42 public wsConnection
!: WebSocket
;
43 public requests
: Requests
;
44 public messageQueue
: string[];
45 public performanceStatistics
!: PerformanceStatistics
;
46 public heartbeatSetInterval
!: NodeJS
.Timeout
;
47 public ocppIncomingRequestService
!: OCPPIncomingRequestService
;
48 public ocppRequestService
!: OCPPRequestService
;
49 private index
: number;
50 private bootNotificationRequest
!: BootNotificationRequest
;
51 private bootNotificationResponse
!: BootNotificationResponse
| null;
52 private connectorsConfigurationHash
!: string;
53 private supervisionUrl
!: string;
54 private wsConnectionUrl
!: string;
55 private hasSocketRestarted
: boolean;
56 private autoReconnectRetryCount
: number;
57 private automaticTransactionGeneration
!: AutomaticTransactionGenerator
;
58 private performanceObserver
!: PerformanceObserver
;
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 getRandomTagId(): string {
82 const index
= Math.floor(Math.random() * this.authorizedTags
.length
);
83 return this.authorizedTags
[index
];
86 public hasAuthorizedTags(): boolean {
87 return !Utils
.isEmptyArray(this.authorizedTags
);
90 public getEnableStatistics(): boolean | undefined {
91 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
94 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
95 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
98 public getNumberOfPhases(): number | undefined {
99 switch (this.getCurrentOutType()) {
101 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
107 public isWebSocketOpen(): boolean {
108 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
;
111 public isRegistered(): boolean {
112 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
115 public isChargingStationAvailable(): boolean {
116 return this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
;
119 public isConnectorAvailable(id
: number): boolean {
120 return this.getConnector(id
).availability
=== AvailabilityType
.OPERATIVE
;
123 public getConnector(id
: number): Connector
{
124 return this.connectors
[id
];
127 public getCurrentOutType(): CurrentType
| undefined {
128 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
131 public getVoltageOut(): number | undefined {
132 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
133 let defaultVoltageOut
: number;
134 switch (this.getCurrentOutType()) {
136 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
139 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
142 logger
.error(errMsg
);
145 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
148 public getTransactionIdTag(transactionId
: number): string | undefined {
149 for (const connector
in this.connectors
) {
150 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
151 return this.getConnector(Utils
.convertToInt(connector
)).transactionIdTag
;
156 public getOutOfOrderEndMeterValues(): boolean {
157 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
160 public getBeginEndMeterValues(): boolean {
161 return this.stationInfo
.beginEndMeterValues
?? false;
164 public getMeteringPerTransaction(): boolean {
165 return this.stationInfo
.meteringPerTransaction
?? true;
168 public getTransactionDataMeterValues(): boolean {
169 return this.stationInfo
.transactionDataMeterValues
?? false;
172 public getMainVoltageMeterValues(): boolean {
173 return this.stationInfo
.mainVoltageMeterValues
?? true;
176 public getPhaseLineToLineVoltageMeterValues(): boolean {
177 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
180 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
181 if (this.getMeteringPerTransaction()) {
182 for (const connector
in this.connectors
) {
183 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
184 return this.getConnector(Utils
.convertToInt(connector
)).transactionEnergyActiveImportRegisterValue
;
188 for (const connector
in this.connectors
) {
189 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
190 return this.getConnector(Utils
.convertToInt(connector
)).energyActiveImportRegisterValue
;
195 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
196 if (this.getMeteringPerTransaction()) {
197 return this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
;
199 return this.getConnector(connectorId
).energyActiveImportRegisterValue
;
202 public getAuthorizeRemoteTxRequests(): boolean {
203 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
204 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
207 public getLocalAuthListEnabled(): boolean {
208 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
209 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
212 public restartWebSocketPing(): void {
213 // Stop WebSocket ping
214 this.stopWebSocketPing();
215 // Start WebSocket ping
216 this.startWebSocketPing();
219 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
220 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
221 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
222 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
225 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
226 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`);
229 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnector(connectorId
).MeterValues
;
230 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
231 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
)) {
232 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
234 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
235 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
236 return sampledValueTemplates[index];
237 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
238 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
239 return sampledValueTemplates[index];
240 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
241 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
242 return sampledValueTemplates[index];
245 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
246 logger.error(`${this.logPrefix()} Missing MeterValues
for default measurand ${measurand}
in template on connectorId ${connectorId}
`);
248 logger.debug(`${this.logPrefix()} No MeterValues
for measurand ${measurand} ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
251 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
252 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
255 public startHeartbeat(): void {
256 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
257 // eslint-disable-next-line @typescript-eslint/no-misused-promises
258 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
259 await this.ocppRequestService
.sendHeartbeat();
260 }, this.getHeartbeatInterval());
261 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
262 } else if (this.heartbeatSetInterval
) {
263 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
265 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
269 public restartHeartbeat(): void {
271 this.stopHeartbeat();
273 this.startHeartbeat();
276 public startMeterValues(connectorId
: number, interval
: number): void {
277 if (connectorId
=== 0) {
278 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
281 if (!this.getConnector(connectorId
)) {
282 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
285 if (!this.getConnector(connectorId
)?.transactionStarted
) {
286 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
288 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
289 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
293 // eslint-disable-next-line @typescript-eslint/no-misused-promises
294 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
295 if (this.getEnableStatistics()) {
296 const sendMeterValues
= performance
.timerify(this.ocppRequestService
.sendMeterValues
);
297 this.performanceObserver
.observe({
298 entryTypes
: ['function'],
300 await sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
302 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
306 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
310 public start(): void {
311 this.openWSConnection();
312 // Monitor authorization file
313 this.startAuthorizationFileMonitoring();
314 // Monitor station template file
315 this.startStationTemplateFileMonitoring();
316 // Handle Socket incoming messages
317 this.wsConnection
.on('message', this.onMessage
.bind(this));
318 // Handle Socket error
319 this.wsConnection
.on('error', this.onError
.bind(this));
320 // Handle Socket close
321 this.wsConnection
.on('close', this.onClose
.bind(this));
322 // Handle Socket opening connection
323 this.wsConnection
.on('open', this.onOpen
.bind(this));
324 // Handle Socket ping
325 this.wsConnection
.on('ping', this.onPing
.bind(this));
326 // Handle Socket pong
327 this.wsConnection
.on('pong', this.onPong
.bind(this));
330 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
331 // Stop message sequence
332 await this.stopMessageSequence(reason
);
333 for (const connector
in this.connectors
) {
334 if (Utils
.convertToInt(connector
) > 0) {
335 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
336 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.UNAVAILABLE
;
339 if (this.isWebSocketOpen()) {
340 this.wsConnection
.close();
342 this.bootNotificationResponse
= null;
343 this.hasStopped
= true;
346 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
347 const configurationKey
: ConfigurationKey
| undefined = this.configuration
.configurationKey
.find((configElement
) => {
348 if (caseInsensitive
) {
349 return configElement
.key
.toLowerCase() === key
.toLowerCase();
351 return configElement
.key
=== key
;
353 return configurationKey
;
356 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
357 const keyFound
= this.getConfigurationKey(key
);
359 this.configuration
.configurationKey
.push({
367 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
371 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
372 const keyFound
= this.getConfigurationKey(key
);
374 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
375 this.configuration
.configurationKey
[keyIndex
].value
= value
;
377 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
381 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
382 let cpReplaced
= false;
383 if (!Utils
.isEmptyArray(this.getConnector(connectorId
).chargingProfiles
)) {
384 this.getConnector(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
385 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
386 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
387 this.getConnector(connectorId
).chargingProfiles
[index
] = cp
;
392 !cpReplaced
&& this.getConnector(connectorId
).chargingProfiles
?.push(cp
);
395 public resetTransactionOnConnector(connectorId
: number): void {
396 this.getConnector(connectorId
).authorized
= false;
397 this.getConnector(connectorId
).transactionStarted
= false;
398 delete this.getConnector(connectorId
).authorizeIdTag
;
399 delete this.getConnector(connectorId
).transactionId
;
400 delete this.getConnector(connectorId
).transactionIdTag
;
401 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
402 delete this.getConnector(connectorId
).transactionBeginMeterValue
;
403 this.stopMeterValues(connectorId
);
406 public addToMessageQueue(message
: string): void {
408 // Handle dups in message queue
409 for (const bufferedMessage
of this.messageQueue
) {
410 // Message already in the queue
411 if (message
=== bufferedMessage
) {
418 this.messageQueue
.push(message
);
422 private flushMessageQueue() {
423 if (!Utils
.isEmptyArray(this.messageQueue
)) {
424 this.messageQueue
.forEach((message
, index
) => {
425 this.messageQueue
.splice(index
, 1);
426 this.wsConnection
.send(message
);
431 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
432 // In case of multiple instances: add instance index to charging station id
433 let instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
434 instanceIndex
= instanceIndex
> 0 ? instanceIndex
: '';
435 const idSuffix
= stationTemplate
.nameSuffix
?? '';
436 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
439 private buildStationInfo(): ChargingStationInfo
{
440 let stationTemplateFromFile
: ChargingStationTemplate
;
442 // Load template file
443 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
444 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
445 fs
.closeSync(fileDescriptor
);
447 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
449 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
450 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
451 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
452 const powerArrayRandomIndex
= Math.floor(Math.random() * stationTemplateFromFile
.power
.length
);
453 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
454 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
455 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
457 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
458 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
459 ? stationTemplateFromFile
.power
* 1000
460 : stationTemplateFromFile
.power
;
462 delete stationInfo
.power
;
463 delete stationInfo
.powerUnit
;
464 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
465 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
469 private getOCPPVersion(): OCPPVersion
{
470 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
473 private handleUnsupportedVersion(version
: OCPPVersion
) {
474 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
475 logger
.error(errMsg
);
476 throw new Error(errMsg
);
479 private initialize(): void {
480 this.stationInfo
= this.buildStationInfo();
481 this.bootNotificationRequest
= {
482 chargePointModel
: this.stationInfo
.chargePointModel
,
483 chargePointVendor
: this.stationInfo
.chargePointVendor
,
484 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
485 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
487 this.configuration
= this.getTemplateChargingStationConfiguration();
488 this.supervisionUrl
= this.getSupervisionURL();
489 this.wsConnectionUrl
= this.supervisionUrl
+ '/' + this.stationInfo
.chargingStationId
;
490 // Build connectors if needed
491 const maxConnectors
= this.getMaxNumberOfConnectors();
492 if (maxConnectors
<= 0) {
493 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
495 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
496 if (templateMaxConnectors
<= 0) {
497 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
499 if (!this.stationInfo
.Connectors
[0]) {
500 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
503 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
504 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
505 this.stationInfo
.randomConnectors
= true;
507 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
508 // FIXME: Handle shrinking the number of connectors
509 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
510 this.connectorsConfigurationHash
= connectorsConfigHash
;
511 // Add connector Id 0
512 let lastConnector
= '0';
513 for (lastConnector
in this.stationInfo
.Connectors
) {
514 if (Utils
.convertToInt(lastConnector
) === 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
515 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
516 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
517 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
518 this.connectors
[lastConnector
].chargingProfiles
= [];
522 // Generate all connectors
523 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
524 for (let index
= 1; index
<= maxConnectors
; index
++) {
525 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
526 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorId
]);
527 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
528 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
529 this.connectors
[index
].chargingProfiles
= [];
534 // Avoid duplication of connectors related information
535 delete this.stationInfo
.Connectors
;
536 // Initialize transaction attributes on connectors
537 for (const connector
in this.connectors
) {
538 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
539 this.initTransactionAttributesOnConnector(Utils
.convertToInt(connector
));
542 switch (this.getOCPPVersion()) {
543 case OCPPVersion
.VERSION_16
:
544 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
545 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
548 this.handleUnsupportedVersion(this.getOCPPVersion());
552 this.initOCPPParameters();
553 if (this.stationInfo
.autoRegister
) {
554 this.bootNotificationResponse
= {
555 currentTime
: new Date().toISOString(),
556 interval
: this.getHeartbeatInterval() / 1000,
557 status: RegistrationStatus
.ACCEPTED
560 this.stationInfo
.powerDivider
= this.getPowerDivider();
561 if (this.getEnableStatistics()) {
562 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
);
563 this.performanceObserver
= new PerformanceObserver((list
) => {
564 const entry
= list
.getEntries()[0];
565 this.performanceStatistics
.logPerformance(entry
, Constants
.ENTITY_CHARGING_STATION
);
566 this.performanceObserver
.disconnect();
571 private initOCPPParameters(): void {
572 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
573 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
575 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
576 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
577 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
579 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
580 const connectorPhaseRotation
= [];
581 for (const connector
in this.connectors
) {
583 if (Utils
.convertToInt(connector
) === 0 && this.getNumberOfPhases() === 0) {
584 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
585 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 0) {
586 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
588 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 1) {
589 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
590 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 3) {
591 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
594 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
596 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
597 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
599 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
600 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
601 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
603 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
604 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
608 private async onOpen(): Promise
<void> {
609 logger
.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
610 if (!this.isRegistered()) {
611 // Send BootNotification
612 let registrationRetryCount
= 0;
614 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
615 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
616 if (!this.isRegistered()) {
617 registrationRetryCount
++;
618 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
620 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
622 if (this.isRegistered()) {
623 await this.startMessageSequence();
624 this.hasStopped
&& (this.hasStopped
= false);
625 if (this.hasSocketRestarted
&& this.isWebSocketOpen()) {
626 this.flushMessageQueue();
629 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
631 this.autoReconnectRetryCount
= 0;
632 this.hasSocketRestarted
= false;
635 private async onClose(closeEvent
: any): Promise
<void> {
636 switch (closeEvent
) {
637 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
638 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
639 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
640 this.autoReconnectRetryCount
= 0;
642 default: // Abnormal close
643 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
644 await this.reconnect(closeEvent
);
649 private async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
650 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
651 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
652 let rejectCallback
: (error
: OCPPError
) => void;
653 let requestPayload
: Record
<string, unknown
>;
656 const request
= JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
657 if (Utils
.isIterable(request
)) {
659 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
661 throw new Error('Incoming request is not iterable');
663 // Check the Type of message
664 switch (messageType
) {
666 case MessageType
.CALL_MESSAGE
:
667 if (this.getEnableStatistics()) {
668 this.performanceStatistics
.addMessage(commandName
, messageType
);
671 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
674 case MessageType
.CALL_RESULT_MESSAGE
:
676 if (Utils
.isIterable(this.requests
[messageId
])) {
677 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
679 throw new Error(`Response request for message id ${messageId} is not iterable`);
681 if (!responseCallback
) {
683 throw new Error(`Response request for unknown message id ${messageId}`);
685 delete this.requests
[messageId
];
686 responseCallback(commandName
, requestPayload
);
689 case MessageType
.CALL_ERROR_MESSAGE
:
690 if (!this.requests
[messageId
]) {
692 throw new Error(`Error request for unknown message id ${messageId}`);
694 if (Utils
.isIterable(this.requests
[messageId
])) {
695 [, rejectCallback
] = this.requests
[messageId
];
697 throw new Error(`Error request for message id ${messageId} is not iterable`);
699 delete this.requests
[messageId
];
700 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), errorDetails
));
704 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
705 logger
.error(errMsg
);
706 throw new Error(errMsg
);
710 logger
.error('%s Incoming request message %j processing error %j on content type %j', this.logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
712 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
716 private onPing(): void {
717 logger
.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
720 private onPong(): void {
721 logger
.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
724 private async onError(errorEvent
: any): Promise
<void> {
725 logger
.error(this.logPrefix() + ' Socket error: %j', errorEvent
);
726 // switch (errorEvent.code) {
727 // case 'ECONNREFUSED':
728 // await this._reconnect(errorEvent);
733 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
734 return this.stationInfo
.Configuration
? this.stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
737 private getAuthorizationFile(): string | undefined {
738 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
741 private getAuthorizedTags(): string[] {
742 let authorizedTags
: string[] = [];
743 const authorizationFile
= this.getAuthorizationFile();
744 if (authorizationFile
) {
746 // Load authorization file
747 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
748 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
749 fs
.closeSync(fileDescriptor
);
751 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
754 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
756 return authorizedTags
;
759 private getUseConnectorId0(): boolean | undefined {
760 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
763 private getNumberOfRunningTransactions(): number {
765 for (const connector
in this.connectors
) {
766 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
774 private getConnectionTimeout(): number | undefined {
775 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
776 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
778 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
781 // -1 for unlimited, 0 for disabling
782 private getAutoReconnectMaxRetries(): number | undefined {
783 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
784 return this.stationInfo
.autoReconnectMaxRetries
;
786 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
787 return Configuration
.getAutoReconnectMaxRetries();
793 private getRegistrationMaxRetries(): number | undefined {
794 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
795 return this.stationInfo
.registrationMaxRetries
;
800 private getPowerDivider(): number {
801 let powerDivider
= this.getNumberOfConnectors();
802 if (this.stationInfo
.powerSharedByConnectors
) {
803 powerDivider
= this.getNumberOfRunningTransactions();
808 private getTemplateMaxNumberOfConnectors(): number {
809 return Object.keys(this.stationInfo
.Connectors
).length
;
812 private getMaxNumberOfConnectors(): number {
813 let maxConnectors
= 0;
814 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
815 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
816 // Distribute evenly the number of connectors
817 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
818 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
819 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
821 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
823 return maxConnectors
;
826 private getNumberOfConnectors(): number {
827 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
830 private async startMessageSequence(): Promise
<void> {
831 // Start WebSocket ping
832 this.startWebSocketPing();
834 this.startHeartbeat();
835 // Initialize connectors status
836 for (const connector
in this.connectors
) {
837 if (Utils
.convertToInt(connector
) === 0) {
839 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
840 // Send status in template at startup
841 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
842 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
843 } else if (this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
844 // Send status in template after reset
845 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
846 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
847 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
848 // Send previous status at template reload
849 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
851 // Send default status
852 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
853 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
857 this.startAutomaticTransactionGenerator();
858 if (this.getEnableStatistics()) {
859 this.performanceStatistics
.start();
863 private startAutomaticTransactionGenerator() {
864 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
865 if (!this.automaticTransactionGeneration
) {
866 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
868 if (this.automaticTransactionGeneration
.timeToStop
) {
869 // The ATG might sleep
870 void this.automaticTransactionGeneration
.start();
875 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
876 // Stop WebSocket ping
877 this.stopWebSocketPing();
879 this.stopHeartbeat();
881 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
882 this.automaticTransactionGeneration
&&
883 !this.automaticTransactionGeneration
.timeToStop
) {
884 await this.automaticTransactionGeneration
.stop(reason
);
886 for (const connector
in this.connectors
) {
887 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
888 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
889 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
890 this.getTransactionIdTag(transactionId
), reason
);
896 private startWebSocketPing(): void {
897 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
898 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
900 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
901 this.webSocketPingSetInterval
= setInterval(() => {
902 if (this.isWebSocketOpen()) {
903 this.wsConnection
.ping((): void => { });
905 }, webSocketPingInterval
* 1000);
906 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
907 } else if (this.webSocketPingSetInterval
) {
908 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
910 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
914 private stopWebSocketPing(): void {
915 if (this.webSocketPingSetInterval
) {
916 clearInterval(this.webSocketPingSetInterval
);
920 private getSupervisionURL(): string {
921 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
923 if (!Utils
.isEmptyArray(supervisionUrls
)) {
924 if (Configuration
.getDistributeStationsToTenantsEqually()) {
925 indexUrl
= this.index
% supervisionUrls
.length
;
928 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
930 return supervisionUrls
[indexUrl
];
932 return supervisionUrls
as string;
935 private getHeartbeatInterval(): number | undefined {
936 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
937 if (HeartbeatInterval
) {
938 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
940 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
941 if (HeartBeatInterval
) {
942 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
944 !this.stationInfo
.autoRegister
&& logger
.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
945 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
948 private stopHeartbeat(): void {
949 if (this.heartbeatSetInterval
) {
950 clearInterval(this.heartbeatSetInterval
);
954 private openWSConnection(options
?: WebSocket
.ClientOptions
, forceCloseOpened
= false): void {
955 options
?? {} as WebSocket
.ClientOptions
;
956 options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
957 if (this.isWebSocketOpen() && forceCloseOpened
) {
958 this.wsConnection
.close();
961 switch (this.getOCPPVersion()) {
962 case OCPPVersion
.VERSION_16
:
963 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
966 this.handleUnsupportedVersion(this.getOCPPVersion());
969 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
970 logger
.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl
);
973 private stopMeterValues(connectorId
: number) {
974 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
975 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
979 private startAuthorizationFileMonitoring(): void {
980 const authorizationFile
= this.getAuthorizationFile();
981 if (authorizationFile
) {
983 fs
.watch(authorizationFile
).on('change', () => {
985 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
986 // Initialize authorizedTags
987 this.authorizedTags
= this.getAuthorizedTags();
989 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
993 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
996 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
1000 private startStationTemplateFileMonitoring(): void {
1002 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1003 fs
.watch(this.stationTemplateFile
).on('change', async (): Promise
<void> => {
1005 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
1009 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1010 this.automaticTransactionGeneration
) {
1011 await this.automaticTransactionGeneration
.stop();
1014 this.startAutomaticTransactionGenerator();
1015 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1017 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
1021 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
1025 private getReconnectExponentialDelay(): boolean | undefined {
1026 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
1029 private async reconnect(error
: any): Promise
<void> {
1031 this.stopHeartbeat();
1032 // Stop the ATG if needed
1033 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1034 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1035 this.automaticTransactionGeneration
&&
1036 !this.automaticTransactionGeneration
.timeToStop
) {
1037 await this.automaticTransactionGeneration
.stop();
1039 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1040 this.autoReconnectRetryCount
++;
1041 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
1042 logger
.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
1043 await Utils
.sleep(reconnectDelay
);
1044 logger
.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
1045 this.openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
1046 this.hasSocketRestarted
= true;
1047 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1048 logger
.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1052 private initTransactionAttributesOnConnector(connectorId
: number): void {
1053 this.getConnector(connectorId
).authorized
= false;
1054 this.getConnector(connectorId
).transactionStarted
= false;
1055 this.getConnector(connectorId
).energyActiveImportRegisterValue
= 0;
1056 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;