1 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/Responses';
2 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
3 import ChargingStationTemplate
, { CurrentType
, PowerUnits
, Voltage
} from
'../types/ChargingStationTemplate';
4 import { ConnectorPhaseRotation
, StandardParametersKey
, SupportedFeatureProfiles
} from
'../types/ocpp/Configuration';
5 import Connectors
, { Connector
, SampledValueTemplate
} from
'../types/Connectors';
6 import { MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
7 import Requests
, { AvailabilityType
, BootNotificationRequest
, IncomingRequest
, IncomingRequestCommand
} from
'../types/ocpp/Requests';
8 import WebSocket
, { ClientOptions
, MessageEvent
} from
'ws';
10 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
11 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
12 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
13 import ChargingStationInfo from
'../types/ChargingStationInfo';
14 import { ClientRequestArgs
} from
'http';
15 import Configuration from
'../utils/Configuration';
16 import Constants from
'../utils/Constants';
17 import { ErrorType
} from
'../types/ocpp/ErrorType';
18 import FileUtils from
'../utils/FileUtils';
19 import { MessageType
} from
'../types/ocpp/MessageType';
20 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
21 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
22 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
23 import OCPPError from
'./ocpp/OCPPError';
24 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
25 import OCPPRequestService from
'./ocpp/OCPPRequestService';
26 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
27 import PerformanceStatistics from
'../performance/PerformanceStatistics';
28 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
29 import { URL
} from
'url';
30 import Utils from
'../utils/Utils';
31 import { WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
32 import crypto from
'crypto';
34 import logger from
'../utils/Logger';
35 import path from
'path';
37 export default class ChargingStation
{
38 public stationTemplateFile
: string;
39 public authorizedTags
: string[];
40 public stationInfo
!: ChargingStationInfo
;
41 public connectors
: Connectors
;
42 public configuration
!: ChargingStationConfiguration
;
43 public hasStopped
: boolean;
44 public wsConnection
!: WebSocket
;
45 public requests
: Requests
;
46 public messageQueue
: string[];
47 public performanceStatistics
!: PerformanceStatistics
;
48 public heartbeatSetInterval
!: NodeJS
.Timeout
;
49 public ocppIncomingRequestService
!: OCPPIncomingRequestService
;
50 public ocppRequestService
!: OCPPRequestService
;
51 private index
: number;
52 private bootNotificationRequest
!: BootNotificationRequest
;
53 private bootNotificationResponse
!: BootNotificationResponse
| null;
54 private connectorsConfigurationHash
!: string;
55 private wsConnectionUrl
!: URL
;
56 private hasSocketRestarted
: boolean;
57 private autoReconnectRetryCount
: number;
58 private automaticTransactionGeneration
!: AutomaticTransactionGenerator
;
59 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
61 constructor(index
: number, stationTemplateFile
: string) {
63 this.stationTemplateFile
= stationTemplateFile
;
64 this.connectors
= {} as Connectors
;
67 this.hasStopped
= false;
68 this.hasSocketRestarted
= false;
69 this.autoReconnectRetryCount
= 0;
71 this.requests
= {} as Requests
;
72 this.messageQueue
= [] as string[];
74 this.authorizedTags
= this.getAuthorizedTags();
77 public logPrefix(): string {
78 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
81 public 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 isWebSocketConnectionOpened(): 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
);
143 throw new 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
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
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 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand ${measurand}
in template on connectorId ${connectorId}
`;
247 logger.error(errorMsg);
248 throw new Error(errorMsg);
250 logger.debug(`${this.logPrefix()} No MeterValues
for measurand ${measurand} ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
253 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
254 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
257 public startHeartbeat(): void {
258 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
259 // eslint-disable-next-line @typescript-eslint/no-misused-promises
260 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
261 await this.ocppRequestService
.sendHeartbeat();
262 }, this.getHeartbeatInterval());
263 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
264 } else if (this.heartbeatSetInterval
) {
265 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
267 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
271 public restartHeartbeat(): void {
273 this.stopHeartbeat();
275 this.startHeartbeat();
278 public startMeterValues(connectorId
: number, interval
: number): void {
279 if (connectorId
=== 0) {
280 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
283 if (!this.getConnector(connectorId
)) {
284 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
287 if (!this.getConnector(connectorId
)?.transactionStarted
) {
288 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
290 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
291 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
295 // eslint-disable-next-line @typescript-eslint/no-misused-promises
296 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
297 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
);
300 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
304 public start(): void {
305 if (this.getEnableStatistics()) {
306 this.performanceStatistics
.start();
308 this.openWSConnection();
309 // Monitor authorization file
310 this.startAuthorizationFileMonitoring();
311 // Monitor station template file
312 this.startStationTemplateFileMonitoring();
313 // Handle Socket incoming messages
314 this.wsConnection
.on('message', this.onMessage
.bind(this));
315 // Handle Socket error
316 this.wsConnection
.on('error', this.onError
.bind(this));
317 // Handle Socket close
318 this.wsConnection
.on('close', this.onClose
.bind(this));
319 // Handle Socket opening connection
320 this.wsConnection
.on('open', this.onOpen
.bind(this));
321 // Handle Socket ping
322 this.wsConnection
.on('ping', this.onPing
.bind(this));
323 // Handle Socket pong
324 this.wsConnection
.on('pong', this.onPong
.bind(this));
327 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
328 // Stop message sequence
329 await this.stopMessageSequence(reason
);
330 for (const connector
in this.connectors
) {
331 if (Utils
.convertToInt(connector
) > 0) {
332 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
333 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.UNAVAILABLE
;
336 if (this.isWebSocketConnectionOpened()) {
337 this.wsConnection
.close();
339 if (this.getEnableStatistics()) {
340 this.performanceStatistics
.stop();
342 this.bootNotificationResponse
= null;
343 this.hasStopped
= true;
346 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
347 return this.configuration
.configurationKey
.find((configElement
) => {
348 if (caseInsensitive
) {
349 return configElement
.key
.toLowerCase() === key
.toLowerCase();
351 return configElement
.key
=== key
;
355 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
356 const keyFound
= this.getConfigurationKey(key
);
358 this.configuration
.configurationKey
.push({
366 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
370 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
371 const keyFound
= this.getConfigurationKey(key
);
373 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
374 this.configuration
.configurationKey
[keyIndex
].value
= value
;
376 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
380 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
381 let cpReplaced
= false;
382 if (!Utils
.isEmptyArray(this.getConnector(connectorId
).chargingProfiles
)) {
383 this.getConnector(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
384 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
385 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
386 this.getConnector(connectorId
).chargingProfiles
[index
] = cp
;
391 !cpReplaced
&& this.getConnector(connectorId
).chargingProfiles
?.push(cp
);
394 public resetTransactionOnConnector(connectorId
: number): void {
395 this.getConnector(connectorId
).authorized
= false;
396 this.getConnector(connectorId
).transactionStarted
= false;
397 delete this.getConnector(connectorId
).authorizeIdTag
;
398 delete this.getConnector(connectorId
).transactionId
;
399 delete this.getConnector(connectorId
).transactionIdTag
;
400 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
401 delete this.getConnector(connectorId
).transactionBeginMeterValue
;
402 this.stopMeterValues(connectorId
);
405 public addToMessageQueue(message
: string): void {
407 // Handle dups in message queue
408 for (const bufferedMessage
of this.messageQueue
) {
409 // Message already in the queue
410 if (message
=== bufferedMessage
) {
417 this.messageQueue
.push(message
);
421 private flushMessageQueue() {
422 if (!Utils
.isEmptyArray(this.messageQueue
)) {
423 this.messageQueue
.forEach((message
, index
) => {
424 this.messageQueue
.splice(index
, 1);
425 // TODO: evaluate the need to track performance
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.wsConnectionUrl
= new URL(this.getSupervisionURL().href
+ '/' + this.stationInfo
.chargingStationId
);
489 // Build connectors if needed
490 const maxConnectors
= this.getMaxNumberOfConnectors();
491 if (maxConnectors
<= 0) {
492 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
494 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
495 if (templateMaxConnectors
<= 0) {
496 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
498 if (!this.stationInfo
.Connectors
[0]) {
499 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
502 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
503 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
504 this.stationInfo
.randomConnectors
= true;
506 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
507 // FIXME: Handle shrinking the number of connectors
508 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
509 this.connectorsConfigurationHash
= connectorsConfigHash
;
510 // Add connector Id 0
511 let lastConnector
= '0';
512 for (lastConnector
in this.stationInfo
.Connectors
) {
513 if (Utils
.convertToInt(lastConnector
) === 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
514 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
515 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
516 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
517 this.connectors
[lastConnector
].chargingProfiles
= [];
521 // Generate all connectors
522 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
523 for (let index
= 1; index
<= maxConnectors
; index
++) {
524 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
525 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorId
]);
526 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
527 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
528 this.connectors
[index
].chargingProfiles
= [];
533 // Avoid duplication of connectors related information
534 delete this.stationInfo
.Connectors
;
535 // Initialize transaction attributes on connectors
536 for (const connector
in this.connectors
) {
537 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
538 this.initTransactionAttributesOnConnector(Utils
.convertToInt(connector
));
541 switch (this.getOCPPVersion()) {
542 case OCPPVersion
.VERSION_16
:
543 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
544 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
547 this.handleUnsupportedVersion(this.getOCPPVersion());
551 this.initOCPPParameters();
552 if (this.stationInfo
.autoRegister
) {
553 this.bootNotificationResponse
= {
554 currentTime
: new Date().toISOString(),
555 interval
: this.getHeartbeatInterval() / 1000,
556 status: RegistrationStatus
.ACCEPTED
559 this.stationInfo
.powerDivider
= this.getPowerDivider();
560 if (this.getEnableStatistics()) {
561 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
565 private initOCPPParameters(): void {
566 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
567 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
569 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
570 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
571 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
573 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
574 const connectorPhaseRotation
= [];
575 for (const connector
in this.connectors
) {
577 if (Utils
.convertToInt(connector
) === 0 && this.getNumberOfPhases() === 0) {
578 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
579 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 0) {
580 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
582 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 1) {
583 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
584 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 3) {
585 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
588 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
590 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
591 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
593 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
594 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
595 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
597 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
598 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
602 private async onOpen(): Promise
<void> {
603 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
604 if (!this.isRegistered()) {
605 // Send BootNotification
606 let registrationRetryCount
= 0;
608 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
609 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
610 if (!this.isRegistered()) {
611 registrationRetryCount
++;
612 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
614 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
616 if (this.isRegistered()) {
617 await this.startMessageSequence();
618 this.hasStopped
&& (this.hasStopped
= false);
619 if (this.hasSocketRestarted
&& this.isWebSocketConnectionOpened()) {
620 this.flushMessageQueue();
623 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
625 this.autoReconnectRetryCount
= 0;
626 this.hasSocketRestarted
= false;
629 private async onClose(closeEvent
: any): Promise
<void> {
630 switch (closeEvent
) {
631 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
632 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
633 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
634 this.autoReconnectRetryCount
= 0;
636 default: // Abnormal close
637 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
638 await this.reconnect(closeEvent
);
643 private async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
644 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
645 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
646 let rejectCallback
: (error
: OCPPError
) => void;
647 let requestPayload
: Record
<string, unknown
>;
650 const request
= JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
651 if (Utils
.isIterable(request
)) {
653 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
655 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
657 // Check the Type of message
658 switch (messageType
) {
660 case MessageType
.CALL_MESSAGE
:
661 if (this.getEnableStatistics()) {
662 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
665 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
668 case MessageType
.CALL_RESULT_MESSAGE
:
670 if (Utils
.isIterable(this.requests
[messageId
])) {
671 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
673 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Response request for message id ${messageId} is not iterable`, commandName
);
675 if (!responseCallback
) {
677 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response request for unknown message id ${messageId}`, commandName
);
679 delete this.requests
[messageId
];
680 responseCallback(commandName
, requestPayload
);
683 case MessageType
.CALL_ERROR_MESSAGE
:
684 if (!this.requests
[messageId
]) {
686 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error request for unknown message id ${messageId}`);
688 if (Utils
.isIterable(this.requests
[messageId
])) {
689 [, rejectCallback
] = this.requests
[messageId
];
691 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Error request for message id ${messageId} is not iterable`);
693 delete this.requests
[messageId
];
694 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), null, errorDetails
));
698 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
699 logger
.error(errMsg
);
700 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
704 logger
.error('%s Incoming request message %j processing error %j on content type %j', this.logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
706 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
710 private onPing(): void {
711 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
714 private onPong(): void {
715 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
718 private async onError(errorEvent
: any): Promise
<void> {
719 logger
.error(this.logPrefix() + ' Socket error: %j', errorEvent
);
720 // switch (errorEvent.code) {
721 // case 'ECONNREFUSED':
722 // await this._reconnect(errorEvent);
727 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
728 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
731 private getAuthorizationFile(): string | undefined {
732 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
735 private getAuthorizedTags(): string[] {
736 let authorizedTags
: string[] = [];
737 const authorizationFile
= this.getAuthorizationFile();
738 if (authorizationFile
) {
740 // Load authorization file
741 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
742 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
743 fs
.closeSync(fileDescriptor
);
745 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
748 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
750 return authorizedTags
;
753 private getUseConnectorId0(): boolean | undefined {
754 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
757 private getNumberOfRunningTransactions(): number {
759 for (const connector
in this.connectors
) {
760 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
768 private getConnectionTimeout(): number | undefined {
769 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
770 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
772 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
775 // -1 for unlimited, 0 for disabling
776 private getAutoReconnectMaxRetries(): number | undefined {
777 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
778 return this.stationInfo
.autoReconnectMaxRetries
;
780 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
781 return Configuration
.getAutoReconnectMaxRetries();
787 private getRegistrationMaxRetries(): number | undefined {
788 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
789 return this.stationInfo
.registrationMaxRetries
;
794 private getPowerDivider(): number {
795 let powerDivider
= this.getNumberOfConnectors();
796 if (this.stationInfo
.powerSharedByConnectors
) {
797 powerDivider
= this.getNumberOfRunningTransactions();
802 private getTemplateMaxNumberOfConnectors(): number {
803 return Object.keys(this.stationInfo
.Connectors
).length
;
806 private getMaxNumberOfConnectors(): number {
807 let maxConnectors
= 0;
808 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
809 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
810 // Distribute evenly the number of connectors
811 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
812 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
813 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
815 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
817 return maxConnectors
;
820 private getNumberOfConnectors(): number {
821 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
824 private async startMessageSequence(): Promise
<void> {
825 // Start WebSocket ping
826 this.startWebSocketPing();
828 this.startHeartbeat();
829 // Initialize connectors status
830 for (const connector
in this.connectors
) {
831 if (Utils
.convertToInt(connector
) === 0) {
833 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
834 // Send status in template at startup
835 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
836 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
837 } else if (this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
838 // Send status in template after reset
839 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
840 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
841 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
842 // Send previous status at template reload
843 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
845 // Send default status
846 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
847 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
851 this.startAutomaticTransactionGenerator();
854 private startAutomaticTransactionGenerator() {
855 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
856 if (!this.automaticTransactionGeneration
) {
857 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
859 if (this.automaticTransactionGeneration
.timeToStop
) {
860 // The ATG might sleep
861 void this.automaticTransactionGeneration
.start();
866 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
867 // Stop WebSocket ping
868 this.stopWebSocketPing();
870 this.stopHeartbeat();
872 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
873 this.automaticTransactionGeneration
&&
874 !this.automaticTransactionGeneration
.timeToStop
) {
875 await this.automaticTransactionGeneration
.stop(reason
);
877 for (const connector
in this.connectors
) {
878 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
879 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
880 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
881 this.getTransactionIdTag(transactionId
), reason
);
887 private startWebSocketPing(): void {
888 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
889 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
891 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
892 this.webSocketPingSetInterval
= setInterval(() => {
893 if (this.isWebSocketConnectionOpened()) {
894 this.wsConnection
.ping((): void => { });
896 }, webSocketPingInterval
* 1000);
897 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
898 } else if (this.webSocketPingSetInterval
) {
899 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
901 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
905 private stopWebSocketPing(): void {
906 if (this.webSocketPingSetInterval
) {
907 clearInterval(this.webSocketPingSetInterval
);
911 private getSupervisionURL(): URL
{
912 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
914 if (!Utils
.isEmptyArray(supervisionUrls
)) {
915 if (Configuration
.getDistributeStationsToTenantsEqually()) {
916 indexUrl
= this.index
% supervisionUrls
.length
;
919 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
921 return new URL(supervisionUrls
[indexUrl
]);
923 return new URL(supervisionUrls
as string);
926 private getHeartbeatInterval(): number | undefined {
927 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
928 if (HeartbeatInterval
) {
929 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
931 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
932 if (HeartBeatInterval
) {
933 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
935 !this.stationInfo
.autoRegister
&& logger
.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
936 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
939 private stopHeartbeat(): void {
940 if (this.heartbeatSetInterval
) {
941 clearInterval(this.heartbeatSetInterval
);
945 private openWSConnection(options
?: ClientOptions
& ClientRequestArgs
, forceCloseOpened
= false): void {
946 options
= options
?? {};
947 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
948 if (!Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) && !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)) {
949 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
951 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
952 this.wsConnection
.close();
955 switch (this.getOCPPVersion()) {
956 case OCPPVersion
.VERSION_16
:
957 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
960 this.handleUnsupportedVersion(this.getOCPPVersion());
963 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
964 logger
.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString());
967 private stopMeterValues(connectorId
: number) {
968 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
969 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
973 private startAuthorizationFileMonitoring(): void {
974 const authorizationFile
= this.getAuthorizationFile();
975 if (authorizationFile
) {
977 fs
.watch(authorizationFile
).on('change', () => {
979 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
980 // Initialize authorizedTags
981 this.authorizedTags
= this.getAuthorizedTags();
983 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
987 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
990 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
994 private startStationTemplateFileMonitoring(): void {
996 // eslint-disable-next-line @typescript-eslint/no-misused-promises
997 fs
.watch(this.stationTemplateFile
).on('change', async (): Promise
<void> => {
999 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
1003 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1004 this.automaticTransactionGeneration
) {
1005 await this.automaticTransactionGeneration
.stop();
1007 this.startAutomaticTransactionGenerator();
1008 if (this.getEnableStatistics()) {
1009 this.performanceStatistics
.restart();
1011 this.performanceStatistics
.stop();
1013 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1015 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
1019 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
1023 private getReconnectExponentialDelay(): boolean | undefined {
1024 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
1027 private async reconnect(error
: unknown
): Promise
<void> {
1028 // Stop WebSocket ping
1029 this.stopWebSocketPing();
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;