1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/Responses';
4 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
5 import ChargingStationTemplate
, { CurrentType
, PowerUnits
, Voltage
} from
'../types/ChargingStationTemplate';
6 import { ConnectorPhaseRotation
, StandardParametersKey
, SupportedFeatureProfiles
} from
'../types/ocpp/Configuration';
7 import Connectors
, { Connector
, SampledValueTemplate
} from
'../types/Connectors';
8 import { MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
9 import Requests
, { AvailabilityType
, BootNotificationRequest
, IncomingRequest
, IncomingRequestCommand
} from
'../types/ocpp/Requests';
10 import WebSocket
, { ClientOptions
, MessageEvent
} from
'ws';
12 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
13 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
14 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
15 import ChargingStationInfo from
'../types/ChargingStationInfo';
16 import { ClientRequestArgs
} from
'http';
17 import Configuration from
'../utils/Configuration';
18 import Constants from
'../utils/Constants';
19 import { ErrorType
} from
'../types/ocpp/ErrorType';
20 import FileUtils from
'../utils/FileUtils';
21 import { MessageType
} from
'../types/ocpp/MessageType';
22 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
23 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
24 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
25 import OCPPError from
'./ocpp/OCPPError';
26 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
27 import OCPPRequestService from
'./ocpp/OCPPRequestService';
28 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
29 import PerformanceStatistics from
'../performance/PerformanceStatistics';
30 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
31 import { URL
} from
'url';
32 import Utils from
'../utils/Utils';
33 import { WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
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 hasStopped
: boolean;
46 public wsConnection
!: WebSocket
;
47 public requests
: Requests
;
48 public messageQueue
: string[];
49 public performanceStatistics
!: PerformanceStatistics
;
50 public heartbeatSetInterval
!: NodeJS
.Timeout
;
51 public ocppIncomingRequestService
!: OCPPIncomingRequestService
;
52 public ocppRequestService
!: OCPPRequestService
;
53 private index
: number;
54 private bootNotificationRequest
!: BootNotificationRequest
;
55 private bootNotificationResponse
!: BootNotificationResponse
| null;
56 private connectorsConfigurationHash
!: string;
57 private wsConnectionUrl
!: URL
;
58 private hasSocketRestarted
: boolean;
59 private autoReconnectRetryCount
: number;
60 private automaticTransactionGeneration
!: AutomaticTransactionGenerator
;
61 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
63 constructor(index
: number, stationTemplateFile
: string) {
65 this.stationTemplateFile
= stationTemplateFile
;
66 this.connectors
= {} as Connectors
;
69 this.hasStopped
= false;
70 this.hasSocketRestarted
= false;
71 this.autoReconnectRetryCount
= 0;
73 this.requests
= {} as Requests
;
74 this.messageQueue
= [] as 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(Math.random() * 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
=== WebSocket
.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}
`);
240 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
241 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
242 return sampledValueTemplates[index];
243 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
244 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
245 return sampledValueTemplates[index];
246 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
247 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
248 return sampledValueTemplates[index];
251 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
252 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand ${measurand}
in template on connectorId ${connectorId}
`;
253 logger.error(errorMsg);
254 throw new Error(errorMsg);
256 logger.debug(`${this.logPrefix()} No MeterValues
for measurand ${measurand} ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
259 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
260 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
263 public startHeartbeat(): void {
264 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
265 // eslint-disable-next-line @typescript-eslint/no-misused-promises
266 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
267 await this.ocppRequestService
.sendHeartbeat();
268 }, this.getHeartbeatInterval());
269 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
270 } else if (this.heartbeatSetInterval
) {
271 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
273 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
277 public restartHeartbeat(): void {
279 this.stopHeartbeat();
281 this.startHeartbeat();
284 public startMeterValues(connectorId
: number, interval
: number): void {
285 if (connectorId
=== 0) {
286 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
289 if (!this.getConnector(connectorId
)) {
290 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
293 if (!this.getConnector(connectorId
)?.transactionStarted
) {
294 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
296 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
297 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
301 // eslint-disable-next-line @typescript-eslint/no-misused-promises
302 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
303 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
);
306 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
310 public start(): void {
311 if (this.getEnableStatistics()) {
312 this.performanceStatistics
.start();
314 this.openWSConnection();
315 // Monitor authorization file
316 this.startAuthorizationFileMonitoring();
317 // Monitor station template file
318 this.startStationTemplateFileMonitoring();
319 // Handle Socket incoming messages
320 this.wsConnection
.on('message', this.onMessage
.bind(this));
321 // Handle Socket error
322 this.wsConnection
.on('error', this.onError
.bind(this));
323 // Handle Socket close
324 this.wsConnection
.on('close', this.onClose
.bind(this));
325 // Handle Socket opening connection
326 this.wsConnection
.on('open', this.onOpen
.bind(this));
327 // Handle Socket ping
328 this.wsConnection
.on('ping', this.onPing
.bind(this));
329 // Handle Socket pong
330 this.wsConnection
.on('pong', this.onPong
.bind(this));
333 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
334 // Stop message sequence
335 await this.stopMessageSequence(reason
);
336 for (const connector
in this.connectors
) {
337 if (Utils
.convertToInt(connector
) > 0) {
338 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
339 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.UNAVAILABLE
;
342 if (this.isWebSocketConnectionOpened()) {
343 this.wsConnection
.close();
345 if (this.getEnableStatistics()) {
346 this.performanceStatistics
.stop();
348 this.bootNotificationResponse
= null;
349 this.hasStopped
= true;
352 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
353 return this.configuration
.configurationKey
.find((configElement
) => {
354 if (caseInsensitive
) {
355 return configElement
.key
.toLowerCase() === key
.toLowerCase();
357 return configElement
.key
=== key
;
361 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
362 const keyFound
= this.getConfigurationKey(key
);
364 this.configuration
.configurationKey
.push({
372 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
376 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
377 const keyFound
= this.getConfigurationKey(key
);
379 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
380 this.configuration
.configurationKey
[keyIndex
].value
= value
;
382 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
386 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
387 let cpReplaced
= false;
388 if (!Utils
.isEmptyArray(this.getConnector(connectorId
).chargingProfiles
)) {
389 this.getConnector(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
390 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
391 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
392 this.getConnector(connectorId
).chargingProfiles
[index
] = cp
;
397 !cpReplaced
&& this.getConnector(connectorId
).chargingProfiles
?.push(cp
);
400 public resetTransactionOnConnector(connectorId
: number): void {
401 this.getConnector(connectorId
).authorized
= false;
402 this.getConnector(connectorId
).transactionStarted
= false;
403 delete this.getConnector(connectorId
).authorizeIdTag
;
404 delete this.getConnector(connectorId
).transactionId
;
405 delete this.getConnector(connectorId
).transactionIdTag
;
406 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
407 delete this.getConnector(connectorId
).transactionBeginMeterValue
;
408 this.stopMeterValues(connectorId
);
411 public addToMessageQueue(message
: string): void {
413 // Handle dups in message queue
414 for (const bufferedMessage
of this.messageQueue
) {
415 // Message already in the queue
416 if (message
=== bufferedMessage
) {
423 this.messageQueue
.push(message
);
427 private flushMessageQueue() {
428 if (!Utils
.isEmptyArray(this.messageQueue
)) {
429 this.messageQueue
.forEach((message
, index
) => {
430 this.messageQueue
.splice(index
, 1);
431 // TODO: evaluate the need to track performance
432 this.wsConnection
.send(message
);
437 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
438 // In case of multiple instances: add instance index to charging station id
439 let instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
440 instanceIndex
= instanceIndex
> 0 ? instanceIndex
: '';
441 const idSuffix
= stationTemplate
.nameSuffix
?? '';
442 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
445 private buildStationInfo(): ChargingStationInfo
{
446 let stationTemplateFromFile
: ChargingStationTemplate
;
448 // Load template file
449 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
450 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
451 fs
.closeSync(fileDescriptor
);
453 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
455 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
456 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
457 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
458 const powerArrayRandomIndex
= Math.floor(Math.random() * stationTemplateFromFile
.power
.length
);
459 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
460 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
461 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
463 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
464 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
465 ? stationTemplateFromFile
.power
* 1000
466 : stationTemplateFromFile
.power
;
468 delete stationInfo
.power
;
469 delete stationInfo
.powerUnit
;
470 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
471 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
475 private getOCPPVersion(): OCPPVersion
{
476 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
479 private handleUnsupportedVersion(version
: OCPPVersion
) {
480 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
481 logger
.error(errMsg
);
482 throw new Error(errMsg
);
485 private initialize(): void {
486 this.stationInfo
= this.buildStationInfo();
487 this.bootNotificationRequest
= {
488 chargePointModel
: this.stationInfo
.chargePointModel
,
489 chargePointVendor
: this.stationInfo
.chargePointVendor
,
490 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
491 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
493 this.configuration
= this.getTemplateChargingStationConfiguration();
494 this.wsConnectionUrl
= new URL(this.getSupervisionURL().href
+ '/' + this.stationInfo
.chargingStationId
);
495 // Build connectors if needed
496 const maxConnectors
= this.getMaxNumberOfConnectors();
497 if (maxConnectors
<= 0) {
498 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
500 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
501 if (templateMaxConnectors
<= 0) {
502 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
504 if (!this.stationInfo
.Connectors
[0]) {
505 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
508 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
509 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
510 this.stationInfo
.randomConnectors
= true;
512 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
513 // FIXME: Handle shrinking the number of connectors
514 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
515 this.connectorsConfigurationHash
= connectorsConfigHash
;
516 // Add connector Id 0
517 let lastConnector
= '0';
518 for (lastConnector
in this.stationInfo
.Connectors
) {
519 if (Utils
.convertToInt(lastConnector
) === 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
520 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
521 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
522 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
523 this.connectors
[lastConnector
].chargingProfiles
= [];
527 // Generate all connectors
528 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
529 for (let index
= 1; index
<= maxConnectors
; index
++) {
530 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
531 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorId
]);
532 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
533 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
534 this.connectors
[index
].chargingProfiles
= [];
539 // Avoid duplication of connectors related information
540 delete this.stationInfo
.Connectors
;
541 // Initialize transaction attributes on connectors
542 for (const connector
in this.connectors
) {
543 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
544 this.initTransactionAttributesOnConnector(Utils
.convertToInt(connector
));
547 switch (this.getOCPPVersion()) {
548 case OCPPVersion
.VERSION_16
:
549 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
550 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
553 this.handleUnsupportedVersion(this.getOCPPVersion());
557 this.initOCPPParameters();
558 if (this.stationInfo
.autoRegister
) {
559 this.bootNotificationResponse
= {
560 currentTime
: new Date().toISOString(),
561 interval
: this.getHeartbeatInterval() / 1000,
562 status: RegistrationStatus
.ACCEPTED
565 this.stationInfo
.powerDivider
= this.getPowerDivider();
566 if (this.getEnableStatistics()) {
567 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
571 private initOCPPParameters(): void {
572 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
573 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
575 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
576 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
577 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
579 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
580 const connectorPhaseRotation
= [];
581 for (const connector
in this.connectors
) {
583 if (Utils
.convertToInt(connector
) === 0 && this.getNumberOfPhases() === 0) {
584 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
585 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 0) {
586 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
588 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 1) {
589 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
590 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 3) {
591 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
594 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
596 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
597 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
599 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
600 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
601 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
603 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
604 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
608 private async onOpen(): Promise
<void> {
609 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
610 if (!this.isRegistered()) {
611 // Send BootNotification
612 let registrationRetryCount
= 0;
614 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
615 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
616 if (!this.isRegistered()) {
617 registrationRetryCount
++;
618 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
620 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
622 if (this.isRegistered()) {
623 await this.startMessageSequence();
624 this.hasStopped
&& (this.hasStopped
= false);
625 if (this.hasSocketRestarted
&& this.isWebSocketConnectionOpened()) {
626 this.flushMessageQueue();
629 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
631 this.autoReconnectRetryCount
= 0;
632 this.hasSocketRestarted
= false;
635 private async onClose(closeEvent
: any): Promise
<void> {
636 switch (closeEvent
) {
637 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
638 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
639 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
640 this.autoReconnectRetryCount
= 0;
642 default: // Abnormal close
643 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
644 await this.reconnect(closeEvent
);
649 private async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
650 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
651 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
652 let rejectCallback
: (error
: OCPPError
) => void;
653 let requestPayload
: Record
<string, unknown
>;
656 const request
= JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
657 if (Utils
.isIterable(request
)) {
659 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
661 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
663 // Check the Type of message
664 switch (messageType
) {
666 case MessageType
.CALL_MESSAGE
:
667 if (this.getEnableStatistics()) {
668 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
671 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
674 case MessageType
.CALL_RESULT_MESSAGE
:
676 if (Utils
.isIterable(this.requests
[messageId
])) {
677 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
679 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Response request for message id ${messageId} is not iterable`, commandName
);
681 if (!responseCallback
) {
683 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response request for unknown message id ${messageId}`, commandName
);
685 delete this.requests
[messageId
];
686 responseCallback(commandName
, requestPayload
);
689 case MessageType
.CALL_ERROR_MESSAGE
:
690 if (!this.requests
[messageId
]) {
692 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error request for unknown message id ${messageId}`);
694 if (Utils
.isIterable(this.requests
[messageId
])) {
695 [, rejectCallback
] = this.requests
[messageId
];
697 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Error request for message id ${messageId} is not iterable`);
699 delete this.requests
[messageId
];
700 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), null, errorDetails
));
704 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
705 logger
.error(errMsg
);
706 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
710 logger
.error('%s Incoming request message %j processing error %j on content type %j', this.logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
712 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
716 private onPing(): void {
717 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
720 private onPong(): void {
721 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
724 private async onError(errorEvent
: any): Promise
<void> {
725 logger
.error(this.logPrefix() + ' Socket error: %j', errorEvent
);
726 // switch (errorEvent.code) {
727 // case 'ECONNREFUSED':
728 // await this._reconnect(errorEvent);
733 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
734 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
737 private getAuthorizationFile(): string | undefined {
738 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
741 private getAuthorizedTags(): string[] {
742 let authorizedTags
: string[] = [];
743 const authorizationFile
= this.getAuthorizationFile();
744 if (authorizationFile
) {
746 // Load authorization file
747 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
748 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
749 fs
.closeSync(fileDescriptor
);
751 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
754 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
756 return authorizedTags
;
759 private getUseConnectorId0(): boolean | undefined {
760 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
763 private getNumberOfRunningTransactions(): number {
765 for (const connector
in this.connectors
) {
766 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
774 private getConnectionTimeout(): number | undefined {
775 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
776 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
778 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
781 // -1 for unlimited, 0 for disabling
782 private getAutoReconnectMaxRetries(): number | undefined {
783 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
784 return this.stationInfo
.autoReconnectMaxRetries
;
786 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
787 return Configuration
.getAutoReconnectMaxRetries();
793 private getRegistrationMaxRetries(): number | undefined {
794 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
795 return this.stationInfo
.registrationMaxRetries
;
800 private getPowerDivider(): number {
801 let powerDivider
= this.getNumberOfConnectors();
802 if (this.stationInfo
.powerSharedByConnectors
) {
803 powerDivider
= this.getNumberOfRunningTransactions();
808 private getTemplateMaxNumberOfConnectors(): number {
809 return Object.keys(this.stationInfo
.Connectors
).length
;
812 private getMaxNumberOfConnectors(): number {
813 let maxConnectors
= 0;
814 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
815 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
816 // Distribute evenly the number of connectors
817 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
818 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
819 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
821 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
823 return maxConnectors
;
826 private getNumberOfConnectors(): number {
827 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
830 private async startMessageSequence(): Promise
<void> {
831 // Start WebSocket ping
832 this.startWebSocketPing();
834 this.startHeartbeat();
835 // Initialize connectors status
836 for (const connector
in this.connectors
) {
837 if (Utils
.convertToInt(connector
) === 0) {
839 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
840 // Send status in template at startup
841 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
842 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
843 } else if (this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
844 // Send status in template after reset
845 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
846 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
847 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
848 // Send previous status at template reload
849 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
851 // Send default status
852 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
853 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
857 this.startAutomaticTransactionGenerator();
860 private startAutomaticTransactionGenerator() {
861 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
862 if (!this.automaticTransactionGeneration
) {
863 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
865 if (this.automaticTransactionGeneration
.timeToStop
) {
866 // The ATG might sleep
867 void this.automaticTransactionGeneration
.start();
872 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
873 // Stop WebSocket ping
874 this.stopWebSocketPing();
876 this.stopHeartbeat();
878 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
879 this.automaticTransactionGeneration
&&
880 !this.automaticTransactionGeneration
.timeToStop
) {
881 await this.automaticTransactionGeneration
.stop(reason
);
883 for (const connector
in this.connectors
) {
884 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
885 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
886 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
887 this.getTransactionIdTag(transactionId
), reason
);
893 private startWebSocketPing(): void {
894 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
895 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
897 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
898 this.webSocketPingSetInterval
= setInterval(() => {
899 if (this.isWebSocketConnectionOpened()) {
900 this.wsConnection
.ping((): void => { });
902 }, webSocketPingInterval
* 1000);
903 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
904 } else if (this.webSocketPingSetInterval
) {
905 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
907 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
911 private stopWebSocketPing(): void {
912 if (this.webSocketPingSetInterval
) {
913 clearInterval(this.webSocketPingSetInterval
);
917 private getSupervisionURL(): URL
{
918 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
920 if (!Utils
.isEmptyArray(supervisionUrls
)) {
921 if (Configuration
.getDistributeStationsToTenantsEqually()) {
922 indexUrl
= this.index
% supervisionUrls
.length
;
925 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
927 return new URL(supervisionUrls
[indexUrl
]);
929 return new URL(supervisionUrls
as string);
932 private getHeartbeatInterval(): number | undefined {
933 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
934 if (HeartbeatInterval
) {
935 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
937 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
938 if (HeartBeatInterval
) {
939 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
941 !this.stationInfo
.autoRegister
&& logger
.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
942 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
945 private stopHeartbeat(): void {
946 if (this.heartbeatSetInterval
) {
947 clearInterval(this.heartbeatSetInterval
);
951 private openWSConnection(options
?: ClientOptions
& ClientRequestArgs
, forceCloseOpened
= false): void {
952 options
= options
?? {};
953 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
954 if (!Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) && !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)) {
955 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
957 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
958 this.wsConnection
.close();
961 switch (this.getOCPPVersion()) {
962 case OCPPVersion
.VERSION_16
:
963 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
966 this.handleUnsupportedVersion(this.getOCPPVersion());
969 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
970 logger
.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString());
973 private stopMeterValues(connectorId
: number) {
974 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
975 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
979 private startAuthorizationFileMonitoring(): void {
980 const authorizationFile
= this.getAuthorizationFile();
981 if (authorizationFile
) {
983 fs
.watch(authorizationFile
).on('change', () => {
985 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
986 // Initialize authorizedTags
987 this.authorizedTags
= this.getAuthorizedTags();
989 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
993 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
996 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
1000 private startStationTemplateFileMonitoring(): void {
1002 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1003 fs
.watch(this.stationTemplateFile
).on('change', async (): Promise
<void> => {
1005 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
1009 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1010 this.automaticTransactionGeneration
) {
1011 await this.automaticTransactionGeneration
.stop();
1013 this.startAutomaticTransactionGenerator();
1014 if (this.getEnableStatistics()) {
1015 this.performanceStatistics
.restart();
1017 this.performanceStatistics
.stop();
1019 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1021 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
1025 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
1029 private getReconnectExponentialDelay(): boolean | undefined {
1030 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
1033 private async reconnect(error
: unknown
): Promise
<void> {
1034 // Stop WebSocket ping
1035 this.stopWebSocketPing();
1037 this.stopHeartbeat();
1038 // Stop the ATG if needed
1039 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1040 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1041 this.automaticTransactionGeneration
&&
1042 !this.automaticTransactionGeneration
.timeToStop
) {
1043 await this.automaticTransactionGeneration
.stop();
1045 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1046 this.autoReconnectRetryCount
++;
1047 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
1048 logger
.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
1049 await Utils
.sleep(reconnectDelay
);
1050 logger
.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
1051 this.openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
1052 this.hasSocketRestarted
= true;
1053 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1054 logger
.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1058 private initTransactionAttributesOnConnector(connectorId
: number): void {
1059 this.getConnector(connectorId
).authorized
= false;
1060 this.getConnector(connectorId
).transactionStarted
= false;
1061 this.getConnector(connectorId
).energyActiveImportRegisterValue
= 0;
1062 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;