Add charging stations listing to WS server commands
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
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';
12
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';
36 import fs from 'fs';
37 import logger from '../utils/Logger';
38 import { parentPort } from 'worker_threads';
39 import path from 'path';
40
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;
64
65 constructor(index: number, stationTemplateFile: string) {
66 this.index = index;
67 this.stationTemplateFile = stationTemplateFile;
68 this.connectors = new Map<number, ConnectorStatus>();
69 this.initialize();
70
71 this.stopped = false;
72 this.wsConnectionRestarted = false;
73 this.autoReconnectRetryCount = 0;
74
75 this.requests = new Map<string, CachedRequest>();
76 this.messageBuffer = new Set<string>();
77
78 this.authorizedTags = this.getAuthorizedTags();
79 }
80
81 get wsConnectionUrl(): URL {
82 return this.getSupervisionURLOCPPConfiguration() ? new URL(this.getConfigurationKey(this.stationInfo.supervisionURLOCPPKey ?? VendorDefaultParametersKey.ConnectionUrl).value + '/' + this.stationInfo.chargingStationId) : this.wsConfiguredConnectionUrl;
83 }
84
85 public logPrefix(): string {
86 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
87 }
88
89 public getBootNotificationRequest(): BootNotificationRequest {
90 return this.bootNotificationRequest;
91 }
92
93 public getRandomIdTag(): string {
94 const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
95 return this.authorizedTags[index];
96 }
97
98 public hasAuthorizedTags(): boolean {
99 return !Utils.isEmptyArray(this.authorizedTags);
100 }
101
102 public getEnableStatistics(): boolean | undefined {
103 return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true;
104 }
105
106 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
107 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
108 }
109
110 public getNumberOfPhases(): number | undefined {
111 switch (this.getCurrentOutType()) {
112 case CurrentType.AC:
113 return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3;
114 case CurrentType.DC:
115 return 0;
116 }
117 }
118
119 public isWebSocketConnectionOpened(): boolean {
120 return this.wsConnection?.readyState === OPEN;
121 }
122
123 public isRegistered(): boolean {
124 return this.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
125 }
126
127 public isChargingStationAvailable(): boolean {
128 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
129 }
130
131 public isConnectorAvailable(id: number): boolean {
132 return this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
133 }
134
135 public getNumberOfConnectors(): number {
136 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
137 }
138
139 public getConnectorStatus(id: number): ConnectorStatus {
140 return this.connectors.get(id);
141 }
142
143 public getCurrentOutType(): CurrentType | undefined {
144 return this.stationInfo.currentOutType ?? CurrentType.AC;
145 }
146
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()) {
151 case CurrentType.AC:
152 defaultVoltageOut = Voltage.VOLTAGE_230;
153 break;
154 case CurrentType.DC:
155 defaultVoltageOut = Voltage.VOLTAGE_400;
156 break;
157 default:
158 logger.error(errMsg);
159 throw new Error(errMsg);
160 }
161 return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut;
162 }
163
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;
168 }
169 }
170 }
171
172 public getOutOfOrderEndMeterValues(): boolean {
173 return this.stationInfo.outOfOrderEndMeterValues ?? false;
174 }
175
176 public getBeginEndMeterValues(): boolean {
177 return this.stationInfo.beginEndMeterValues ?? false;
178 }
179
180 public getMeteringPerTransaction(): boolean {
181 return this.stationInfo.meteringPerTransaction ?? true;
182 }
183
184 public getTransactionDataMeterValues(): boolean {
185 return this.stationInfo.transactionDataMeterValues ?? false;
186 }
187
188 public getMainVoltageMeterValues(): boolean {
189 return this.stationInfo.mainVoltageMeterValues ?? true;
190 }
191
192 public getPhaseLineToLineVoltageMeterValues(): boolean {
193 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
194 }
195
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;
201 }
202 }
203 }
204 for (const connectorId of this.connectors.keys()) {
205 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
206 return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
207 }
208 }
209 }
210
211 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
212 if (this.getMeteringPerTransaction()) {
213 return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
214 }
215 return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
216 }
217
218 public getAuthorizeRemoteTxRequests(): boolean {
219 const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests);
220 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
221 }
222
223 public getLocalAuthListEnabled(): boolean {
224 const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled);
225 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
226 }
227
228 public restartWebSocketPing(): void {
229 // Stop WebSocket ping
230 this.stopWebSocketPing();
231 // Start WebSocket ping
232 this.startWebSocketPing();
233 }
234
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}`);
239 return;
240 }
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`);
243 return;
244 }
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];
258 }
259 }
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);
264 }
265 logger.debug(`${this.logPrefix()} No MeterValues for measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
266 }
267
268 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
269 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
270 }
271
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()));
281 } else {
282 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
283 }
284 }
285
286 public restartHeartbeat(): void {
287 // Stop heartbeat
288 this.stopHeartbeat();
289 // Start heartbeat
290 this.startHeartbeat();
291 }
292
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()}`);
296 return;
297 }
298 if (!this.getConnectorStatus(connectorId)) {
299 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
300 return;
301 }
302 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
303 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
304 return;
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`);
307 return;
308 }
309 if (interval > 0) {
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);
313 }, interval);
314 } else {
315 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
316 }
317 }
318
319 public start(): void {
320 if (this.getEnableStatistics()) {
321 this.performanceStatistics.start();
322 }
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 } });
341 }
342
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;
350 }
351 }
352 if (this.isWebSocketConnectionOpened()) {
353 this.wsConnection.close();
354 }
355 if (this.getEnableStatistics()) {
356 this.performanceStatistics.stop();
357 }
358 this.bootNotificationResponse = null;
359 parentPort.postMessage({ id: ChargingStationWorkerMessageEvents.STOPPED, data: { id: this.stationInfo.chargingStationId } });
360 this.stopped = true;
361 }
362
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();
367 }
368 return configElement.key === key;
369 });
370 }
371
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;
377 if (!keyFound) {
378 this.configuration.configurationKey.push({
379 key,
380 readonly,
381 value,
382 visible,
383 reboot,
384 });
385 } else {
386 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound);
387 }
388 }
389
390 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
391 const keyFound = this.getConfigurationKey(key);
392 if (keyFound) {
393 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
394 this.configuration.configurationKey[keyIndex].value = value;
395 } else {
396 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value });
397 }
398 }
399
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;
407 cpReplaced = true;
408 }
409 });
410 }
411 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
412 }
413
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);
426 }
427
428 public bufferMessage(message: string): void {
429 this.messageBuffer.add(message);
430 }
431
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);
438 });
439 }
440 }
441
442 private getSupervisionURLOCPPConfiguration(): boolean {
443 return this.stationInfo.supervisionURLOCPPConfiguration ?? false;
444 }
445
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;
451 }
452
453 private buildStationInfo(): ChargingStationInfo {
454 let stationTemplateFromFile: ChargingStationTemplate;
455 try {
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);
460 } catch (error) {
461 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
462 }
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];
471 } else {
472 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
473 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
474 ? stationTemplateFromFile.power * 1000
475 : stationTemplateFromFile.power;
476 }
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;
481 return stationInfo;
482 }
483
484 private getOCPPVersion(): OCPPVersion {
485 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
486 }
487
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);
492 }
493
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 },
503 };
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`);
508 }
509 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
510 if (templateMaxConnectors <= 0) {
511 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
512 }
513 if (!this.stationInfo.Connectors[0]) {
514 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
515 }
516 // Sanity check
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;
520 }
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 = [];
535 }
536 }
537 }
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 = [];
546 }
547 }
548 }
549 }
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);
556 }
557 }
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));
563 break;
564 default:
565 this.handleUnsupportedVersion(this.getOCPPVersion());
566 break;
567 }
568 // OCPP parameters
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
575 };
576 }
577 this.stationInfo.powerDivider = this.getPowerDivider();
578 if (this.getEnableStatistics()) {
579 this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId, this.wsConnectionUrl);
580 }
581 }
582
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 });
586 }
587 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
588 this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
589 }
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);
593 }
594 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
595 const connectorPhaseRotation = [];
596 for (const connectorId of this.connectors.keys()) {
597 // AC/DC
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}`);
602 // AC
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}`);
607 }
608 }
609 this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString());
610 }
611 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
612 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
613 }
614 if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled)
615 && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) {
616 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
617 }
618 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
619 this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString());
620 }
621 }
622
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;
628 do {
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);
634 }
635 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
636 }
637 if (this.isRegistered()) {
638 await this.startMessageSequence();
639 this.stopped && (this.stopped = false);
640 if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) {
641 this.flushMessageBuffer();
642 }
643 } else {
644 logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
645 }
646 this.autoReconnectRetryCount = 0;
647 this.wsConnectionRestarted = false;
648 }
649
650 private async onClose(code: number, reason: string): Promise<void> {
651 switch (code) {
652 // Normal close
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;
657 break;
658 // Abnormal close
659 default:
660 logger.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
661 await this.reconnect(code);
662 break;
663 }
664 }
665
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;
673 let errMsg: string;
674 try {
675 const request = JSON.parse(data.toString()) as IncomingRequest;
676 if (Utils.isIterable(request)) {
677 // Parse the message
678 [messageType, messageId, commandName, commandPayload, errorDetails] = request;
679 } else {
680 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming request is not iterable', commandName);
681 }
682 // Check the Type of message
683 switch (messageType) {
684 // Incoming Message
685 case MessageType.CALL_MESSAGE:
686 if (this.getEnableStatistics()) {
687 this.performanceStatistics.addRequestStatistic(commandName, messageType);
688 }
689 // Process the call
690 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
691 break;
692 // Outcome Message
693 case MessageType.CALL_RESULT_MESSAGE:
694 // Respond
695 cachedRequest = this.requests.get(messageId);
696 if (Utils.isIterable(cachedRequest)) {
697 [responseCallback, , , requestPayload] = cachedRequest;
698 } else {
699 throw new OCPPError(ErrorType.PROTOCOL_ERROR, `Cached request for message id ${messageId} response is not iterable`, commandName);
700 }
701 if (!responseCallback) {
702 // Error
703 throw new OCPPError(ErrorType.INTERNAL_ERROR, `Response for unknown message id ${messageId}`, commandName);
704 }
705 responseCallback(commandName, requestPayload);
706 break;
707 // Error Message
708 case MessageType.CALL_ERROR_MESSAGE:
709 cachedRequest = this.requests.get(messageId);
710 if (Utils.isIterable(cachedRequest)) {
711 [, rejectCallback, requestCommandName] = cachedRequest;
712 } else {
713 throw new OCPPError(ErrorType.PROTOCOL_ERROR, `Cached request for message id ${messageId} error response is not iterable`);
714 }
715 if (!rejectCallback) {
716 // Error
717 throw new OCPPError(ErrorType.INTERNAL_ERROR, `Error response for unknown message id ${messageId}`, requestCommandName);
718 }
719 rejectCallback(new OCPPError(commandName, commandPayload.toString(), requestCommandName, errorDetails));
720 break;
721 // Error
722 default:
723 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
724 logger.error(errMsg);
725 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
726 }
727 } catch (error) {
728 // Log
729 logger.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data.toString(), this.requests.get(messageId), error);
730 // Send error
731 messageType === MessageType.CALL_MESSAGE && await this.ocppRequestService.sendError(messageId, error as OCPPError, commandName);
732 }
733 }
734
735 private onPing(): void {
736 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
737 }
738
739 private onPong(): void {
740 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
741 }
742
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);
748 // break;
749 // }
750 }
751
752 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
753 return this.stationInfo.Configuration ?? {} as ChargingStationConfiguration;
754 }
755
756 private getAuthorizationFile(): string | undefined {
757 return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile));
758 }
759
760 private getAuthorizedTags(): string[] {
761 let authorizedTags: string[] = [];
762 const authorizationFile = this.getAuthorizationFile();
763 if (authorizationFile) {
764 try {
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);
769 } catch (error) {
770 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException);
771 }
772 } else {
773 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
774 }
775 return authorizedTags;
776 }
777
778 private getUseConnectorId0(): boolean | undefined {
779 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
780 }
781
782 private getNumberOfRunningTransactions(): number {
783 let trxCount = 0;
784 for (const connectorId of this.connectors.keys()) {
785 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
786 trxCount++;
787 }
788 }
789 return trxCount;
790 }
791
792 // 0 for disabling
793 private getConnectionTimeout(): number | undefined {
794 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
795 return parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? Constants.DEFAULT_CONNECTION_TIMEOUT;
796 }
797 return Constants.DEFAULT_CONNECTION_TIMEOUT;
798 }
799
800 // -1 for unlimited, 0 for disabling
801 private getAutoReconnectMaxRetries(): number | undefined {
802 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
803 return this.stationInfo.autoReconnectMaxRetries;
804 }
805 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
806 return Configuration.getAutoReconnectMaxRetries();
807 }
808 return -1;
809 }
810
811 // 0 for disabling
812 private getRegistrationMaxRetries(): number | undefined {
813 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
814 return this.stationInfo.registrationMaxRetries;
815 }
816 return -1;
817 }
818
819 private getPowerDivider(): number {
820 let powerDivider = this.getNumberOfConnectors();
821 if (this.stationInfo.powerSharedByConnectors) {
822 powerDivider = this.getNumberOfRunningTransactions();
823 }
824 return powerDivider;
825 }
826
827 private getTemplateMaxNumberOfConnectors(): number {
828 return Object.keys(this.stationInfo.Connectors).length;
829 }
830
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;
839 } else {
840 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
841 }
842 return maxConnectors;
843 }
844
845 private async startMessageSequence(): Promise<void> {
846 // Start WebSocket ping
847 this.startWebSocketPing();
848 // Start heartbeat
849 this.startHeartbeat();
850 // Initialize connectors status
851 for (const connectorId of this.connectors.keys()) {
852 if (connectorId === 0) {
853 continue;
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);
865 } else {
866 // Send default status
867 await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE);
868 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
869 }
870 }
871 // Start the ATG
872 this.startAutomaticTransactionGenerator();
873 }
874
875 private startAutomaticTransactionGenerator() {
876 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
877 if (!this.automaticTransactionGenerator) {
878 this.automaticTransactionGenerator = new AutomaticTransactionGenerator(this);
879 }
880 if (!this.automaticTransactionGenerator.started) {
881 this.automaticTransactionGenerator.start();
882 }
883 }
884 }
885
886 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
887 // Stop WebSocket ping
888 this.stopWebSocketPing();
889 // Stop heartbeat
890 this.stopHeartbeat();
891 // Stop the ATG
892 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
893 this.automaticTransactionGenerator &&
894 this.automaticTransactionGenerator.started) {
895 this.automaticTransactionGenerator.stop();
896 } else {
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);
902 }
903 }
904 }
905 }
906
907 private startWebSocketPing(): void {
908 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval)
909 ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value)
910 : 0;
911 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
912 this.webSocketPingSetInterval = setInterval(() => {
913 if (this.isWebSocketConnectionOpened()) {
914 this.wsConnection.ping((): void => { /* This is intentional */ });
915 }
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');
920 } else {
921 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
922 }
923 }
924
925 private stopWebSocketPing(): void {
926 if (this.webSocketPingSetInterval) {
927 clearInterval(this.webSocketPingSetInterval);
928 }
929 }
930
931 private getConfiguredSupervisionURL(): URL {
932 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ?? Configuration.getSupervisionURLs());
933 let indexUrl = 0;
934 if (!Utils.isEmptyArray(supervisionUrls)) {
935 if (Configuration.getDistributeStationsToTenantsEqually()) {
936 indexUrl = this.index % supervisionUrls.length;
937 } else {
938 // Get a random url
939 indexUrl = Math.floor(Utils.secureRandom() * supervisionUrls.length);
940 }
941 return new URL(supervisionUrls[indexUrl]);
942 }
943 return new URL(supervisionUrls as string);
944 }
945
946 private getHeartbeatInterval(): number | undefined {
947 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
948 if (HeartbeatInterval) {
949 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
950 }
951 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
952 if (HeartBeatInterval) {
953 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
954 }
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;
957 }
958
959 private stopHeartbeat(): void {
960 if (this.heartbeatSetInterval) {
961 clearInterval(this.heartbeatSetInterval);
962 }
963 }
964
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}`;
969 }
970 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
971 this.wsConnection.close();
972 }
973 let protocol: string;
974 switch (this.getOCPPVersion()) {
975 case OCPPVersion.VERSION_16:
976 protocol = 'ocpp' + OCPPVersion.VERSION_16;
977 break;
978 default:
979 this.handleUnsupportedVersion(this.getOCPPVersion());
980 break;
981 }
982 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
983 logger.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString());
984 }
985
986 private stopMeterValues(connectorId: number) {
987 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
988 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
989 }
990 }
991
992 private startAuthorizationFileMonitoring(): void {
993 const authorizationFile = this.getAuthorizationFile();
994 if (authorizationFile) {
995 try {
996 fs.watch(authorizationFile, (event, filename) => {
997 if (filename && event === 'change') {
998 try {
999 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
1000 // Initialize authorizedTags
1001 this.authorizedTags = this.getAuthorizedTags();
1002 } catch (error) {
1003 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
1004 }
1005 }
1006 });
1007 } catch (error) {
1008 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException);
1009 }
1010 } else {
1011 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
1012 }
1013 }
1014
1015 private startStationTemplateFileMonitoring(): void {
1016 try {
1017 fs.watch(this.stationTemplateFile, (event, filename): void => {
1018 if (filename && event === 'change') {
1019 try {
1020 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
1021 // Initialize
1022 this.initialize();
1023 // Restart the ATG
1024 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
1025 this.automaticTransactionGenerator) {
1026 this.automaticTransactionGenerator.stop();
1027 }
1028 this.startAutomaticTransactionGenerator();
1029 if (this.getEnableStatistics()) {
1030 this.performanceStatistics.restart();
1031 } else {
1032 this.performanceStatistics.stop();
1033 }
1034 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1035 } catch (error) {
1036 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
1037 }
1038 }
1039 });
1040 } catch (error) {
1041 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
1042 }
1043 }
1044
1045 private getReconnectExponentialDelay(): boolean | undefined {
1046 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1047 }
1048
1049 private async reconnect(code: number): Promise<void> {
1050 // Stop WebSocket ping
1051 this.stopWebSocketPing();
1052 // Stop heartbeat
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();
1060 }
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()})`);
1072 }
1073 }
1074
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;
1082 }
1083 }
1084