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 { MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
9 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
10 import WebSocket
, { ClientOptions
, Data
, OPEN
} from
'ws';
12 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
13 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
14 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
15 import ChargingStationInfo from
'../types/ChargingStationInfo';
16 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
17 import { ClientRequestArgs
} from
'http';
18 import Configuration from
'../utils/Configuration';
19 import { ConnectorStatus
} from
'../types/ConnectorStatus';
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
'../exception/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 { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
33 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
34 import { URL
} from
'url';
35 import Utils from
'../utils/Utils';
36 import crypto from
'crypto';
38 import logger from
'../utils/Logger';
39 import { parentPort
} from
'worker_threads';
40 import path from
'path';
42 export default class ChargingStation
{
43 public readonly stationTemplateFile
: string;
44 public authorizedTags
: string[];
45 public stationInfo
!: ChargingStationInfo
;
46 public readonly connectors
: Map
<number, ConnectorStatus
>;
47 public configuration
!: ChargingStationConfiguration
;
48 public wsConnection
!: WebSocket
;
49 public readonly requests
: Map
<string, CachedRequest
>;
50 public performanceStatistics
!: PerformanceStatistics
;
51 public heartbeatSetInterval
!: NodeJS
.Timeout
;
52 public ocppRequestService
!: OCPPRequestService
;
53 private readonly index
: number;
54 private bootNotificationRequest
!: BootNotificationRequest
;
55 private bootNotificationResponse
!: BootNotificationResponse
| null;
56 private connectorsConfigurationHash
!: string;
57 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
58 private readonly messageBuffer
: Set
<string>;
59 private wsConfiguredConnectionUrl
!: URL
;
60 private wsConnectionRestarted
: boolean;
61 private stopped
: boolean;
62 private autoReconnectRetryCount
: number;
63 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
64 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
66 constructor(index
: number, stationTemplateFile
: string) {
68 this.stationTemplateFile
= stationTemplateFile
;
69 this.connectors
= new Map
<number, ConnectorStatus
>();
73 this.wsConnectionRestarted
= false;
74 this.autoReconnectRetryCount
= 0;
76 this.requests
= new Map
<string, CachedRequest
>();
77 this.messageBuffer
= new Set
<string>();
79 this.authorizedTags
= this.getAuthorizedTags();
82 get
wsConnectionUrl(): URL
{
83 return this.getSupervisionUrlOcppConfiguration() ? new URL(this.getConfigurationKey(this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
).value
+ '/' + this.stationInfo
.chargingStationId
) : this.wsConfiguredConnectionUrl
;
86 public logPrefix(): string {
87 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
90 public getBootNotificationRequest(): BootNotificationRequest
{
91 return this.bootNotificationRequest
;
94 public getRandomIdTag(): string {
95 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
96 return this.authorizedTags
[index
];
99 public hasAuthorizedTags(): boolean {
100 return !Utils
.isEmptyArray(this.authorizedTags
);
103 public getEnableStatistics(): boolean | undefined {
104 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
107 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
108 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
111 public getNumberOfPhases(): number | undefined {
112 switch (this.getCurrentOutType()) {
114 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
120 public isWebSocketConnectionOpened(): boolean {
121 return this?.wsConnection
?.readyState
=== OPEN
;
124 public isRegistered(): boolean {
125 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
128 public isChargingStationAvailable(): boolean {
129 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
132 public isConnectorAvailable(id
: number): boolean {
133 return this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
136 public getNumberOfConnectors(): number {
137 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
140 public getConnectorStatus(id
: number): ConnectorStatus
{
141 return this.connectors
.get(id
);
144 public getCurrentOutType(): CurrentType
| undefined {
145 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
148 public getVoltageOut(): number | undefined {
149 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
150 let defaultVoltageOut
: number;
151 switch (this.getCurrentOutType()) {
153 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
156 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
159 logger
.error(errMsg
);
160 throw new Error(errMsg
);
162 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
165 public getTransactionIdTag(transactionId
: number): string | undefined {
166 for (const connectorId
of this.connectors
.keys()) {
167 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
168 return this.getConnectorStatus(connectorId
).transactionIdTag
;
173 public getOutOfOrderEndMeterValues(): boolean {
174 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
177 public getBeginEndMeterValues(): boolean {
178 return this.stationInfo
.beginEndMeterValues
?? false;
181 public getMeteringPerTransaction(): boolean {
182 return this.stationInfo
.meteringPerTransaction
?? true;
185 public getTransactionDataMeterValues(): boolean {
186 return this.stationInfo
.transactionDataMeterValues
?? false;
189 public getMainVoltageMeterValues(): boolean {
190 return this.stationInfo
.mainVoltageMeterValues
?? true;
193 public getPhaseLineToLineVoltageMeterValues(): boolean {
194 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
197 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
198 if (this.getMeteringPerTransaction()) {
199 for (const connectorId
of this.connectors
.keys()) {
200 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
201 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
205 for (const connectorId
of this.connectors
.keys()) {
206 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
207 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
212 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
213 if (this.getMeteringPerTransaction()) {
214 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
216 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
219 public getAuthorizeRemoteTxRequests(): boolean {
220 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
221 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
224 public getLocalAuthListEnabled(): boolean {
225 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
226 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
229 public restartWebSocketPing(): void {
230 // Stop WebSocket ping
231 this.stopWebSocketPing();
232 // Start WebSocket ping
233 this.startWebSocketPing();
236 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
237 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
238 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
239 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
242 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
243 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`);
246 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnectorStatus(connectorId
).MeterValues
;
247 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
248 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
249 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
250 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
251 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
252 return sampledValueTemplates[index];
253 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
254 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
255 return sampledValueTemplates[index];
256 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
257 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
258 return sampledValueTemplates[index];
261 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
262 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand
'${measurand}' in template on connectorId ${connectorId}
`;
263 logger.error(errorMsg);
264 throw new Error(errorMsg);
266 logger.debug(`${this.logPrefix()} No MeterValues
for measurand
'${measurand}' ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
269 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
270 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
273 public startHeartbeat(): void {
274 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
275 // eslint-disable-next-line @typescript-eslint/no-misused-promises
276 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
277 await this.ocppRequestService
.sendHeartbeat();
278 }, this.getHeartbeatInterval());
279 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
280 } else if (this.heartbeatSetInterval
) {
281 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
283 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
287 public restartHeartbeat(): void {
289 this.stopHeartbeat();
291 this.startHeartbeat();
294 public startMeterValues(connectorId
: number, interval
: number): void {
295 if (connectorId
=== 0) {
296 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
299 if (!this.getConnectorStatus(connectorId
)) {
300 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
303 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
304 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
306 } else if (this.getConnectorStatus(connectorId
)?.transactionStarted
&& !this.getConnectorStatus(connectorId
)?.transactionId
) {
307 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
311 // eslint-disable-next-line @typescript-eslint/no-misused-promises
312 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
313 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnectorStatus(connectorId
).transactionId
, interval
);
316 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
320 public start(): void {
321 if (this.getEnableStatistics()) {
322 this.performanceStatistics
.start();
324 this.openWSConnection();
325 // Monitor authorization file
326 this.startAuthorizationFileMonitoring();
327 // Monitor station template file
328 this.startStationTemplateFileMonitoring();
329 // Handle WebSocket message
330 this.wsConnection
.on('message', this.onMessage
.bind(this));
331 // Handle WebSocket error
332 this.wsConnection
.on('error', this.onError
.bind(this));
333 // Handle WebSocket close
334 this.wsConnection
.on('close', this.onClose
.bind(this));
335 // Handle WebSocket open
336 this.wsConnection
.on('open', this.onOpen
.bind(this));
337 // Handle WebSocket ping
338 this.wsConnection
.on('ping', this.onPing
.bind(this));
339 // Handle WebSocket pong
340 this.wsConnection
.on('pong', this.onPong
.bind(this));
341 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STARTED
, data
: { id
: this.stationInfo
.chargingStationId
} });
344 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
345 // Stop message sequence
346 await this.stopMessageSequence(reason
);
347 for (const connectorId
of this.connectors
.keys()) {
348 if (connectorId
> 0) {
349 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.UNAVAILABLE
);
350 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
353 if (this.isWebSocketConnectionOpened()) {
354 this.wsConnection
.close();
356 if (this.getEnableStatistics()) {
357 this.performanceStatistics
.stop();
359 this.bootNotificationResponse
= null;
360 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STOPPED
, data
: { id
: this.stationInfo
.chargingStationId
} });
364 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
365 return this.configuration
.configurationKey
.find((configElement
) => {
366 if (caseInsensitive
) {
367 return configElement
.key
.toLowerCase() === key
.toLowerCase();
369 return configElement
.key
=== key
;
373 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, options
: { readonly?: boolean, visible
?: boolean, reboot
?: boolean } = { readonly: false, visible
: true, reboot
: false }): void {
374 const keyFound
= this.getConfigurationKey(key
);
375 const readonly = options
.readonly;
376 const visible
= options
.visible
;
377 const reboot
= options
.reboot
;
379 this.configuration
.configurationKey
.push({
387 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
391 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
392 const keyFound
= this.getConfigurationKey(key
);
394 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
395 this.configuration
.configurationKey
[keyIndex
].value
= value
;
397 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
401 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
402 let cpReplaced
= false;
403 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
404 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
405 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
406 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
407 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
412 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
415 public resetConnectorStatus(connectorId
: number): void {
416 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
417 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
418 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
419 this.getConnectorStatus(connectorId
).transactionStarted
= false;
420 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
421 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
422 delete this.getConnectorStatus(connectorId
).transactionId
;
423 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
424 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
425 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
426 this.stopMeterValues(connectorId
);
429 public bufferMessage(message
: string): void {
430 this.messageBuffer
.add(message
);
433 private flushMessageBuffer() {
434 if (this.messageBuffer
.size
> 0) {
435 this.messageBuffer
.forEach((message
) => {
436 // TODO: evaluate the need to track performance
437 this.wsConnection
.send(message
);
438 this.messageBuffer
.delete(message
);
443 private getSupervisionUrlOcppConfiguration(): boolean {
444 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
447 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
448 // In case of multiple instances: add instance index to charging station id
449 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
450 const idSuffix
= stationTemplate
.nameSuffix
?? '';
451 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
454 private buildStationInfo(): ChargingStationInfo
{
455 let stationTemplateFromFile
: ChargingStationTemplate
;
457 // Load template file
458 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
459 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
460 fs
.closeSync(fileDescriptor
);
462 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
as NodeJS
.ErrnoException
);
464 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
465 stationInfo
.wsOptions
= stationTemplateFromFile
?.wsOptions
?? {};
466 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
467 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
468 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplateFromFile
.power
.length
);
469 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
470 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
471 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
473 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
474 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
475 ? stationTemplateFromFile
.power
* 1000
476 : stationTemplateFromFile
.power
;
478 delete stationInfo
.power
;
479 delete stationInfo
.powerUnit
;
480 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
481 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
485 private getOcppVersion(): OCPPVersion
{
486 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
489 private handleUnsupportedVersion(version
: OCPPVersion
) {
490 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
491 logger
.error(errMsg
);
492 throw new Error(errMsg
);
495 private initialize(): void {
496 this.stationInfo
= this.buildStationInfo();
497 this.configuration
= this.getTemplateChargingStationConfiguration();
498 delete this.stationInfo
.Configuration
;
499 this.bootNotificationRequest
= {
500 chargePointModel
: this.stationInfo
.chargePointModel
,
501 chargePointVendor
: this.stationInfo
.chargePointVendor
,
502 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
503 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
505 // Build connectors if needed
506 const maxConnectors
= this.getMaxNumberOfConnectors();
507 if (maxConnectors
<= 0) {
508 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
510 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
511 if (templateMaxConnectors
<= 0) {
512 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
514 if (!this.stationInfo
.Connectors
[0]) {
515 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
518 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
519 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
520 this.stationInfo
.randomConnectors
= true;
522 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
523 const connectorsConfigChanged
= this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
524 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
525 connectorsConfigChanged
&& (this.connectors
.clear());
526 this.connectorsConfigurationHash
= connectorsConfigHash
;
527 // Add connector Id 0
528 let lastConnector
= '0';
529 for (lastConnector
in this.stationInfo
.Connectors
) {
530 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
531 if (lastConnectorId
=== 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
532 this.connectors
.set(lastConnectorId
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
]));
533 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
534 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
535 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
539 // Generate all connectors
540 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
541 for (let index
= 1; index
<= maxConnectors
; index
++) {
542 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1) : index
;
543 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
]));
544 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
545 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
546 this.getConnectorStatus(index
).chargingProfiles
= [];
551 // Avoid duplication of connectors related information
552 delete this.stationInfo
.Connectors
;
553 // Initialize transaction attributes on connectors
554 for (const connectorId
of this.connectors
.keys()) {
555 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
556 this.initializeConnectorStatus(connectorId
);
559 this.wsConfiguredConnectionUrl
= new URL(this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
);
560 switch (this.getOcppVersion()) {
561 case OCPPVersion
.VERSION_16
:
562 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
563 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
566 this.handleUnsupportedVersion(this.getOcppVersion());
570 this.initOcppParameters();
571 if (this.stationInfo
.autoRegister
) {
572 this.bootNotificationResponse
= {
573 currentTime
: new Date().toISOString(),
574 interval
: this.getHeartbeatInterval() / 1000,
575 status: RegistrationStatus
.ACCEPTED
578 this.stationInfo
.powerDivider
= this.getPowerDivider();
579 if (this.getEnableStatistics()) {
580 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
584 private initOcppParameters(): void {
585 if (this.getSupervisionUrlOcppConfiguration() && !this.getConfigurationKey(this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
)) {
586 this.addConfigurationKey(VendorDefaultParametersKey
.ConnectionUrl
, this.getConfiguredSupervisionUrl().href
, { reboot
: true });
588 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
589 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
591 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), { readonly: true });
592 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
593 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
595 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
596 const connectorPhaseRotation
= [];
597 for (const connectorId
of this.connectors
.keys()) {
599 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
600 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
601 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
602 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
604 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
605 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
606 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
607 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
610 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
612 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
613 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
615 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
616 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
617 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
619 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
620 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
624 private async onOpen(): Promise
<void> {
625 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
626 if (!this.isRegistered()) {
627 // Send BootNotification
628 let registrationRetryCount
= 0;
630 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
631 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
632 if (!this.isRegistered()) {
633 registrationRetryCount
++;
634 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
636 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
638 if (this.isRegistered() && this.stationInfo
.autoRegister
) {
639 await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
640 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
642 if (this.isRegistered()) {
643 await this.startMessageSequence();
644 this.stopped
&& (this.stopped
= false);
645 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
646 this.flushMessageBuffer();
649 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
651 this.autoReconnectRetryCount
= 0;
652 this.wsConnectionRestarted
= false;
655 private async onClose(code
: number, reason
: string): Promise
<void> {
658 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
659 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
660 logger
.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
661 this.autoReconnectRetryCount
= 0;
665 logger
.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
666 await this.reconnect(code
);
671 private async onMessage(data
: Data
): Promise
<void> {
672 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
673 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
674 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
675 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
676 let requestPayload
: Record
<string, unknown
>;
677 let cachedRequest
: CachedRequest
;
680 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
681 if (Utils
.isIterable(request
)) {
683 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
685 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
687 // Check the Type of message
688 switch (messageType
) {
690 case MessageType
.CALL_MESSAGE
:
691 if (this.getEnableStatistics()) {
692 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
695 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
698 case MessageType
.CALL_RESULT_MESSAGE
:
700 cachedRequest
= this.requests
.get(messageId
);
701 if (Utils
.isIterable(cachedRequest
)) {
702 [responseCallback
, , , requestPayload
] = cachedRequest
;
704 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} response is not iterable`, commandName
);
706 if (!responseCallback
) {
708 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response for unknown message id ${messageId}`, commandName
);
710 responseCallback(commandName
, requestPayload
);
713 case MessageType
.CALL_ERROR_MESSAGE
:
714 cachedRequest
= this.requests
.get(messageId
);
715 if (Utils
.isIterable(cachedRequest
)) {
716 [, rejectCallback
, requestCommandName
] = cachedRequest
;
718 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} error response is not iterable`);
720 if (!rejectCallback
) {
722 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error response for unknown message id ${messageId}`, requestCommandName
);
724 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
));
728 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
729 logger
.error(errMsg
);
730 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
734 logger
.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data
.toString(), this.requests
.get(messageId
), error
);
736 messageType
=== MessageType
.CALL_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
);
740 private onPing(): void {
741 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
744 private onPong(): void {
745 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
748 private async onError(error
: WSError
): Promise
<void> {
749 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
750 // switch (error.code) {
751 // case 'ECONNREFUSED':
752 // await this.reconnect(error);
757 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
758 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
761 private getAuthorizationFile(): string | undefined {
762 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
765 private getAuthorizedTags(): string[] {
766 let authorizedTags
: string[] = [];
767 const authorizationFile
= this.getAuthorizationFile();
768 if (authorizationFile
) {
770 // Load authorization file
771 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
772 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
773 fs
.closeSync(fileDescriptor
);
775 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
as NodeJS
.ErrnoException
);
778 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
780 return authorizedTags
;
783 private getUseConnectorId0(): boolean | undefined {
784 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
787 private getNumberOfRunningTransactions(): number {
789 for (const connectorId
of this.connectors
.keys()) {
790 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
798 private getConnectionTimeout(): number | undefined {
799 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
800 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
802 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
805 // -1 for unlimited, 0 for disabling
806 private getAutoReconnectMaxRetries(): number | undefined {
807 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
808 return this.stationInfo
.autoReconnectMaxRetries
;
810 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
811 return Configuration
.getAutoReconnectMaxRetries();
817 private getRegistrationMaxRetries(): number | undefined {
818 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
819 return this.stationInfo
.registrationMaxRetries
;
824 private getPowerDivider(): number {
825 let powerDivider
= this.getNumberOfConnectors();
826 if (this.stationInfo
.powerSharedByConnectors
) {
827 powerDivider
= this.getNumberOfRunningTransactions();
832 private getTemplateMaxNumberOfConnectors(): number {
833 return Object.keys(this.stationInfo
.Connectors
).length
;
836 private getMaxNumberOfConnectors(): number {
837 let maxConnectors
: number;
838 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
839 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
840 // Distribute evenly the number of connectors
841 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
842 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
843 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
845 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
847 return maxConnectors
;
850 private async startMessageSequence(): Promise
<void> {
851 // Start WebSocket ping
852 this.startWebSocketPing();
854 this.startHeartbeat();
855 // Initialize connectors status
856 for (const connectorId
of this.connectors
.keys()) {
857 if (connectorId
=== 0) {
859 } else if (!this.stopped
&& !this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
860 // Send status in template at startup
861 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
862 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
863 } else if (this.stopped
&& this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
864 // Send status in template after reset
865 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
866 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
867 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
868 // Send previous status at template reload
869 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).status);
871 // Send default status
872 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
873 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
877 this.startAutomaticTransactionGenerator();
880 private startAutomaticTransactionGenerator() {
881 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
882 if (!this.automaticTransactionGenerator
) {
883 this.automaticTransactionGenerator
= new AutomaticTransactionGenerator(this);
885 if (!this.automaticTransactionGenerator
.started
) {
886 this.automaticTransactionGenerator
.start();
891 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
892 // Stop WebSocket ping
893 this.stopWebSocketPing();
895 this.stopHeartbeat();
897 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
898 this.automaticTransactionGenerator
&&
899 this.automaticTransactionGenerator
.started
) {
900 this.automaticTransactionGenerator
.stop();
902 for (const connectorId
of this.connectors
.keys()) {
903 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
904 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
905 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
906 this.getTransactionIdTag(transactionId
), reason
);
912 private startWebSocketPing(): void {
913 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
914 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
916 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
917 this.webSocketPingSetInterval
= setInterval(() => {
918 if (this.isWebSocketConnectionOpened()) {
919 this.wsConnection
.ping((): void => { /* This is intentional */ });
921 }, webSocketPingInterval
* 1000);
922 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.formatDurationSeconds(webSocketPingInterval
));
923 } else if (this.webSocketPingSetInterval
) {
924 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.formatDurationSeconds(webSocketPingInterval
) + ' already started');
926 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
930 private stopWebSocketPing(): void {
931 if (this.webSocketPingSetInterval
) {
932 clearInterval(this.webSocketPingSetInterval
);
936 private getConfiguredSupervisionUrl(): URL
{
937 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionUrl
?? Configuration
.getSupervisionUrls());
939 if (!Utils
.isEmptyArray(supervisionUrls
)) {
940 if (Configuration
.getDistributeStationsToTenantsEqually()) {
941 indexUrl
= this.index
% supervisionUrls
.length
;
944 indexUrl
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
946 return new URL(supervisionUrls
[indexUrl
]);
948 return new URL(supervisionUrls
as string);
951 private getHeartbeatInterval(): number | undefined {
952 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
953 if (HeartbeatInterval
) {
954 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
956 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
957 if (HeartBeatInterval
) {
958 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
960 !this.stationInfo
.autoRegister
&& logger
.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
961 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
964 private stopHeartbeat(): void {
965 if (this.heartbeatSetInterval
) {
966 clearInterval(this.heartbeatSetInterval
);
970 private openWSConnection(options
: ClientOptions
& ClientRequestArgs
= this.stationInfo
.wsOptions
, forceCloseOpened
= false): void {
971 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
972 if (!Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) && !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)) {
973 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
975 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
976 this.wsConnection
.close();
978 let protocol
: string;
979 switch (this.getOcppVersion()) {
980 case OCPPVersion
.VERSION_16
:
981 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
984 this.handleUnsupportedVersion(this.getOcppVersion());
987 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
988 logger
.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString());
991 private stopMeterValues(connectorId
: number) {
992 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
993 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
997 private startAuthorizationFileMonitoring(): void {
998 const authorizationFile
= this.getAuthorizationFile();
999 if (authorizationFile
) {
1001 fs
.watch(authorizationFile
, (event
, filename
) => {
1002 if (filename
&& event
=== 'change') {
1004 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
1005 // Initialize authorizedTags
1006 this.authorizedTags
= this.getAuthorizedTags();
1008 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
1013 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
as NodeJS
.ErrnoException
);
1016 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
1020 private startStationTemplateFileMonitoring(): void {
1022 fs
.watch(this.stationTemplateFile
, (event
, filename
): void => {
1023 if (filename
&& event
=== 'change') {
1025 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
1029 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1030 this.automaticTransactionGenerator
) {
1031 this.automaticTransactionGenerator
.stop();
1033 this.startAutomaticTransactionGenerator();
1034 if (this.getEnableStatistics()) {
1035 this.performanceStatistics
.restart();
1037 this.performanceStatistics
.stop();
1039 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1041 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
1046 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
as NodeJS
.ErrnoException
);
1050 private getReconnectExponentialDelay(): boolean | undefined {
1051 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
1054 private async reconnect(code
: number): Promise
<void> {
1055 // Stop WebSocket ping
1056 this.stopWebSocketPing();
1058 this.stopHeartbeat();
1059 // Stop the ATG if needed
1060 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1061 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1062 this.automaticTransactionGenerator
&&
1063 this.automaticTransactionGenerator
.started
) {
1064 this.automaticTransactionGenerator
.stop();
1066 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1067 this.autoReconnectRetryCount
++;
1068 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
1069 const reconnectTimeout
= (reconnectDelay
- 100) > 0 && reconnectDelay
;
1070 logger
.error(`${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`);
1071 await Utils
.sleep(reconnectDelay
);
1072 logger
.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
1073 this.openWSConnection({ ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
}, true);
1074 this.wsConnectionRestarted
= true;
1075 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1076 logger
.error(`${this.logPrefix()} WebSocket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1080 private initializeConnectorStatus(connectorId
: number): void {
1081 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
1082 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
1083 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
1084 this.getConnectorStatus(connectorId
).transactionStarted
= false;
1085 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
1086 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;