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
, VendorDefaultParametersKey
} 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 { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
18 import { ClientRequestArgs
} from
'http';
19 import Configuration from
'../utils/Configuration';
20 import Constants from
'../utils/Constants';
21 import { ErrorType
} from
'../types/ocpp/ErrorType';
22 import FileUtils from
'../utils/FileUtils';
23 import { MessageType
} from
'../types/ocpp/MessageType';
24 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
25 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
26 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
27 import OCPPError from
'./ocpp/OCPPError';
28 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
29 import OCPPRequestService from
'./ocpp/OCPPRequestService';
30 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
31 import PerformanceStatistics from
'../performance/PerformanceStatistics';
32 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
33 import { URL
} from
'url';
34 import Utils from
'../utils/Utils';
35 import crypto from
'crypto';
37 import logger from
'../utils/Logger';
38 import { parentPort
} from
'worker_threads';
39 import path from
'path';
41 export default class ChargingStation
{
42 public readonly stationTemplateFile
: string;
43 public authorizedTags
: string[];
44 public stationInfo
!: ChargingStationInfo
;
45 public readonly connectors
: Map
<number, ConnectorStatus
>;
46 public configuration
!: ChargingStationConfiguration
;
47 public wsConnection
!: WebSocket
;
48 public readonly requests
: Map
<string, CachedRequest
>;
49 public performanceStatistics
!: PerformanceStatistics
;
50 public heartbeatSetInterval
!: NodeJS
.Timeout
;
51 public ocppRequestService
!: OCPPRequestService
;
52 private readonly index
: number;
53 private bootNotificationRequest
!: BootNotificationRequest
;
54 private bootNotificationResponse
!: BootNotificationResponse
| null;
55 private connectorsConfigurationHash
!: string;
56 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
57 private readonly messageBuffer
: Set
<string>;
58 private wsConfiguredConnectionUrl
!: URL
;
59 private wsConnectionRestarted
: boolean;
60 private stopped
: boolean;
61 private autoReconnectRetryCount
: number;
62 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
63 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
65 constructor(index
: number, stationTemplateFile
: string) {
67 this.stationTemplateFile
= stationTemplateFile
;
68 this.connectors
= new Map
<number, ConnectorStatus
>();
72 this.wsConnectionRestarted
= false;
73 this.autoReconnectRetryCount
= 0;
75 this.requests
= new Map
<string, CachedRequest
>();
76 this.messageBuffer
= new Set
<string>();
78 this.authorizedTags
= this.getAuthorizedTags();
81 get
wsConnectionUrl(): URL
{
82 return this.getSupervisionURLOCPPConfiguration() ? new URL(this.getConfigurationKey(this.stationInfo
.supervisionURLOCPPKey
?? VendorDefaultParametersKey
.ConnectionUrl
).value
+ '/' + this.stationInfo
.chargingStationId
) : this.wsConfiguredConnectionUrl
;
85 public logPrefix(): string {
86 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
89 public getBootNotificationRequest(): BootNotificationRequest
{
90 return this.bootNotificationRequest
;
93 public getRandomIdTag(): string {
94 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
95 return this.authorizedTags
[index
];
98 public hasAuthorizedTags(): boolean {
99 return !Utils
.isEmptyArray(this.authorizedTags
);
102 public getEnableStatistics(): boolean | undefined {
103 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
106 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
107 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
110 public getNumberOfPhases(): number | undefined {
111 switch (this.getCurrentOutType()) {
113 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
119 public isWebSocketConnectionOpened(): boolean {
120 return this.wsConnection
?.readyState
=== OPEN
;
123 public isRegistered(): boolean {
124 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
127 public isChargingStationAvailable(): boolean {
128 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
131 public isConnectorAvailable(id
: number): boolean {
132 return this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
135 public getNumberOfConnectors(): number {
136 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
139 public getConnectorStatus(id
: number): ConnectorStatus
{
140 return this.connectors
.get(id
);
143 public getCurrentOutType(): CurrentType
| undefined {
144 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
147 public getVoltageOut(): number | undefined {
148 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
149 let defaultVoltageOut
: number;
150 switch (this.getCurrentOutType()) {
152 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
155 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
158 logger
.error(errMsg
);
159 throw new Error(errMsg
);
161 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
164 public getTransactionIdTag(transactionId
: number): string | undefined {
165 for (const connectorId
of this.connectors
.keys()) {
166 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
167 return this.getConnectorStatus(connectorId
).transactionIdTag
;
172 public getOutOfOrderEndMeterValues(): boolean {
173 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
176 public getBeginEndMeterValues(): boolean {
177 return this.stationInfo
.beginEndMeterValues
?? false;
180 public getMeteringPerTransaction(): boolean {
181 return this.stationInfo
.meteringPerTransaction
?? true;
184 public getTransactionDataMeterValues(): boolean {
185 return this.stationInfo
.transactionDataMeterValues
?? false;
188 public getMainVoltageMeterValues(): boolean {
189 return this.stationInfo
.mainVoltageMeterValues
?? true;
192 public getPhaseLineToLineVoltageMeterValues(): boolean {
193 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
196 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
197 if (this.getMeteringPerTransaction()) {
198 for (const connectorId
of this.connectors
.keys()) {
199 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
200 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
204 for (const connectorId
of this.connectors
.keys()) {
205 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
206 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
211 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
212 if (this.getMeteringPerTransaction()) {
213 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
215 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
218 public getAuthorizeRemoteTxRequests(): boolean {
219 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
220 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
223 public getLocalAuthListEnabled(): boolean {
224 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
225 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
228 public restartWebSocketPing(): void {
229 // Stop WebSocket ping
230 this.stopWebSocketPing();
231 // Start WebSocket ping
232 this.startWebSocketPing();
235 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
236 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
237 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
238 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
241 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
242 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`);
245 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnectorStatus(connectorId
).MeterValues
;
246 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
247 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
248 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
249 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
250 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
251 return sampledValueTemplates[index];
252 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
253 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
254 return sampledValueTemplates[index];
255 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
256 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
257 return sampledValueTemplates[index];
260 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
261 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand
'${measurand}' in template on connectorId ${connectorId}
`;
262 logger.error(errorMsg);
263 throw new Error(errorMsg);
265 logger.debug(`${this.logPrefix()} No MeterValues
for measurand
'${measurand}' ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
268 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
269 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
272 public startHeartbeat(): void {
273 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
274 // eslint-disable-next-line @typescript-eslint/no-misused-promises
275 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
276 await this.ocppRequestService
.sendHeartbeat();
277 }, this.getHeartbeatInterval());
278 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
279 } else if (this.heartbeatSetInterval
) {
280 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
282 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
286 public restartHeartbeat(): void {
288 this.stopHeartbeat();
290 this.startHeartbeat();
293 public startMeterValues(connectorId
: number, interval
: number): void {
294 if (connectorId
=== 0) {
295 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
298 if (!this.getConnectorStatus(connectorId
)) {
299 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
302 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
303 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
305 } else if (this.getConnectorStatus(connectorId
)?.transactionStarted
&& !this.getConnectorStatus(connectorId
)?.transactionId
) {
306 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
310 // eslint-disable-next-line @typescript-eslint/no-misused-promises
311 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
312 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnectorStatus(connectorId
).transactionId
, interval
);
315 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
319 public start(): void {
320 if (this.getEnableStatistics()) {
321 this.performanceStatistics
.start();
323 this.openWSConnection();
324 // Monitor authorization file
325 this.startAuthorizationFileMonitoring();
326 // Monitor station template file
327 this.startStationTemplateFileMonitoring();
328 // Handle WebSocket message
329 this.wsConnection
.on('message', this.onMessage
.bind(this));
330 // Handle WebSocket error
331 this.wsConnection
.on('error', this.onError
.bind(this));
332 // Handle WebSocket close
333 this.wsConnection
.on('close', this.onClose
.bind(this));
334 // Handle WebSocket open
335 this.wsConnection
.on('open', this.onOpen
.bind(this));
336 // Handle WebSocket ping
337 this.wsConnection
.on('ping', this.onPing
.bind(this));
338 // Handle WebSocket pong
339 this.wsConnection
.on('pong', this.onPong
.bind(this));
340 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STARTED
, data
: { id
: this.stationInfo
.chargingStationId
} });
343 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
344 // Stop message sequence
345 await this.stopMessageSequence(reason
);
346 for (const connectorId
of this.connectors
.keys()) {
347 if (connectorId
> 0) {
348 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.UNAVAILABLE
);
349 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
352 if (this.isWebSocketConnectionOpened()) {
353 this.wsConnection
.close();
355 if (this.getEnableStatistics()) {
356 this.performanceStatistics
.stop();
358 this.bootNotificationResponse
= null;
359 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STOPPED
, data
: { id
: this.stationInfo
.chargingStationId
} });
363 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
364 return this.configuration
.configurationKey
.find((configElement
) => {
365 if (caseInsensitive
) {
366 return configElement
.key
.toLowerCase() === key
.toLowerCase();
368 return configElement
.key
=== key
;
372 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, options
: { readonly?: boolean, visible
?: boolean, reboot
?: boolean } = { readonly: false, visible
: true, reboot
: false }): void {
373 const keyFound
= this.getConfigurationKey(key
);
374 const readonly = options
.readonly;
375 const visible
= options
.visible
;
376 const reboot
= options
.reboot
;
378 this.configuration
.configurationKey
.push({
386 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
390 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
391 const keyFound
= this.getConfigurationKey(key
);
393 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
394 this.configuration
.configurationKey
[keyIndex
].value
= value
;
396 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
400 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
401 let cpReplaced
= false;
402 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
403 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
404 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
405 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
406 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
411 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
414 public resetConnectorStatus(connectorId
: number): void {
415 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
416 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
417 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
418 this.getConnectorStatus(connectorId
).transactionStarted
= false;
419 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
420 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
421 delete this.getConnectorStatus(connectorId
).transactionId
;
422 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
423 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
424 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
425 this.stopMeterValues(connectorId
);
428 public bufferMessage(message
: string): void {
429 this.messageBuffer
.add(message
);
432 private flushMessageBuffer() {
433 if (this.messageBuffer
.size
> 0) {
434 this.messageBuffer
.forEach((message
) => {
435 // TODO: evaluate the need to track performance
436 this.wsConnection
.send(message
);
437 this.messageBuffer
.delete(message
);
442 private getSupervisionURLOCPPConfiguration(): boolean {
443 return this.stationInfo
.supervisionURLOCPPConfiguration
?? false;
446 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
447 // In case of multiple instances: add instance index to charging station id
448 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
449 const idSuffix
= stationTemplate
.nameSuffix
?? '';
450 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
453 private buildStationInfo(): ChargingStationInfo
{
454 let stationTemplateFromFile
: ChargingStationTemplate
;
456 // Load template file
457 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
458 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
459 fs
.closeSync(fileDescriptor
);
461 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
as NodeJS
.ErrnoException
);
463 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
464 stationInfo
.wsOptions
= stationTemplateFromFile
?.wsOptions
?? {};
465 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
466 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
467 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplateFromFile
.power
.length
);
468 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
469 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
470 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
472 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
473 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
474 ? stationTemplateFromFile
.power
* 1000
475 : stationTemplateFromFile
.power
;
477 delete stationInfo
.power
;
478 delete stationInfo
.powerUnit
;
479 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
480 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
484 private getOCPPVersion(): OCPPVersion
{
485 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
488 private handleUnsupportedVersion(version
: OCPPVersion
) {
489 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
490 logger
.error(errMsg
);
491 throw new Error(errMsg
);
494 private initialize(): void {
495 this.stationInfo
= this.buildStationInfo();
496 this.configuration
= this.getTemplateChargingStationConfiguration();
497 delete this.stationInfo
.Configuration
;
498 this.bootNotificationRequest
= {
499 chargePointModel
: this.stationInfo
.chargePointModel
,
500 chargePointVendor
: this.stationInfo
.chargePointVendor
,
501 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
502 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
504 // Build connectors if needed
505 const maxConnectors
= this.getMaxNumberOfConnectors();
506 if (maxConnectors
<= 0) {
507 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
509 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
510 if (templateMaxConnectors
<= 0) {
511 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
513 if (!this.stationInfo
.Connectors
[0]) {
514 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
517 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
518 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
519 this.stationInfo
.randomConnectors
= true;
521 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
522 const connectorsConfigChanged
= this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
523 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
524 connectorsConfigChanged
&& (this.connectors
.clear());
525 this.connectorsConfigurationHash
= connectorsConfigHash
;
526 // Add connector Id 0
527 let lastConnector
= '0';
528 for (lastConnector
in this.stationInfo
.Connectors
) {
529 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
530 if (lastConnectorId
=== 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
531 this.connectors
.set(lastConnectorId
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
]));
532 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
533 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
534 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
538 // Generate all connectors
539 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
540 for (let index
= 1; index
<= maxConnectors
; index
++) {
541 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1) : index
;
542 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
]));
543 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
544 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
545 this.getConnectorStatus(index
).chargingProfiles
= [];
550 // Avoid duplication of connectors related information
551 delete this.stationInfo
.Connectors
;
552 // Initialize transaction attributes on connectors
553 for (const connectorId
of this.connectors
.keys()) {
554 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
555 this.initializeConnectorStatus(connectorId
);
558 this.wsConfiguredConnectionUrl
= new URL(this.getConfiguredSupervisionURL().href
+ '/' + this.stationInfo
.chargingStationId
);
559 switch (this.getOCPPVersion()) {
560 case OCPPVersion
.VERSION_16
:
561 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
562 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
565 this.handleUnsupportedVersion(this.getOCPPVersion());
569 this.initOCPPParameters();
570 if (this.stationInfo
.autoRegister
) {
571 this.bootNotificationResponse
= {
572 currentTime
: new Date().toISOString(),
573 interval
: this.getHeartbeatInterval() / 1000,
574 status: RegistrationStatus
.ACCEPTED
577 this.stationInfo
.powerDivider
= this.getPowerDivider();
578 if (this.getEnableStatistics()) {
579 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
583 private initOCPPParameters(): void {
584 if (this.getSupervisionURLOCPPConfiguration() && !this.getConfigurationKey(this.stationInfo
.supervisionURLOCPPKey
?? VendorDefaultParametersKey
.ConnectionUrl
)) {
585 this.addConfigurationKey(VendorDefaultParametersKey
.ConnectionUrl
, this.getConfiguredSupervisionURL().href
, { reboot
: true });
587 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
588 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
590 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), { readonly: true });
591 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
592 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
594 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
595 const connectorPhaseRotation
= [];
596 for (const connectorId
of this.connectors
.keys()) {
598 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
599 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
600 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
601 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
603 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
604 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
605 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
606 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
609 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
611 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
612 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
614 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
615 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
616 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
618 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
619 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
623 private async onOpen(): Promise
<void> {
624 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
625 if (!this.isRegistered()) {
626 // Send BootNotification
627 let registrationRetryCount
= 0;
629 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
630 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
631 if (!this.isRegistered()) {
632 registrationRetryCount
++;
633 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
635 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
637 if (this.isRegistered()) {
638 await this.startMessageSequence();
639 this.stopped
&& (this.stopped
= false);
640 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
641 this.flushMessageBuffer();
644 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
646 this.autoReconnectRetryCount
= 0;
647 this.wsConnectionRestarted
= false;
650 private async onClose(code
: number, reason
: string): Promise
<void> {
653 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
654 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
655 logger
.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
656 this.autoReconnectRetryCount
= 0;
660 logger
.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
661 await this.reconnect(code
);
666 private async onMessage(data
: Data
): Promise
<void> {
667 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
668 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
669 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
670 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
671 let requestPayload
: Record
<string, unknown
>;
672 let cachedRequest
: CachedRequest
;
675 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
676 if (Utils
.isIterable(request
)) {
678 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
680 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
682 // Check the Type of message
683 switch (messageType
) {
685 case MessageType
.CALL_MESSAGE
:
686 if (this.getEnableStatistics()) {
687 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
690 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
693 case MessageType
.CALL_RESULT_MESSAGE
:
695 cachedRequest
= this.requests
.get(messageId
);
696 if (Utils
.isIterable(cachedRequest
)) {
697 [responseCallback
, , , requestPayload
] = cachedRequest
;
699 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} response is not iterable`, commandName
);
701 if (!responseCallback
) {
703 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response for unknown message id ${messageId}`, commandName
);
705 responseCallback(commandName
, requestPayload
);
708 case MessageType
.CALL_ERROR_MESSAGE
:
709 cachedRequest
= this.requests
.get(messageId
);
710 if (Utils
.isIterable(cachedRequest
)) {
711 [, rejectCallback
, requestCommandName
] = cachedRequest
;
713 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} error response is not iterable`);
715 if (!rejectCallback
) {
717 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error response for unknown message id ${messageId}`, requestCommandName
);
719 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
));
723 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
724 logger
.error(errMsg
);
725 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
729 logger
.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data
.toString(), this.requests
.get(messageId
), error
);
731 messageType
=== MessageType
.CALL_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
);
735 private onPing(): void {
736 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
739 private onPong(): void {
740 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
743 private async onError(error
: WSError
): Promise
<void> {
744 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
745 // switch (error.code) {
746 // case 'ECONNREFUSED':
747 // await this.reconnect(error);
752 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
753 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
756 private getAuthorizationFile(): string | undefined {
757 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
760 private getAuthorizedTags(): string[] {
761 let authorizedTags
: string[] = [];
762 const authorizationFile
= this.getAuthorizationFile();
763 if (authorizationFile
) {
765 // Load authorization file
766 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
767 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
768 fs
.closeSync(fileDescriptor
);
770 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
as NodeJS
.ErrnoException
);
773 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
775 return authorizedTags
;
778 private getUseConnectorId0(): boolean | undefined {
779 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
782 private getNumberOfRunningTransactions(): number {
784 for (const connectorId
of this.connectors
.keys()) {
785 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
793 private getConnectionTimeout(): number | undefined {
794 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
795 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
797 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
800 // -1 for unlimited, 0 for disabling
801 private getAutoReconnectMaxRetries(): number | undefined {
802 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
803 return this.stationInfo
.autoReconnectMaxRetries
;
805 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
806 return Configuration
.getAutoReconnectMaxRetries();
812 private getRegistrationMaxRetries(): number | undefined {
813 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
814 return this.stationInfo
.registrationMaxRetries
;
819 private getPowerDivider(): number {
820 let powerDivider
= this.getNumberOfConnectors();
821 if (this.stationInfo
.powerSharedByConnectors
) {
822 powerDivider
= this.getNumberOfRunningTransactions();
827 private getTemplateMaxNumberOfConnectors(): number {
828 return Object.keys(this.stationInfo
.Connectors
).length
;
831 private getMaxNumberOfConnectors(): number {
832 let maxConnectors
= 0;
833 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
834 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
835 // Distribute evenly the number of connectors
836 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
837 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
838 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
840 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
842 return maxConnectors
;
845 private async startMessageSequence(): Promise
<void> {
846 // Start WebSocket ping
847 this.startWebSocketPing();
849 this.startHeartbeat();
850 // Initialize connectors status
851 for (const connectorId
of this.connectors
.keys()) {
852 if (connectorId
=== 0) {
854 } else if (!this.stopped
&& !this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
855 // Send status in template at startup
856 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
857 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
858 } else if (this.stopped
&& this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
859 // Send status in template after reset
860 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
861 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
862 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
863 // Send previous status at template reload
864 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).status);
866 // Send default status
867 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
868 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
872 this.startAutomaticTransactionGenerator();
875 private startAutomaticTransactionGenerator() {
876 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
877 if (!this.automaticTransactionGenerator
) {
878 this.automaticTransactionGenerator
= new AutomaticTransactionGenerator(this);
880 if (!this.automaticTransactionGenerator
.started
) {
881 this.automaticTransactionGenerator
.start();
886 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
887 // Stop WebSocket ping
888 this.stopWebSocketPing();
890 this.stopHeartbeat();
892 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
893 this.automaticTransactionGenerator
&&
894 this.automaticTransactionGenerator
.started
) {
895 this.automaticTransactionGenerator
.stop();
897 for (const connectorId
of this.connectors
.keys()) {
898 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
899 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
900 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
901 this.getTransactionIdTag(transactionId
), reason
);
907 private startWebSocketPing(): void {
908 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
909 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
911 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
912 this.webSocketPingSetInterval
= setInterval(() => {
913 if (this.isWebSocketConnectionOpened()) {
914 this.wsConnection
.ping((): void => { /* This is intentional */ });
916 }, webSocketPingInterval
* 1000);
917 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.formatDurationSeconds(webSocketPingInterval
));
918 } else if (this.webSocketPingSetInterval
) {
919 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.formatDurationSeconds(webSocketPingInterval
) + ' already started');
921 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
925 private stopWebSocketPing(): void {
926 if (this.webSocketPingSetInterval
) {
927 clearInterval(this.webSocketPingSetInterval
);
931 private getConfiguredSupervisionURL(): URL
{
932 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
?? Configuration
.getSupervisionURLs());
934 if (!Utils
.isEmptyArray(supervisionUrls
)) {
935 if (Configuration
.getDistributeStationsToTenantsEqually()) {
936 indexUrl
= this.index
% supervisionUrls
.length
;
939 indexUrl
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
941 return new URL(supervisionUrls
[indexUrl
]);
943 return new URL(supervisionUrls
as string);
946 private getHeartbeatInterval(): number | undefined {
947 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
948 if (HeartbeatInterval
) {
949 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
951 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
952 if (HeartBeatInterval
) {
953 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
955 !this.stationInfo
.autoRegister
&& logger
.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
956 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
959 private stopHeartbeat(): void {
960 if (this.heartbeatSetInterval
) {
961 clearInterval(this.heartbeatSetInterval
);
965 private openWSConnection(options
: ClientOptions
& ClientRequestArgs
= this.stationInfo
.wsOptions
, forceCloseOpened
= false): void {
966 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
967 if (!Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) && !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)) {
968 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
970 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
971 this.wsConnection
.close();
973 let protocol
: string;
974 switch (this.getOCPPVersion()) {
975 case OCPPVersion
.VERSION_16
:
976 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
979 this.handleUnsupportedVersion(this.getOCPPVersion());
982 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
983 logger
.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString());
986 private stopMeterValues(connectorId
: number) {
987 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
988 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
992 private startAuthorizationFileMonitoring(): void {
993 const authorizationFile
= this.getAuthorizationFile();
994 if (authorizationFile
) {
996 fs
.watch(authorizationFile
, (event
, filename
) => {
997 if (filename
&& event
=== 'change') {
999 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
1000 // Initialize authorizedTags
1001 this.authorizedTags
= this.getAuthorizedTags();
1003 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
1008 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
as NodeJS
.ErrnoException
);
1011 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
1015 private startStationTemplateFileMonitoring(): void {
1017 fs
.watch(this.stationTemplateFile
, (event
, filename
): void => {
1018 if (filename
&& event
=== 'change') {
1020 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
1024 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1025 this.automaticTransactionGenerator
) {
1026 this.automaticTransactionGenerator
.stop();
1028 this.startAutomaticTransactionGenerator();
1029 if (this.getEnableStatistics()) {
1030 this.performanceStatistics
.restart();
1032 this.performanceStatistics
.stop();
1034 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1036 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
1041 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
as NodeJS
.ErrnoException
);
1045 private getReconnectExponentialDelay(): boolean | undefined {
1046 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
1049 private async reconnect(code
: number): Promise
<void> {
1050 // Stop WebSocket ping
1051 this.stopWebSocketPing();
1053 this.stopHeartbeat();
1054 // Stop the ATG if needed
1055 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1056 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1057 this.automaticTransactionGenerator
&&
1058 this.automaticTransactionGenerator
.started
) {
1059 this.automaticTransactionGenerator
.stop();
1061 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1062 this.autoReconnectRetryCount
++;
1063 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
1064 const reconnectTimeout
= (reconnectDelay
- 100) > 0 && reconnectDelay
;
1065 logger
.error(`${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`);
1066 await Utils
.sleep(reconnectDelay
);
1067 logger
.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
1068 this.openWSConnection({ ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
}, true);
1069 this.wsConnectionRestarted
= true;
1070 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1071 logger
.error(`${this.logPrefix()} WebSocket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1075 private initializeConnectorStatus(connectorId
: number): void {
1076 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
1077 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
1078 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
1079 this.getConnectorStatus(connectorId
).transactionStarted
= false;
1080 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
1081 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;