1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { AvailabilityType
, BootNotificationRequest
, IncomingRequest
, IncomingRequestCommand
, Request
} from
'../types/ocpp/Requests';
4 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/Responses';
5 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
6 import ChargingStationTemplate
, { CurrentType
, PowerUnits
, Voltage
} from
'../types/ChargingStationTemplate';
7 import { Connector
, Connectors
, SampledValueTemplate
} from
'../types/Connectors';
8 import { ConnectorPhaseRotation
, StandardParametersKey
, SupportedFeatureProfiles
} from
'../types/ocpp/Configuration';
9 import { MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
10 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
11 import WebSocket
, { ClientOptions
, Data
, OPEN
} from
'ws';
13 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
14 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
15 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
16 import ChargingStationInfo from
'../types/ChargingStationInfo';
17 import { ClientRequestArgs
} from
'http';
18 import Configuration from
'../utils/Configuration';
19 import Constants from
'../utils/Constants';
20 import { ErrorType
} from
'../types/ocpp/ErrorType';
21 import FileUtils from
'../utils/FileUtils';
22 import { MessageType
} from
'../types/ocpp/MessageType';
23 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
24 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
25 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
26 import OCPPError from
'./ocpp/OCPPError';
27 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
28 import OCPPRequestService from
'./ocpp/OCPPRequestService';
29 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
30 import PerformanceStatistics from
'../performance/PerformanceStatistics';
31 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
32 import { URL
} from
'url';
33 import Utils from
'../utils/Utils';
34 import crypto from
'crypto';
36 import logger from
'../utils/Logger';
37 import path from
'path';
39 export default class ChargingStation
{
40 public stationTemplateFile
: string;
41 public authorizedTags
: string[];
42 public stationInfo
!: ChargingStationInfo
;
43 public connectors
: Connectors
;
44 public configuration
!: ChargingStationConfiguration
;
45 public wsConnection
!: WebSocket
;
46 public requests
: Map
<string, Request
>;
47 public performanceStatistics
!: PerformanceStatistics
;
48 public heartbeatSetInterval
!: NodeJS
.Timeout
;
49 public ocppRequestService
!: OCPPRequestService
;
50 private index
: number;
51 private bootNotificationRequest
!: BootNotificationRequest
;
52 private bootNotificationResponse
!: BootNotificationResponse
| null;
53 private connectorsConfigurationHash
!: string;
54 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
55 private messageQueue
: string[];
56 private wsConnectionUrl
!: URL
;
57 private wsConnectionRestarted
: boolean;
58 private stopped
: boolean;
59 private autoReconnectRetryCount
: number;
60 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
61 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
63 constructor(index
: number, stationTemplateFile
: string) {
65 this.stationTemplateFile
= stationTemplateFile
;
66 this.connectors
= {} as Connectors
;
70 this.wsConnectionRestarted
= false;
71 this.autoReconnectRetryCount
= 0;
73 this.requests
= new Map
<string, Request
>();
74 this.messageQueue
= new Array<string>();
76 this.authorizedTags
= this.getAuthorizedTags();
79 public logPrefix(): string {
80 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
83 public getBootNotificationRequest(): BootNotificationRequest
{
84 return this.bootNotificationRequest
;
87 public getRandomTagId(): string {
88 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
89 return this.authorizedTags
[index
];
92 public hasAuthorizedTags(): boolean {
93 return !Utils
.isEmptyArray(this.authorizedTags
);
96 public getEnableStatistics(): boolean | undefined {
97 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
100 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
101 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
104 public getNumberOfPhases(): number | undefined {
105 switch (this.getCurrentOutType()) {
107 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
113 public isWebSocketConnectionOpened(): boolean {
114 return this.wsConnection
?.readyState
=== OPEN
;
117 public isRegistered(): boolean {
118 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
121 public isChargingStationAvailable(): boolean {
122 return this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
;
125 public isConnectorAvailable(id
: number): boolean {
126 return this.getConnector(id
).availability
=== AvailabilityType
.OPERATIVE
;
129 public getConnector(id
: number): Connector
{
130 return this.connectors
[id
];
133 public getCurrentOutType(): CurrentType
| undefined {
134 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
137 public getVoltageOut(): number | undefined {
138 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
139 let defaultVoltageOut
: number;
140 switch (this.getCurrentOutType()) {
142 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
145 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
148 logger
.error(errMsg
);
149 throw new Error(errMsg
);
151 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
154 public getTransactionIdTag(transactionId
: number): string | undefined {
155 for (const connector
in this.connectors
) {
156 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
157 return this.getConnector(Utils
.convertToInt(connector
)).transactionIdTag
;
162 public getOutOfOrderEndMeterValues(): boolean {
163 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
166 public getBeginEndMeterValues(): boolean {
167 return this.stationInfo
.beginEndMeterValues
?? false;
170 public getMeteringPerTransaction(): boolean {
171 return this.stationInfo
.meteringPerTransaction
?? true;
174 public getTransactionDataMeterValues(): boolean {
175 return this.stationInfo
.transactionDataMeterValues
?? false;
178 public getMainVoltageMeterValues(): boolean {
179 return this.stationInfo
.mainVoltageMeterValues
?? true;
182 public getPhaseLineToLineVoltageMeterValues(): boolean {
183 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
186 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
187 if (this.getMeteringPerTransaction()) {
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
)).transactionEnergyActiveImportRegisterValue
;
194 for (const connector
in this.connectors
) {
195 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
196 return this.getConnector(Utils
.convertToInt(connector
)).energyActiveImportRegisterValue
;
201 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
202 if (this.getMeteringPerTransaction()) {
203 return this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
;
205 return this.getConnector(connectorId
).energyActiveImportRegisterValue
;
208 public getAuthorizeRemoteTxRequests(): boolean {
209 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
210 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
213 public getLocalAuthListEnabled(): boolean {
214 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
215 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
218 public restartWebSocketPing(): void {
219 // Stop WebSocket ping
220 this.stopWebSocketPing();
221 // Start WebSocket ping
222 this.startWebSocketPing();
225 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
226 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
227 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
228 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
231 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
232 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`);
235 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnector(connectorId
).MeterValues
;
236 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
237 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
238 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
239 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
240 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
241 return sampledValueTemplates[index];
242 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
243 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
244 return sampledValueTemplates[index];
245 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
246 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
247 return sampledValueTemplates[index];
250 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
251 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand
'${measurand}' in template on connectorId ${connectorId}
`;
252 logger.error(errorMsg);
253 throw new Error(errorMsg);
255 logger.debug(`${this.logPrefix()} No MeterValues
for measurand
'${measurand}' ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
258 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
259 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
262 public startHeartbeat(): void {
263 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
264 // eslint-disable-next-line @typescript-eslint/no-misused-promises
265 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
266 await this.ocppRequestService
.sendHeartbeat();
267 }, this.getHeartbeatInterval());
268 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
269 } else if (this.heartbeatSetInterval
) {
270 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
272 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
276 public restartHeartbeat(): void {
278 this.stopHeartbeat();
280 this.startHeartbeat();
283 public startMeterValues(connectorId
: number, interval
: number): void {
284 if (connectorId
=== 0) {
285 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
288 if (!this.getConnector(connectorId
)) {
289 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
292 if (!this.getConnector(connectorId
)?.transactionStarted
) {
293 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
295 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
296 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
300 // eslint-disable-next-line @typescript-eslint/no-misused-promises
301 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
302 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
);
305 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
309 public start(): void {
310 if (this.getEnableStatistics()) {
311 this.performanceStatistics
.start();
313 this.openWSConnection();
314 // Monitor authorization file
315 this.startAuthorizationFileMonitoring();
316 // Monitor station template file
317 this.startStationTemplateFileMonitoring();
318 // Handle Socket incoming messages
319 this.wsConnection
.on('message', this.onMessage
.bind(this));
320 // Handle Socket error
321 this.wsConnection
.on('error', this.onError
.bind(this));
322 // Handle Socket close
323 this.wsConnection
.on('close', this.onClose
.bind(this));
324 // Handle Socket opening connection
325 this.wsConnection
.on('open', this.onOpen
.bind(this));
326 // Handle Socket ping
327 this.wsConnection
.on('ping', this.onPing
.bind(this));
328 // Handle Socket pong
329 this.wsConnection
.on('pong', this.onPong
.bind(this));
332 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
333 // Stop message sequence
334 await this.stopMessageSequence(reason
);
335 for (const connector
in this.connectors
) {
336 if (Utils
.convertToInt(connector
) > 0) {
337 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
338 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.UNAVAILABLE
;
341 if (this.isWebSocketConnectionOpened()) {
342 this.wsConnection
.close();
344 if (this.getEnableStatistics()) {
345 this.performanceStatistics
.stop();
347 this.bootNotificationResponse
= null;
351 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
352 return this.configuration
.configurationKey
.find((configElement
) => {
353 if (caseInsensitive
) {
354 return configElement
.key
.toLowerCase() === key
.toLowerCase();
356 return configElement
.key
=== key
;
360 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
361 const keyFound
= this.getConfigurationKey(key
);
363 this.configuration
.configurationKey
.push({
371 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
375 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
376 const keyFound
= this.getConfigurationKey(key
);
378 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
379 this.configuration
.configurationKey
[keyIndex
].value
= value
;
381 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
385 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
386 let cpReplaced
= false;
387 if (!Utils
.isEmptyArray(this.getConnector(connectorId
).chargingProfiles
)) {
388 this.getConnector(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
389 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
390 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
391 this.getConnector(connectorId
).chargingProfiles
[index
] = cp
;
396 !cpReplaced
&& this.getConnector(connectorId
).chargingProfiles
?.push(cp
);
399 public resetTransactionOnConnector(connectorId
: number): void {
400 this.getConnector(connectorId
).authorized
= false;
401 this.getConnector(connectorId
).transactionStarted
= false;
402 delete this.getConnector(connectorId
).authorizeIdTag
;
403 delete this.getConnector(connectorId
).transactionId
;
404 delete this.getConnector(connectorId
).transactionIdTag
;
405 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
406 delete this.getConnector(connectorId
).transactionBeginMeterValue
;
407 this.stopMeterValues(connectorId
);
410 public addToMessageQueue(message
: string): void {
412 // Handle dups in message queue
413 for (const bufferedMessage
of this.messageQueue
) {
414 // Message already in the queue
415 if (message
=== bufferedMessage
) {
422 this.messageQueue
.push(message
);
426 private flushMessageQueue() {
427 if (!Utils
.isEmptyArray(this.messageQueue
)) {
428 this.messageQueue
.forEach((message
, index
) => {
429 this.messageQueue
.splice(index
, 1);
430 // TODO: evaluate the need to track performance
431 this.wsConnection
.send(message
);
436 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
437 // In case of multiple instances: add instance index to charging station id
438 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
439 const idSuffix
= stationTemplate
.nameSuffix
?? '';
440 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
443 private buildStationInfo(): ChargingStationInfo
{
444 let stationTemplateFromFile
: ChargingStationTemplate
;
446 // Load template file
447 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
448 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
449 fs
.closeSync(fileDescriptor
);
451 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
453 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
454 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
455 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
456 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplateFromFile
.power
.length
);
457 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
458 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
459 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
461 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
462 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
463 ? stationTemplateFromFile
.power
* 1000
464 : stationTemplateFromFile
.power
;
466 delete stationInfo
.power
;
467 delete stationInfo
.powerUnit
;
468 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
469 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
473 private getOCPPVersion(): OCPPVersion
{
474 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
477 private handleUnsupportedVersion(version
: OCPPVersion
) {
478 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
479 logger
.error(errMsg
);
480 throw new Error(errMsg
);
483 private initialize(): void {
484 this.stationInfo
= this.buildStationInfo();
485 this.bootNotificationRequest
= {
486 chargePointModel
: this.stationInfo
.chargePointModel
,
487 chargePointVendor
: this.stationInfo
.chargePointVendor
,
488 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
489 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
491 this.configuration
= this.getTemplateChargingStationConfiguration();
492 this.wsConnectionUrl
= new URL(this.getSupervisionURL().href
+ '/' + this.stationInfo
.chargingStationId
);
493 // Build connectors if needed
494 const maxConnectors
= this.getMaxNumberOfConnectors();
495 if (maxConnectors
<= 0) {
496 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
498 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
499 if (templateMaxConnectors
<= 0) {
500 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
502 if (!this.stationInfo
.Connectors
[0]) {
503 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
506 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
507 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
508 this.stationInfo
.randomConnectors
= true;
510 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
511 // FIXME: Handle shrinking the number of connectors
512 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
513 this.connectorsConfigurationHash
= connectorsConfigHash
;
514 // Add connector Id 0
515 let lastConnector
= '0';
516 for (lastConnector
in this.stationInfo
.Connectors
) {
517 if (Utils
.convertToInt(lastConnector
) === 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
518 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
519 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
520 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
521 this.connectors
[lastConnector
].chargingProfiles
= [];
525 // Generate all connectors
526 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
527 for (let index
= 1; index
<= maxConnectors
; index
++) {
528 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
529 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorId
]);
530 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
531 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
532 this.connectors
[index
].chargingProfiles
= [];
537 // Avoid duplication of connectors related information
538 delete this.stationInfo
.Connectors
;
539 // Initialize transaction attributes on connectors
540 for (const connector
in this.connectors
) {
541 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
542 this.initTransactionAttributesOnConnector(Utils
.convertToInt(connector
));
545 switch (this.getOCPPVersion()) {
546 case OCPPVersion
.VERSION_16
:
547 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
548 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
551 this.handleUnsupportedVersion(this.getOCPPVersion());
555 this.initOCPPParameters();
556 if (this.stationInfo
.autoRegister
) {
557 this.bootNotificationResponse
= {
558 currentTime
: new Date().toISOString(),
559 interval
: this.getHeartbeatInterval() / 1000,
560 status: RegistrationStatus
.ACCEPTED
563 this.stationInfo
.powerDivider
= this.getPowerDivider();
564 if (this.getEnableStatistics()) {
565 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
569 private initOCPPParameters(): void {
570 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
571 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
573 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
574 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
575 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
577 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
578 const connectorPhaseRotation
= [];
579 for (const connector
in this.connectors
) {
581 if (Utils
.convertToInt(connector
) === 0 && this.getNumberOfPhases() === 0) {
582 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
583 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 0) {
584 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
586 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 1) {
587 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
588 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 3) {
589 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
592 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
594 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
595 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
597 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
598 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
599 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
601 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
602 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
606 private async onOpen(): Promise
<void> {
607 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
608 if (!this.isRegistered()) {
609 // Send BootNotification
610 let registrationRetryCount
= 0;
612 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
613 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
614 if (!this.isRegistered()) {
615 registrationRetryCount
++;
616 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
618 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
620 if (this.isRegistered()) {
621 await this.startMessageSequence();
622 this.stopped
&& (this.stopped
= false);
623 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
624 this.flushMessageQueue();
627 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
629 this.autoReconnectRetryCount
= 0;
630 this.wsConnectionRestarted
= false;
633 private async onClose(code
: number, reason
: string): Promise
<void> {
636 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
637 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
638 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
639 this.autoReconnectRetryCount
= 0;
643 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
644 await this.reconnect(code
);
649 private async onMessage(data
: Data
): 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
>;
654 let cachedRequest
: Request
;
657 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
658 if (Utils
.isIterable(request
)) {
660 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
662 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
664 // Check the Type of message
665 switch (messageType
) {
667 case MessageType
.CALL_MESSAGE
:
668 if (this.getEnableStatistics()) {
669 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
672 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
675 case MessageType
.CALL_RESULT_MESSAGE
:
677 cachedRequest
= this.requests
.get(messageId
);
678 if (Utils
.isIterable(cachedRequest
)) {
679 [responseCallback
, , requestPayload
] = cachedRequest
;
681 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Response request for message id ${messageId} is not iterable`, commandName
);
683 if (!responseCallback
) {
685 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response request for unknown message id ${messageId}`, commandName
);
687 this.requests
.delete(messageId
);
688 responseCallback(commandName
, requestPayload
);
691 case MessageType
.CALL_ERROR_MESSAGE
:
692 cachedRequest
= this.requests
.get(messageId
);
693 if (!cachedRequest
) {
695 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error request for unknown message id ${messageId}`);
697 if (Utils
.isIterable(cachedRequest
)) {
698 [, rejectCallback
] = cachedRequest
;
700 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Error request for message id ${messageId} is not iterable`);
702 this.requests
.delete(messageId
);
703 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), null, errorDetails
));
707 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
708 logger
.error(errMsg
);
709 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
713 logger
.error('%s Incoming request message %j processing error %j on content type %j', this.logPrefix(), data
, error
, this.requests
.get(messageId
));
715 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
719 private onPing(): void {
720 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
723 private onPong(): void {
724 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
727 private async onError(error
: WSError
): Promise
<void> {
728 logger
.error(this.logPrefix() + ' Socket error: %j', error
);
729 // switch (error.code) {
730 // case 'ECONNREFUSED':
731 // await this.reconnect(error);
736 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
737 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
740 private getAuthorizationFile(): string | undefined {
741 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
744 private getAuthorizedTags(): string[] {
745 let authorizedTags
: string[] = [];
746 const authorizationFile
= this.getAuthorizationFile();
747 if (authorizationFile
) {
749 // Load authorization file
750 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
751 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
752 fs
.closeSync(fileDescriptor
);
754 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
757 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
759 return authorizedTags
;
762 private getUseConnectorId0(): boolean | undefined {
763 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
766 private getNumberOfRunningTransactions(): number {
768 for (const connector
in this.connectors
) {
769 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
777 private getConnectionTimeout(): number | undefined {
778 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
779 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
781 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
784 // -1 for unlimited, 0 for disabling
785 private getAutoReconnectMaxRetries(): number | undefined {
786 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
787 return this.stationInfo
.autoReconnectMaxRetries
;
789 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
790 return Configuration
.getAutoReconnectMaxRetries();
796 private getRegistrationMaxRetries(): number | undefined {
797 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
798 return this.stationInfo
.registrationMaxRetries
;
803 private getPowerDivider(): number {
804 let powerDivider
= this.getNumberOfConnectors();
805 if (this.stationInfo
.powerSharedByConnectors
) {
806 powerDivider
= this.getNumberOfRunningTransactions();
811 private getTemplateMaxNumberOfConnectors(): number {
812 return Object.keys(this.stationInfo
.Connectors
).length
;
815 private getMaxNumberOfConnectors(): number {
816 let maxConnectors
= 0;
817 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
818 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
819 // Distribute evenly the number of connectors
820 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
821 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
822 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
824 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
826 return maxConnectors
;
829 private getNumberOfConnectors(): number {
830 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
833 private async startMessageSequence(): Promise
<void> {
834 // Start WebSocket ping
835 this.startWebSocketPing();
837 this.startHeartbeat();
838 // Initialize connectors status
839 for (const connector
in this.connectors
) {
840 if (Utils
.convertToInt(connector
) === 0) {
842 } else if (!this.stopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
843 // Send status in template at startup
844 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
845 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
846 } else if (this.stopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
847 // Send status in template after reset
848 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
849 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
850 } else if (!this.stopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
851 // Send previous status at template reload
852 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
854 // Send default status
855 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
856 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
860 this.startAutomaticTransactionGenerator();
863 private startAutomaticTransactionGenerator() {
864 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
865 if (!this.automaticTransactionGenerator
) {
866 this.automaticTransactionGenerator
= new AutomaticTransactionGenerator(this);
868 if (!this.automaticTransactionGenerator
.started
) {
869 this.automaticTransactionGenerator
.start();
874 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
875 // Stop WebSocket ping
876 this.stopWebSocketPing();
878 this.stopHeartbeat();
880 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
881 this.automaticTransactionGenerator
&&
882 this.automaticTransactionGenerator
.started
) {
883 await this.automaticTransactionGenerator
.stop(reason
);
885 for (const connector
in this.connectors
) {
886 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
887 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
888 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
889 this.getTransactionIdTag(transactionId
), reason
);
895 private startWebSocketPing(): void {
896 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
897 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
899 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
900 this.webSocketPingSetInterval
= setInterval(() => {
901 if (this.isWebSocketConnectionOpened()) {
902 this.wsConnection
.ping((): void => { /* This is intentional */ });
904 }, webSocketPingInterval
* 1000);
905 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.formatDurationSeconds(webSocketPingInterval
));
906 } else if (this.webSocketPingSetInterval
) {
907 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.formatDurationSeconds(webSocketPingInterval
) + ' already started');
909 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
913 private stopWebSocketPing(): void {
914 if (this.webSocketPingSetInterval
) {
915 clearInterval(this.webSocketPingSetInterval
);
919 private getSupervisionURL(): URL
{
920 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
922 if (!Utils
.isEmptyArray(supervisionUrls
)) {
923 if (Configuration
.getDistributeStationsToTenantsEqually()) {
924 indexUrl
= this.index
% supervisionUrls
.length
;
927 indexUrl
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
929 return new URL(supervisionUrls
[indexUrl
]);
931 return new URL(supervisionUrls
as string);
934 private getHeartbeatInterval(): number | undefined {
935 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
936 if (HeartbeatInterval
) {
937 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
939 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
940 if (HeartBeatInterval
) {
941 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
943 !this.stationInfo
.autoRegister
&& logger
.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
944 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
947 private stopHeartbeat(): void {
948 if (this.heartbeatSetInterval
) {
949 clearInterval(this.heartbeatSetInterval
);
953 private openWSConnection(options
?: ClientOptions
& ClientRequestArgs
, forceCloseOpened
= false): void {
954 options
= options
?? {};
955 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
956 if (!Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) && !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)) {
957 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
959 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
960 this.wsConnection
.close();
963 switch (this.getOCPPVersion()) {
964 case OCPPVersion
.VERSION_16
:
965 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
968 this.handleUnsupportedVersion(this.getOCPPVersion());
971 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
972 logger
.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString());
975 private stopMeterValues(connectorId
: number) {
976 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
977 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
981 private startAuthorizationFileMonitoring(): void {
982 const authorizationFile
= this.getAuthorizationFile();
983 if (authorizationFile
) {
985 fs
.watch(authorizationFile
, (event
, filename
) => {
986 if (filename
&& event
=== 'change') {
988 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
989 // Initialize authorizedTags
990 this.authorizedTags
= this.getAuthorizedTags();
992 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
997 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
1000 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
1004 private startStationTemplateFileMonitoring(): void {
1006 fs
.watch(this.stationTemplateFile
, async (event
, filename
): Promise
<void> => {
1007 if (filename
&& event
=== 'change') {
1009 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
1013 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1014 this.automaticTransactionGenerator
) {
1015 await this.automaticTransactionGenerator
.stop();
1017 this.startAutomaticTransactionGenerator();
1018 if (this.getEnableStatistics()) {
1019 this.performanceStatistics
.restart();
1021 this.performanceStatistics
.stop();
1023 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1025 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
1030 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
1034 private getReconnectExponentialDelay(): boolean | undefined {
1035 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
1038 private async reconnect(code
: number): Promise
<void> {
1039 // Stop WebSocket ping
1040 this.stopWebSocketPing();
1042 this.stopHeartbeat();
1043 // Stop the ATG if needed
1044 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1045 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1046 this.automaticTransactionGenerator
&&
1047 this.automaticTransactionGenerator
.started
) {
1048 await this.automaticTransactionGenerator
.stop();
1050 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1051 this.autoReconnectRetryCount
++;
1052 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
1053 const reconnectTimeout
= reconnectDelay
- 100;
1054 logger
.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`);
1055 await Utils
.sleep(reconnectDelay
);
1056 logger
.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
1057 this.openWSConnection({ handshakeTimeout
: reconnectTimeout
}, true);
1058 this.wsConnectionRestarted
= true;
1059 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1060 logger
.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1064 private initTransactionAttributesOnConnector(connectorId
: number): void {
1065 this.getConnector(connectorId
).authorized
= false;
1066 this.getConnector(connectorId
).transactionStarted
= false;
1067 this.getConnector(connectorId
).energyActiveImportRegisterValue
= 0;
1068 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;