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