1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { AvailabilityType
, BootNotificationRequest
, CachedRequest
, IncomingRequest
, IncomingRequestCommand
, RequestCommand
} 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 { ConnectorPhaseRotation
, StandardParametersKey
, SupportedFeatureProfiles
} from
'../types/ocpp/Configuration';
8 import { ConnectorStatus
, SampledValueTemplate
} from
'../types/Connectors';
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 readonly stationTemplateFile
: string;
41 public authorizedTags
: string[];
42 public stationInfo
!: ChargingStationInfo
;
43 public readonly connectors
: Map
<number, ConnectorStatus
>;
44 public configuration
!: ChargingStationConfiguration
;
45 public wsConnection
!: WebSocket
;
46 public readonly requests
: Map
<string, CachedRequest
>;
47 public performanceStatistics
!: PerformanceStatistics
;
48 public heartbeatSetInterval
!: NodeJS
.Timeout
;
49 public ocppRequestService
!: OCPPRequestService
;
50 private readonly index
: number;
51 private bootNotificationRequest
!: BootNotificationRequest
;
52 private bootNotificationResponse
!: BootNotificationResponse
| null;
53 private connectorsConfigurationHash
!: string;
54 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
55 private readonly 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
= new Map
<number, ConnectorStatus
>();
70 this.wsConnectionRestarted
= false;
71 this.autoReconnectRetryCount
= 0;
73 this.requests
= new Map
<string, CachedRequest
>();
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 getRandomIdTag(): 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.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
125 public isConnectorAvailable(id
: number): boolean {
126 return this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
129 public getNumberOfConnectors(): number {
130 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
133 public getConnectorStatus(id
: number): ConnectorStatus
{
134 return this.connectors
.get(id
);
137 public getCurrentOutType(): CurrentType
| undefined {
138 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
141 public getVoltageOut(): number | undefined {
142 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
143 let defaultVoltageOut
: number;
144 switch (this.getCurrentOutType()) {
146 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
149 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
152 logger
.error(errMsg
);
153 throw new Error(errMsg
);
155 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
158 public getTransactionIdTag(transactionId
: number): string | undefined {
159 for (const connectorId
of this.connectors
.keys()) {
160 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
161 return this.getConnectorStatus(connectorId
).transactionIdTag
;
166 public getOutOfOrderEndMeterValues(): boolean {
167 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
170 public getBeginEndMeterValues(): boolean {
171 return this.stationInfo
.beginEndMeterValues
?? false;
174 public getMeteringPerTransaction(): boolean {
175 return this.stationInfo
.meteringPerTransaction
?? true;
178 public getTransactionDataMeterValues(): boolean {
179 return this.stationInfo
.transactionDataMeterValues
?? false;
182 public getMainVoltageMeterValues(): boolean {
183 return this.stationInfo
.mainVoltageMeterValues
?? true;
186 public getPhaseLineToLineVoltageMeterValues(): boolean {
187 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
190 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
191 if (this.getMeteringPerTransaction()) {
192 for (const connectorId
of this.connectors
.keys()) {
193 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
194 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
198 for (const connectorId
of this.connectors
.keys()) {
199 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
200 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
205 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
206 if (this.getMeteringPerTransaction()) {
207 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
209 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
212 public getAuthorizeRemoteTxRequests(): boolean {
213 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
214 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
217 public getLocalAuthListEnabled(): boolean {
218 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
219 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
222 public restartWebSocketPing(): void {
223 // Stop WebSocket ping
224 this.stopWebSocketPing();
225 // Start WebSocket ping
226 this.startWebSocketPing();
229 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
230 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
231 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
232 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
235 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
236 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`);
239 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnectorStatus(connectorId
).MeterValues
;
240 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
241 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
242 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
243 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
244 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
245 return sampledValueTemplates[index];
246 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
247 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
248 return sampledValueTemplates[index];
249 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
250 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
251 return sampledValueTemplates[index];
254 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
255 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand
'${measurand}' in template on connectorId ${connectorId}
`;
256 logger.error(errorMsg);
257 throw new Error(errorMsg);
259 logger.debug(`${this.logPrefix()} No MeterValues
for measurand
'${measurand}' ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
262 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
263 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
266 public startHeartbeat(): void {
267 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
268 // eslint-disable-next-line @typescript-eslint/no-misused-promises
269 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
270 await this.ocppRequestService
.sendHeartbeat();
271 }, this.getHeartbeatInterval());
272 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
273 } else if (this.heartbeatSetInterval
) {
274 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
276 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
280 public restartHeartbeat(): void {
282 this.stopHeartbeat();
284 this.startHeartbeat();
287 public startMeterValues(connectorId
: number, interval
: number): void {
288 if (connectorId
=== 0) {
289 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
292 if (!this.getConnectorStatus(connectorId
)) {
293 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
296 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
297 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
299 } else if (this.getConnectorStatus(connectorId
)?.transactionStarted
&& !this.getConnectorStatus(connectorId
)?.transactionId
) {
300 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
304 // eslint-disable-next-line @typescript-eslint/no-misused-promises
305 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
306 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnectorStatus(connectorId
).transactionId
, interval
);
309 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
313 public start(): void {
314 if (this.getEnableStatistics()) {
315 this.performanceStatistics
.start();
317 this.openWSConnection();
318 // Monitor authorization file
319 this.startAuthorizationFileMonitoring();
320 // Monitor station template file
321 this.startStationTemplateFileMonitoring();
322 // Handle WebSocket message
323 this.wsConnection
.on('message', this.onMessage
.bind(this));
324 // Handle WebSocket error
325 this.wsConnection
.on('error', this.onError
.bind(this));
326 // Handle WebSocket close
327 this.wsConnection
.on('close', this.onClose
.bind(this));
328 // Handle WebSocket open
329 this.wsConnection
.on('open', this.onOpen
.bind(this));
330 // Handle WebSocket ping
331 this.wsConnection
.on('ping', this.onPing
.bind(this));
332 // Handle WebSocket pong
333 this.wsConnection
.on('pong', this.onPong
.bind(this));
336 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
337 // Stop message sequence
338 await this.stopMessageSequence(reason
);
339 for (const connectorId
of this.connectors
.keys()) {
340 if (connectorId
> 0) {
341 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.UNAVAILABLE
);
342 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
345 if (this.isWebSocketConnectionOpened()) {
346 this.wsConnection
.close();
348 if (this.getEnableStatistics()) {
349 this.performanceStatistics
.stop();
351 this.bootNotificationResponse
= null;
355 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
356 return this.configuration
.configurationKey
.find((configElement
) => {
357 if (caseInsensitive
) {
358 return configElement
.key
.toLowerCase() === key
.toLowerCase();
360 return configElement
.key
=== key
;
364 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
365 const keyFound
= this.getConfigurationKey(key
);
367 this.configuration
.configurationKey
.push({
375 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
379 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
380 const keyFound
= this.getConfigurationKey(key
);
382 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
383 this.configuration
.configurationKey
[keyIndex
].value
= value
;
385 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
389 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
390 let cpReplaced
= false;
391 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
392 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
393 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
394 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
395 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
400 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
403 public resetTransactionOnConnector(connectorId
: number): void {
404 this.getConnectorStatus(connectorId
).authorized
= false;
405 this.getConnectorStatus(connectorId
).transactionStarted
= false;
406 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
407 delete this.getConnectorStatus(connectorId
).transactionId
;
408 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
409 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
410 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
411 this.stopMeterValues(connectorId
);
414 public addToMessageQueue(message
: string): void {
416 // Handle dups in message queue
417 for (const bufferedMessage
of this.messageQueue
) {
418 // Message already in the queue
419 if (message
=== bufferedMessage
) {
426 this.messageQueue
.push(message
);
430 private flushMessageQueue() {
431 if (!Utils
.isEmptyArray(this.messageQueue
)) {
432 this.messageQueue
.forEach((message
, index
) => {
433 this.messageQueue
.splice(index
, 1);
434 // TODO: evaluate the need to track performance
435 this.wsConnection
.send(message
);
440 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
441 // In case of multiple instances: add instance index to charging station id
442 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
443 const idSuffix
= stationTemplate
.nameSuffix
?? '';
444 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
447 private buildStationInfo(): ChargingStationInfo
{
448 let stationTemplateFromFile
: ChargingStationTemplate
;
450 // Load template file
451 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
452 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
453 fs
.closeSync(fileDescriptor
);
455 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
457 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
458 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
459 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
460 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplateFromFile
.power
.length
);
461 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
462 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
463 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
465 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
466 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
467 ? stationTemplateFromFile
.power
* 1000
468 : stationTemplateFromFile
.power
;
470 delete stationInfo
.power
;
471 delete stationInfo
.powerUnit
;
472 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
473 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
477 private getOCPPVersion(): OCPPVersion
{
478 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
481 private handleUnsupportedVersion(version
: OCPPVersion
) {
482 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
483 logger
.error(errMsg
);
484 throw new Error(errMsg
);
487 private initialize(): void {
488 this.stationInfo
= this.buildStationInfo();
489 this.bootNotificationRequest
= {
490 chargePointModel
: this.stationInfo
.chargePointModel
,
491 chargePointVendor
: this.stationInfo
.chargePointVendor
,
492 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
493 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
495 this.configuration
= this.getTemplateChargingStationConfiguration();
496 this.wsConnectionUrl
= new URL(this.getSupervisionURL().href
+ '/' + this.stationInfo
.chargingStationId
);
497 // Build connectors if needed
498 const maxConnectors
= this.getMaxNumberOfConnectors();
499 if (maxConnectors
<= 0) {
500 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
502 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
503 if (templateMaxConnectors
<= 0) {
504 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
506 if (!this.stationInfo
.Connectors
[0]) {
507 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
510 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
511 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
512 this.stationInfo
.randomConnectors
= true;
514 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
515 const connectorsConfigChanged
= this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
516 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
517 connectorsConfigChanged
&& (this.connectors
.clear());
518 this.connectorsConfigurationHash
= connectorsConfigHash
;
519 // Add connector Id 0
520 let lastConnector
= '0';
521 for (lastConnector
in this.stationInfo
.Connectors
) {
522 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
523 if (lastConnectorId
=== 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
524 this.connectors
.set(lastConnectorId
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
]));
525 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
526 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
527 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
531 // Generate all connectors
532 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
533 for (let index
= 1; index
<= maxConnectors
; index
++) {
534 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1) : index
;
535 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
]));
536 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
537 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
538 this.getConnectorStatus(index
).chargingProfiles
= [];
543 // Avoid duplication of connectors related information
544 delete this.stationInfo
.Connectors
;
545 // Initialize transaction attributes on connectors
546 for (const connectorId
of this.connectors
.keys()) {
547 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
548 this.initTransactionAttributesOnConnector(connectorId
);
551 switch (this.getOCPPVersion()) {
552 case OCPPVersion
.VERSION_16
:
553 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
554 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
557 this.handleUnsupportedVersion(this.getOCPPVersion());
561 this.initOCPPParameters();
562 if (this.stationInfo
.autoRegister
) {
563 this.bootNotificationResponse
= {
564 currentTime
: new Date().toISOString(),
565 interval
: this.getHeartbeatInterval() / 1000,
566 status: RegistrationStatus
.ACCEPTED
569 this.stationInfo
.powerDivider
= this.getPowerDivider();
570 if (this.getEnableStatistics()) {
571 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
575 private initOCPPParameters(): void {
576 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
577 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
579 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
580 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
581 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
583 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
584 const connectorPhaseRotation
= [];
585 for (const connectorId
of this.connectors
.keys()) {
587 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
588 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
589 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
590 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
592 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
593 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
594 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
595 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
598 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
600 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
601 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
603 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
604 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
605 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
607 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
608 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
612 private async onOpen(): Promise
<void> {
613 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
614 if (!this.isRegistered()) {
615 // Send BootNotification
616 let registrationRetryCount
= 0;
618 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
619 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
620 if (!this.isRegistered()) {
621 registrationRetryCount
++;
622 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
624 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
626 if (this.isRegistered()) {
627 await this.startMessageSequence();
628 this.stopped
&& (this.stopped
= false);
629 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
630 this.flushMessageQueue();
633 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
635 this.autoReconnectRetryCount
= 0;
636 this.wsConnectionRestarted
= false;
639 private async onClose(code
: number, reason
: string): Promise
<void> {
642 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
643 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
644 logger
.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
645 this.autoReconnectRetryCount
= 0;
649 logger
.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
650 await this.reconnect(code
);
655 private async onMessage(data
: Data
): Promise
<void> {
656 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
657 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
658 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
659 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
660 let requestPayload
: Record
<string, unknown
>;
661 let cachedRequest
: CachedRequest
;
664 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
665 if (Utils
.isIterable(request
)) {
667 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
669 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
671 // Check the Type of message
672 switch (messageType
) {
674 case MessageType
.CALL_MESSAGE
:
675 if (this.getEnableStatistics()) {
676 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
679 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
682 case MessageType
.CALL_RESULT_MESSAGE
:
684 cachedRequest
= this.requests
.get(messageId
);
685 if (Utils
.isIterable(cachedRequest
)) {
686 [responseCallback
, , , requestPayload
] = cachedRequest
;
688 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} response is not iterable`, commandName
);
690 if (!responseCallback
) {
692 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response for unknown message id ${messageId}`, commandName
);
694 responseCallback(commandName
, requestPayload
);
697 case MessageType
.CALL_ERROR_MESSAGE
:
698 cachedRequest
= this.requests
.get(messageId
);
699 if (Utils
.isIterable(cachedRequest
)) {
700 [, rejectCallback
, requestCommandName
] = cachedRequest
;
702 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} error response is not iterable`);
704 if (!rejectCallback
) {
706 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error response for unknown message id ${messageId}`, requestCommandName
);
708 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
));
712 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
713 logger
.error(errMsg
);
714 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
718 logger
.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data
, this.requests
.get(messageId
), error
);
720 messageType
=== MessageType
.CALL_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
724 private onPing(): void {
725 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
728 private onPong(): void {
729 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
732 private async onError(error
: WSError
): Promise
<void> {
733 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
734 // switch (error.code) {
735 // case 'ECONNREFUSED':
736 // await this.reconnect(error);
741 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
742 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
745 private getAuthorizationFile(): string | undefined {
746 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
749 private getAuthorizedTags(): string[] {
750 let authorizedTags
: string[] = [];
751 const authorizationFile
= this.getAuthorizationFile();
752 if (authorizationFile
) {
754 // Load authorization file
755 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
756 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
757 fs
.closeSync(fileDescriptor
);
759 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
762 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
764 return authorizedTags
;
767 private getUseConnectorId0(): boolean | undefined {
768 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
771 private getNumberOfRunningTransactions(): number {
773 for (const connectorId
of this.connectors
.keys()) {
774 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
782 private getConnectionTimeout(): number | undefined {
783 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
784 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
786 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
789 // -1 for unlimited, 0 for disabling
790 private getAutoReconnectMaxRetries(): number | undefined {
791 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
792 return this.stationInfo
.autoReconnectMaxRetries
;
794 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
795 return Configuration
.getAutoReconnectMaxRetries();
801 private getRegistrationMaxRetries(): number | undefined {
802 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
803 return this.stationInfo
.registrationMaxRetries
;
808 private getPowerDivider(): number {
809 let powerDivider
= this.getNumberOfConnectors();
810 if (this.stationInfo
.powerSharedByConnectors
) {
811 powerDivider
= this.getNumberOfRunningTransactions();
816 private getTemplateMaxNumberOfConnectors(): number {
817 return Object.keys(this.stationInfo
.Connectors
).length
;
820 private getMaxNumberOfConnectors(): number {
821 let maxConnectors
= 0;
822 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
823 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
824 // Distribute evenly the number of connectors
825 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
826 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
827 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
829 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
831 return maxConnectors
;
834 private async startMessageSequence(): Promise
<void> {
835 // Start WebSocket ping
836 this.startWebSocketPing();
838 this.startHeartbeat();
839 // Initialize connectors status
840 for (const connectorId
of this.connectors
.keys()) {
841 if (connectorId
=== 0) {
843 } else if (!this.stopped
&& !this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
844 // Send status in template at startup
845 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
846 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
847 } else if (this.stopped
&& this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
848 // Send status in template after reset
849 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
850 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
851 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
852 // Send previous status at template reload
853 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).status);
855 // Send default status
856 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
857 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
861 this.startAutomaticTransactionGenerator();
864 private startAutomaticTransactionGenerator() {
865 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
866 if (!this.automaticTransactionGenerator
) {
867 this.automaticTransactionGenerator
= new AutomaticTransactionGenerator(this);
869 if (!this.automaticTransactionGenerator
.started
) {
870 this.automaticTransactionGenerator
.start();
875 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
876 // Stop WebSocket ping
877 this.stopWebSocketPing();
879 this.stopHeartbeat();
881 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
882 this.automaticTransactionGenerator
&&
883 this.automaticTransactionGenerator
.started
) {
884 this.automaticTransactionGenerator
.stop();
886 for (const connectorId
of this.connectors
.keys()) {
887 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
888 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
889 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
890 this.getTransactionIdTag(transactionId
), reason
);
896 private startWebSocketPing(): void {
897 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
898 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
900 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
901 this.webSocketPingSetInterval
= setInterval(() => {
902 if (this.isWebSocketConnectionOpened()) {
903 this.wsConnection
.ping((): void => { /* This is intentional */ });
905 }, webSocketPingInterval
* 1000);
906 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.formatDurationSeconds(webSocketPingInterval
));
907 } else if (this.webSocketPingSetInterval
) {
908 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.formatDurationSeconds(webSocketPingInterval
) + ' already started');
910 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
914 private stopWebSocketPing(): void {
915 if (this.webSocketPingSetInterval
) {
916 clearInterval(this.webSocketPingSetInterval
);
920 private getSupervisionURL(): URL
{
921 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
923 if (!Utils
.isEmptyArray(supervisionUrls
)) {
924 if (Configuration
.getDistributeStationsToTenantsEqually()) {
925 indexUrl
= this.index
% supervisionUrls
.length
;
928 indexUrl
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
930 return new URL(supervisionUrls
[indexUrl
]);
932 return new URL(supervisionUrls
as string);
935 private getHeartbeatInterval(): number | undefined {
936 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
937 if (HeartbeatInterval
) {
938 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
940 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
941 if (HeartBeatInterval
) {
942 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
944 !this.stationInfo
.autoRegister
&& logger
.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
945 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
948 private stopHeartbeat(): void {
949 if (this.heartbeatSetInterval
) {
950 clearInterval(this.heartbeatSetInterval
);
954 private openWSConnection(options
?: ClientOptions
& ClientRequestArgs
, forceCloseOpened
= false): void {
955 options
= options
?? {};
956 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
957 if (!Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) && !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)) {
958 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
960 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
961 this.wsConnection
.close();
964 switch (this.getOCPPVersion()) {
965 case OCPPVersion
.VERSION_16
:
966 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
969 this.handleUnsupportedVersion(this.getOCPPVersion());
972 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
973 logger
.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString());
976 private stopMeterValues(connectorId
: number) {
977 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
978 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
982 private startAuthorizationFileMonitoring(): void {
983 const authorizationFile
= this.getAuthorizationFile();
984 if (authorizationFile
) {
986 fs
.watch(authorizationFile
, (event
, filename
) => {
987 if (filename
&& event
=== 'change') {
989 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
990 // Initialize authorizedTags
991 this.authorizedTags
= this.getAuthorizedTags();
993 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
998 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
1001 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
1005 private startStationTemplateFileMonitoring(): void {
1007 fs
.watch(this.stationTemplateFile
, (event
, filename
): void => {
1008 if (filename
&& event
=== 'change') {
1010 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
1014 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1015 this.automaticTransactionGenerator
) {
1016 this.automaticTransactionGenerator
.stop();
1018 this.startAutomaticTransactionGenerator();
1019 if (this.getEnableStatistics()) {
1020 this.performanceStatistics
.restart();
1022 this.performanceStatistics
.stop();
1024 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1026 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
1031 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
1035 private getReconnectExponentialDelay(): boolean | undefined {
1036 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
1039 private async reconnect(code
: number): Promise
<void> {
1040 // Stop WebSocket ping
1041 this.stopWebSocketPing();
1043 this.stopHeartbeat();
1044 // Stop the ATG if needed
1045 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1046 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1047 this.automaticTransactionGenerator
&&
1048 this.automaticTransactionGenerator
.started
) {
1049 this.automaticTransactionGenerator
.stop();
1051 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1052 this.autoReconnectRetryCount
++;
1053 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
1054 const reconnectTimeout
= reconnectDelay
- 100;
1055 logger
.error(`${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`);
1056 await Utils
.sleep(reconnectDelay
);
1057 logger
.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
1058 this.openWSConnection({ handshakeTimeout
: reconnectTimeout
}, true);
1059 this.wsConnectionRestarted
= true;
1060 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1061 logger
.error(`${this.logPrefix()} WebSocket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1065 private initTransactionAttributesOnConnector(connectorId
: number): void {
1066 this.getConnectorStatus(connectorId
).authorized
= false;
1067 this.getConnectorStatus(connectorId
).transactionStarted
= false;
1068 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
1069 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;