f7e654f94108ad41b1678695a56465e2ca113578
[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 { JsonType } from '../types/JsonType';
24 import { MessageType } from '../types/ocpp/MessageType';
25 import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
26 import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
27 import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
28 import OCPPError from '../exception/OCPPError';
29 import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
30 import OCPPRequestService from './ocpp/OCPPRequestService';
31 import { OCPPVersion } from '../types/ocpp/OCPPVersion';
32 import PerformanceStatistics from '../performance/PerformanceStatistics';
33 import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates';
34 import { StopTransactionReason } from '../types/ocpp/Transaction';
35 import { SupervisionUrlDistribution } from '../types/ConfigurationData';
36 import { URL } from 'url';
37 import Utils from '../utils/Utils';
38 import crypto from 'crypto';
39 import fs from 'fs';
40 import logger from '../utils/Logger';
41 import { parentPort } from 'worker_threads';
42 import path from 'path';
43
44 export default class ChargingStation {
45 public readonly id: string;
46 public readonly stationTemplateFile: string;
47 public authorizedTags: string[];
48 public stationInfo!: ChargingStationInfo;
49 public readonly connectors: Map<number, ConnectorStatus>;
50 public configuration!: ChargingStationConfiguration;
51 public wsConnection!: WebSocket;
52 public readonly requests: Map<string, CachedRequest>;
53 public performanceStatistics!: PerformanceStatistics;
54 public heartbeatSetInterval!: NodeJS.Timeout;
55 public ocppRequestService!: OCPPRequestService;
56 private readonly index: number;
57 private bootNotificationRequest!: BootNotificationRequest;
58 private bootNotificationResponse!: BootNotificationResponse | null;
59 private connectorsConfigurationHash!: string;
60 private ocppIncomingRequestService!: OCPPIncomingRequestService;
61 private readonly messageBuffer: Set<string>;
62 private wsConfiguredConnectionUrl!: URL;
63 private wsConnectionRestarted: boolean;
64 private stopped: boolean;
65 private autoReconnectRetryCount: number;
66 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
67 private webSocketPingSetInterval!: NodeJS.Timeout;
68
69 constructor(index: number, stationTemplateFile: string) {
70 this.id = Utils.generateUUID();
71 this.index = index;
72 this.stationTemplateFile = stationTemplateFile;
73 this.stopped = false;
74 this.wsConnectionRestarted = false;
75 this.autoReconnectRetryCount = 0;
76 this.connectors = new Map<number, ConnectorStatus>();
77 this.requests = new Map<string, CachedRequest>();
78 this.messageBuffer = new Set<string>();
79 this.initialize();
80 this.authorizedTags = this.getAuthorizedTags();
81 }
82
83 get wsConnectionUrl(): URL {
84 return this.getSupervisionUrlOcppConfiguration() ? new URL(this.getConfigurationKey(this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl).value + '/' + this.stationInfo.chargingStationId) : this.wsConfiguredConnectionUrl;
85 }
86
87 public logPrefix(): string {
88 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
89 }
90
91 public getBootNotificationRequest(): BootNotificationRequest {
92 return this.bootNotificationRequest;
93 }
94
95 public getRandomIdTag(): string {
96 const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
97 return this.authorizedTags[index];
98 }
99
100 public hasAuthorizedTags(): boolean {
101 return !Utils.isEmptyArray(this.authorizedTags);
102 }
103
104 public getEnableStatistics(): boolean | undefined {
105 return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true;
106 }
107
108 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
109 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
110 }
111
112 public getNumberOfPhases(): number | undefined {
113 switch (this.getCurrentOutType()) {
114 case CurrentType.AC:
115 return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3;
116 case CurrentType.DC:
117 return 0;
118 }
119 }
120
121 public isWebSocketConnectionOpened(): boolean {
122 return this?.wsConnection?.readyState === OPEN;
123 }
124
125 public getRegistrationStatus(): RegistrationStatus {
126 return this?.bootNotificationResponse?.status;
127 }
128
129 public isInUnknownState(): boolean {
130 return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status);
131 }
132
133 public isInPendingState(): boolean {
134 return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING;
135 }
136
137 public isInAcceptedState(): boolean {
138 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
139 }
140
141 public isInRejectedState(): boolean {
142 return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED;
143 }
144
145 public isRegistered(): boolean {
146 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
147 }
148
149 public isChargingStationAvailable(): boolean {
150 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
151 }
152
153 public isConnectorAvailable(id: number): boolean {
154 return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
155 }
156
157 public getNumberOfConnectors(): number {
158 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
159 }
160
161 public getConnectorStatus(id: number): ConnectorStatus {
162 return this.connectors.get(id);
163 }
164
165 public getCurrentOutType(): CurrentType | undefined {
166 return this.stationInfo.currentOutType ?? CurrentType.AC;
167 }
168
169 public getOcppStrictCompliance(): boolean {
170 return this.stationInfo.ocppStrictCompliance ?? false;
171 }
172
173 public getVoltageOut(): number | undefined {
174 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
175 let defaultVoltageOut: number;
176 switch (this.getCurrentOutType()) {
177 case CurrentType.AC:
178 defaultVoltageOut = Voltage.VOLTAGE_230;
179 break;
180 case CurrentType.DC:
181 defaultVoltageOut = Voltage.VOLTAGE_400;
182 break;
183 default:
184 logger.error(errMsg);
185 throw new Error(errMsg);
186 }
187 return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut;
188 }
189
190 public getTransactionIdTag(transactionId: number): string | undefined {
191 for (const connectorId of this.connectors.keys()) {
192 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
193 return this.getConnectorStatus(connectorId).transactionIdTag;
194 }
195 }
196 }
197
198 public getOutOfOrderEndMeterValues(): boolean {
199 return this.stationInfo.outOfOrderEndMeterValues ?? false;
200 }
201
202 public getBeginEndMeterValues(): boolean {
203 return this.stationInfo.beginEndMeterValues ?? false;
204 }
205
206 public getMeteringPerTransaction(): boolean {
207 return this.stationInfo.meteringPerTransaction ?? true;
208 }
209
210 public getTransactionDataMeterValues(): boolean {
211 return this.stationInfo.transactionDataMeterValues ?? false;
212 }
213
214 public getMainVoltageMeterValues(): boolean {
215 return this.stationInfo.mainVoltageMeterValues ?? true;
216 }
217
218 public getPhaseLineToLineVoltageMeterValues(): boolean {
219 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
220 }
221
222 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
223 if (this.getMeteringPerTransaction()) {
224 for (const connectorId of this.connectors.keys()) {
225 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
226 return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
227 }
228 }
229 }
230 for (const connectorId of this.connectors.keys()) {
231 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
232 return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
233 }
234 }
235 }
236
237 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
238 if (this.getMeteringPerTransaction()) {
239 return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
240 }
241 return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
242 }
243
244 public getAuthorizeRemoteTxRequests(): boolean {
245 const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests);
246 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
247 }
248
249 public getLocalAuthListEnabled(): boolean {
250 const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled);
251 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
252 }
253
254 public restartWebSocketPing(): void {
255 // Stop WebSocket ping
256 this.stopWebSocketPing();
257 // Start WebSocket ping
258 this.startWebSocketPing();
259 }
260
261 public getSampledValueTemplate(connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
262 phase?: MeterValuePhase): SampledValueTemplate | undefined {
263 const onPhaseStr = phase ? `on phase ${phase} ` : '';
264 if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
265 logger.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`);
266 return;
267 }
268 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
269 logger.debug(`${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${StandardParametersKey.MeterValuesSampledData}' OCPP parameter`);
270 return;
271 }
272 const sampledValueTemplates: SampledValueTemplate[] = this.getConnectorStatus(connectorId).MeterValues;
273 for (let index = 0; !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length; index++) {
274 if (!Constants.SUPPORTED_MEASURANDS.includes(sampledValueTemplates[index]?.measurand ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER)) {
275 logger.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`);
276 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
277 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
278 return sampledValueTemplates[index];
279 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
280 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
281 return sampledValueTemplates[index];
282 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
283 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
284 return sampledValueTemplates[index];
285 }
286 }
287 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
288 const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
289 logger.error(errorMsg);
290 throw new Error(errorMsg);
291 }
292 logger.debug(`${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`);
293 }
294
295 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
296 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
297 }
298
299 public startHeartbeat(): void {
300 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
301 // eslint-disable-next-line @typescript-eslint/no-misused-promises
302 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
303 await this.ocppRequestService.sendHeartbeat();
304 }, this.getHeartbeatInterval());
305 logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()));
306 } else if (this.heartbeatSetInterval) {
307 logger.info(this.logPrefix() + ' Heartbeat already started every ' + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()));
308 } else {
309 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
310 }
311 }
312
313 public restartHeartbeat(): void {
314 // Stop heartbeat
315 this.stopHeartbeat();
316 // Start heartbeat
317 this.startHeartbeat();
318 }
319
320 public startMeterValues(connectorId: number, interval: number): void {
321 if (connectorId === 0) {
322 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
323 return;
324 }
325 if (!this.getConnectorStatus(connectorId)) {
326 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
327 return;
328 }
329 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
330 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
331 return;
332 } else if (this.getConnectorStatus(connectorId)?.transactionStarted && !this.getConnectorStatus(connectorId)?.transactionId) {
333 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
334 return;
335 }
336 if (interval > 0) {
337 // eslint-disable-next-line @typescript-eslint/no-misused-promises
338 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
339 await this.ocppRequestService.sendMeterValues(connectorId, this.getConnectorStatus(connectorId).transactionId, interval);
340 }, interval);
341 } else {
342 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
343 }
344 }
345
346 public start(): void {
347 if (this.getEnableStatistics()) {
348 this.performanceStatistics.start();
349 }
350 this.openWSConnection();
351 // Monitor authorization file
352 this.startAuthorizationFileMonitoring();
353 // Monitor station template file
354 this.startStationTemplateFileMonitoring();
355 // Handle WebSocket message
356 this.wsConnection.on('message', this.onMessage.bind(this));
357 // Handle WebSocket error
358 this.wsConnection.on('error', this.onError.bind(this));
359 // Handle WebSocket close
360 this.wsConnection.on('close', this.onClose.bind(this));
361 // Handle WebSocket open
362 this.wsConnection.on('open', this.onOpen.bind(this));
363 // Handle WebSocket ping
364 this.wsConnection.on('ping', this.onPing.bind(this));
365 // Handle WebSocket pong
366 this.wsConnection.on('pong', this.onPong.bind(this));
367 parentPort.postMessage({ id: ChargingStationWorkerMessageEvents.STARTED, data: { id: this.stationInfo.chargingStationId } });
368 }
369
370 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
371 // Stop message sequence
372 await this.stopMessageSequence(reason);
373 for (const connectorId of this.connectors.keys()) {
374 if (connectorId > 0) {
375 await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.UNAVAILABLE);
376 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
377 }
378 }
379 if (this.isWebSocketConnectionOpened()) {
380 this.wsConnection.close();
381 }
382 if (this.getEnableStatistics()) {
383 this.performanceStatistics.stop();
384 }
385 this.bootNotificationResponse = null;
386 parentPort.postMessage({ id: ChargingStationWorkerMessageEvents.STOPPED, data: { id: this.stationInfo.chargingStationId } });
387 this.stopped = true;
388 }
389
390 public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey | undefined {
391 return this.configuration.configurationKey.find((configElement) => {
392 if (caseInsensitive) {
393 return configElement.key.toLowerCase() === key.toLowerCase();
394 }
395 return configElement.key === key;
396 });
397 }
398
399 public addConfigurationKey(key: string | StandardParametersKey, value: string, options: { readonly?: boolean, visible?: boolean, reboot?: boolean } = { readonly: false, visible: true, reboot: false }): void {
400 const keyFound = this.getConfigurationKey(key);
401 const readonly = options.readonly;
402 const visible = options.visible;
403 const reboot = options.reboot;
404 if (!keyFound) {
405 this.configuration.configurationKey.push({
406 key,
407 readonly,
408 value,
409 visible,
410 reboot,
411 });
412 } else {
413 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound);
414 }
415 }
416
417 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
418 const keyFound = this.getConfigurationKey(key);
419 if (keyFound) {
420 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
421 this.configuration.configurationKey[keyIndex].value = value;
422 } else {
423 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value });
424 }
425 }
426
427 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
428 let cpReplaced = false;
429 if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
430 this.getConnectorStatus(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => {
431 if (chargingProfile.chargingProfileId === cp.chargingProfileId
432 || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
433 this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
434 cpReplaced = true;
435 }
436 });
437 }
438 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
439 }
440
441 public resetConnectorStatus(connectorId: number): void {
442 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
443 this.getConnectorStatus(connectorId).idTagAuthorized = false;
444 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
445 this.getConnectorStatus(connectorId).transactionStarted = false;
446 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
447 delete this.getConnectorStatus(connectorId).authorizeIdTag;
448 delete this.getConnectorStatus(connectorId).transactionId;
449 delete this.getConnectorStatus(connectorId).transactionIdTag;
450 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
451 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
452 this.stopMeterValues(connectorId);
453 }
454
455 public bufferMessage(message: string): void {
456 this.messageBuffer.add(message);
457 }
458
459 private flushMessageBuffer() {
460 if (this.messageBuffer.size > 0) {
461 this.messageBuffer.forEach((message) => {
462 // TODO: evaluate the need to track performance
463 this.wsConnection.send(message);
464 this.messageBuffer.delete(message);
465 });
466 }
467 }
468
469 private getSupervisionUrlOcppConfiguration(): boolean {
470 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
471 }
472
473 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
474 // In case of multiple instances: add instance index to charging station id
475 const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
476 const idSuffix = stationTemplate.nameSuffix ?? '';
477 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
478 }
479
480 private buildStationInfo(): ChargingStationInfo {
481 let stationTemplateFromFile: ChargingStationTemplate;
482 try {
483 // Load template file
484 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
485 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
486 fs.closeSync(fileDescriptor);
487 } catch (error) {
488 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
489 }
490 const chargingStationId = this.getChargingStationId(stationTemplateFromFile);
491 // Deprecation template keys section
492 this.warnDeprecatedTemplateKey(stationTemplateFromFile, 'supervisionUrl', chargingStationId, 'Use \'supervisionUrls\' instead');
493 this.convertDeprecatedTemplateKey(stationTemplateFromFile, 'supervisionUrl', 'supervisionUrls');
494 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
495 stationInfo.wsOptions = stationTemplateFromFile?.wsOptions ?? {};
496 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
497 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
498 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplateFromFile.power.length);
499 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
500 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
501 : stationTemplateFromFile.power[powerArrayRandomIndex];
502 } else {
503 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
504 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
505 ? stationTemplateFromFile.power * 1000
506 : stationTemplateFromFile.power;
507 }
508 delete stationInfo.power;
509 delete stationInfo.powerUnit;
510 stationInfo.chargingStationId = chargingStationId;
511 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
512 return stationInfo;
513 }
514
515 private getOcppVersion(): OCPPVersion {
516 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
517 }
518
519 private handleUnsupportedVersion(version: OCPPVersion) {
520 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
521 logger.error(errMsg);
522 throw new Error(errMsg);
523 }
524
525 private initialize(): void {
526 this.stationInfo = this.buildStationInfo();
527 this.configuration = this.getTemplateChargingStationConfiguration();
528 delete this.stationInfo.Configuration;
529 this.bootNotificationRequest = {
530 chargePointModel: this.stationInfo.chargePointModel,
531 chargePointVendor: this.stationInfo.chargePointVendor,
532 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
533 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
534 };
535 // Build connectors if needed
536 const maxConnectors = this.getMaxNumberOfConnectors();
537 if (maxConnectors <= 0) {
538 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
539 }
540 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
541 if (templateMaxConnectors <= 0) {
542 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
543 }
544 if (!this.stationInfo.Connectors[0]) {
545 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
546 }
547 // Sanity check
548 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
549 logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
550 this.stationInfo.randomConnectors = true;
551 }
552 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
553 const connectorsConfigChanged = this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
554 if (this.connectors?.size === 0 || connectorsConfigChanged) {
555 connectorsConfigChanged && (this.connectors.clear());
556 this.connectorsConfigurationHash = connectorsConfigHash;
557 // Add connector Id 0
558 let lastConnector = '0';
559 for (lastConnector in this.stationInfo.Connectors) {
560 const lastConnectorId = Utils.convertToInt(lastConnector);
561 if (lastConnectorId === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
562 this.connectors.set(lastConnectorId, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector]));
563 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
564 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
565 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
566 }
567 }
568 }
569 // Generate all connectors
570 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
571 for (let index = 1; index <= maxConnectors; index++) {
572 const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1) : index;
573 this.connectors.set(index, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId]));
574 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
575 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
576 this.getConnectorStatus(index).chargingProfiles = [];
577 }
578 }
579 }
580 }
581 // Avoid duplication of connectors related information
582 delete this.stationInfo.Connectors;
583 // Initialize transaction attributes on connectors
584 for (const connectorId of this.connectors.keys()) {
585 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
586 this.initializeConnectorStatus(connectorId);
587 }
588 }
589 this.wsConfiguredConnectionUrl = new URL(this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId);
590 switch (this.getOcppVersion()) {
591 case OCPPVersion.VERSION_16:
592 this.ocppIncomingRequestService = OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(this);
593 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(this, OCPP16ResponseService.getInstance<OCPP16ResponseService>(this));
594 break;
595 default:
596 this.handleUnsupportedVersion(this.getOcppVersion());
597 break;
598 }
599 // OCPP parameters
600 this.initOcppParameters();
601 if (this.stationInfo.autoRegister) {
602 this.bootNotificationResponse = {
603 currentTime: new Date().toISOString(),
604 interval: this.getHeartbeatInterval() / 1000,
605 status: RegistrationStatus.ACCEPTED
606 };
607 }
608 this.stationInfo.powerDivider = this.getPowerDivider();
609 if (this.getEnableStatistics()) {
610 this.performanceStatistics = PerformanceStatistics.getInstance(this.id, this.stationInfo.chargingStationId, this.wsConnectionUrl);
611 }
612 }
613
614 private initOcppParameters(): void {
615 if (this.getSupervisionUrlOcppConfiguration() && !this.getConfigurationKey(this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl)) {
616 this.addConfigurationKey(VendorDefaultParametersKey.ConnectionUrl, this.getConfiguredSupervisionUrl().href, { reboot: true });
617 }
618 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
619 this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
620 }
621 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), { readonly: true });
622 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
623 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
624 }
625 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
626 const connectorPhaseRotation = [];
627 for (const connectorId of this.connectors.keys()) {
628 // AC/DC
629 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
630 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
631 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
632 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
633 // AC
634 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
635 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
636 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
637 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
638 }
639 }
640 this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString());
641 }
642 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
643 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
644 }
645 if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled)
646 && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) {
647 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
648 }
649 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
650 this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString());
651 }
652 }
653
654 private async onOpen(): Promise<void> {
655 logger.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
656 if (!this.isInAcceptedState()) {
657 // Send BootNotification
658 let registrationRetryCount = 0;
659 do {
660 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
661 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
662 if (!this.isInAcceptedState()) {
663 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
664 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
665 }
666 } while (!this.isInAcceptedState() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
667 }
668 if (this.isInAcceptedState()) {
669 await this.startMessageSequence();
670 this.stopped && (this.stopped = false);
671 if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) {
672 this.flushMessageBuffer();
673 }
674 } else {
675 logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
676 }
677 this.autoReconnectRetryCount = 0;
678 this.wsConnectionRestarted = false;
679 }
680
681 private async onClose(code: number, reason: string): Promise<void> {
682 switch (code) {
683 // Normal close
684 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
685 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
686 logger.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
687 this.autoReconnectRetryCount = 0;
688 break;
689 // Abnormal close
690 default:
691 logger.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
692 await this.reconnect(code);
693 break;
694 }
695 }
696
697 private async onMessage(data: Data): Promise<void> {
698 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
699 let responseCallback: (payload: JsonType | string, requestPayload: JsonType | OCPPError) => void;
700 let rejectCallback: (error: OCPPError, requestStatistic?: boolean) => void;
701 let requestCommandName: RequestCommand | IncomingRequestCommand;
702 let requestPayload: JsonType | OCPPError;
703 let cachedRequest: CachedRequest;
704 let errMsg: string;
705 try {
706 const request = JSON.parse(data.toString()) as IncomingRequest;
707 if (Utils.isIterable(request)) {
708 // Parse the message
709 [messageType, messageId, commandName, commandPayload, errorDetails] = request;
710 } else {
711 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming request is not iterable', commandName);
712 }
713 // Check the Type of message
714 switch (messageType) {
715 // Incoming Message
716 case MessageType.CALL_MESSAGE:
717 if (this.getEnableStatistics()) {
718 this.performanceStatistics.addRequestStatistic(commandName, messageType);
719 }
720 // Process the call
721 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
722 break;
723 // Outcome Message
724 case MessageType.CALL_RESULT_MESSAGE:
725 // Respond
726 cachedRequest = this.requests.get(messageId);
727 if (Utils.isIterable(cachedRequest)) {
728 [responseCallback, , , requestPayload] = cachedRequest;
729 } else {
730 throw new OCPPError(ErrorType.PROTOCOL_ERROR, `Cached request for message id ${messageId} response is not iterable`, commandName);
731 }
732 if (!responseCallback) {
733 // Error
734 throw new OCPPError(ErrorType.INTERNAL_ERROR, `Response for unknown message id ${messageId}`, commandName);
735 }
736 responseCallback(commandName, requestPayload);
737 break;
738 // Error Message
739 case MessageType.CALL_ERROR_MESSAGE:
740 cachedRequest = this.requests.get(messageId);
741 if (Utils.isIterable(cachedRequest)) {
742 [, rejectCallback, requestCommandName] = cachedRequest;
743 } else {
744 throw new OCPPError(ErrorType.PROTOCOL_ERROR, `Cached request for message id ${messageId} error response is not iterable`);
745 }
746 if (!rejectCallback) {
747 // Error
748 throw new OCPPError(ErrorType.INTERNAL_ERROR, `Error response for unknown message id ${messageId}`, requestCommandName);
749 }
750 rejectCallback(new OCPPError(commandName, commandPayload.toString(), requestCommandName, errorDetails));
751 break;
752 // Error
753 default:
754 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
755 logger.error(errMsg);
756 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
757 }
758 } catch (error) {
759 // Log
760 logger.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data.toString(), this.requests.get(messageId), error);
761 // Send error
762 messageType === MessageType.CALL_MESSAGE && await this.ocppRequestService.sendError(messageId, error as OCPPError, commandName);
763 }
764 }
765
766 private onPing(): void {
767 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
768 }
769
770 private onPong(): void {
771 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
772 }
773
774 private async onError(error: WSError): Promise<void> {
775 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
776 // switch (error.code) {
777 // case 'ECONNREFUSED':
778 // await this.reconnect(error);
779 // break;
780 // }
781 }
782
783 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
784 return this.stationInfo.Configuration ?? {} as ChargingStationConfiguration;
785 }
786
787 private getAuthorizationFile(): string | undefined {
788 return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile));
789 }
790
791 private getAuthorizedTags(): string[] {
792 let authorizedTags: string[] = [];
793 const authorizationFile = this.getAuthorizationFile();
794 if (authorizationFile) {
795 try {
796 // Load authorization file
797 const fileDescriptor = fs.openSync(authorizationFile, 'r');
798 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
799 fs.closeSync(fileDescriptor);
800 } catch (error) {
801 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException);
802 }
803 } else {
804 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
805 }
806 return authorizedTags;
807 }
808
809 private getUseConnectorId0(): boolean | undefined {
810 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
811 }
812
813 private getNumberOfRunningTransactions(): number {
814 let trxCount = 0;
815 for (const connectorId of this.connectors.keys()) {
816 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
817 trxCount++;
818 }
819 }
820 return trxCount;
821 }
822
823 // 0 for disabling
824 private getConnectionTimeout(): number | undefined {
825 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
826 return parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? Constants.DEFAULT_CONNECTION_TIMEOUT;
827 }
828 return Constants.DEFAULT_CONNECTION_TIMEOUT;
829 }
830
831 // -1 for unlimited, 0 for disabling
832 private getAutoReconnectMaxRetries(): number | undefined {
833 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
834 return this.stationInfo.autoReconnectMaxRetries;
835 }
836 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
837 return Configuration.getAutoReconnectMaxRetries();
838 }
839 return -1;
840 }
841
842 // 0 for disabling
843 private getRegistrationMaxRetries(): number | undefined {
844 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
845 return this.stationInfo.registrationMaxRetries;
846 }
847 return -1;
848 }
849
850 private getPowerDivider(): number {
851 let powerDivider = this.getNumberOfConnectors();
852 if (this.stationInfo.powerSharedByConnectors) {
853 powerDivider = this.getNumberOfRunningTransactions();
854 }
855 return powerDivider;
856 }
857
858 private getTemplateMaxNumberOfConnectors(): number {
859 return Object.keys(this.stationInfo.Connectors).length;
860 }
861
862 private getMaxNumberOfConnectors(): number {
863 let maxConnectors: number;
864 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
865 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
866 // Distribute evenly the number of connectors
867 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
868 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
869 maxConnectors = this.stationInfo.numberOfConnectors as number;
870 } else {
871 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
872 }
873 return maxConnectors;
874 }
875
876 private async startMessageSequence(): Promise<void> {
877 if (this.stationInfo.autoRegister) {
878 await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
879 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
880 }
881 // Start WebSocket ping
882 this.startWebSocketPing();
883 // Start heartbeat
884 this.startHeartbeat();
885 // Initialize connectors status
886 for (const connectorId of this.connectors.keys()) {
887 if (connectorId === 0) {
888 continue;
889 } else if (!this.stopped && !this.getConnectorStatus(connectorId)?.status && this.getConnectorStatus(connectorId)?.bootStatus) {
890 // Send status in template at startup
891 await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).bootStatus);
892 this.getConnectorStatus(connectorId).status = this.getConnectorStatus(connectorId).bootStatus;
893 } else if (this.stopped && this.getConnectorStatus(connectorId)?.status && this.getConnectorStatus(connectorId)?.bootStatus) {
894 // Send status in template after reset
895 await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).bootStatus);
896 this.getConnectorStatus(connectorId).status = this.getConnectorStatus(connectorId).bootStatus;
897 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
898 // Send previous status at template reload
899 await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).status);
900 } else {
901 // Send default status
902 await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE);
903 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
904 }
905 }
906 // Start the ATG
907 this.startAutomaticTransactionGenerator();
908 }
909
910 private startAutomaticTransactionGenerator() {
911 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
912 if (!this.automaticTransactionGenerator) {
913 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this);
914 }
915 if (!this.automaticTransactionGenerator.started) {
916 this.automaticTransactionGenerator.start();
917 }
918 }
919 }
920
921 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
922 // Stop WebSocket ping
923 this.stopWebSocketPing();
924 // Stop heartbeat
925 this.stopHeartbeat();
926 // Stop the ATG
927 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
928 this.automaticTransactionGenerator?.started) {
929 this.automaticTransactionGenerator.stop();
930 } else {
931 for (const connectorId of this.connectors.keys()) {
932 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
933 const transactionId = this.getConnectorStatus(connectorId).transactionId;
934 await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId),
935 this.getTransactionIdTag(transactionId), reason);
936 }
937 }
938 }
939 }
940
941 private startWebSocketPing(): void {
942 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval)
943 ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value)
944 : 0;
945 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
946 this.webSocketPingSetInterval = setInterval(() => {
947 if (this.isWebSocketConnectionOpened()) {
948 this.wsConnection.ping((): void => { /* This is intentional */ });
949 }
950 }, webSocketPingInterval * 1000);
951 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.formatDurationSeconds(webSocketPingInterval));
952 } else if (this.webSocketPingSetInterval) {
953 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.formatDurationSeconds(webSocketPingInterval) + ' already started');
954 } else {
955 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
956 }
957 }
958
959 private stopWebSocketPing(): void {
960 if (this.webSocketPingSetInterval) {
961 clearInterval(this.webSocketPingSetInterval);
962 }
963 }
964
965 private warnDeprecatedTemplateKey(template: ChargingStationTemplate, key: string, chargingStationId: string, logMsgToAppend = ''): void {
966 if (!Utils.isUndefined(template[key])) {
967 logger.warn(`${Utils.logPrefix(` ${chargingStationId} |`)} Deprecated template key '${key}' usage in file '${this.stationTemplateFile}'${logMsgToAppend && '. ' + logMsgToAppend}`);
968 }
969 }
970
971 private convertDeprecatedTemplateKey(template: ChargingStationTemplate, deprecatedKey: string, key: string): void {
972 if (!Utils.isUndefined(template[deprecatedKey])) {
973 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
974 template[key] = template[deprecatedKey];
975 delete template[deprecatedKey];
976 }
977 }
978
979 private getConfiguredSupervisionUrl(): URL {
980 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls());
981 if (!Utils.isEmptyArray(supervisionUrls)) {
982 let urlIndex = 0;
983 switch (Configuration.getSupervisionUrlDistribution()) {
984 case SupervisionUrlDistribution.ROUND_ROBIN:
985 urlIndex = (this.index - 1) % supervisionUrls.length;
986 break;
987 case SupervisionUrlDistribution.RANDOM:
988 // Get a random url
989 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
990 break;
991 case SupervisionUrlDistribution.SEQUENTIAL:
992 if (this.index <= supervisionUrls.length) {
993 urlIndex = this.index - 1;
994 } else {
995 logger.warn(`${this.logPrefix()} No more configured supervision urls available, using the first one`);
996 }
997 break;
998 default:
999 logger.error(`${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${SupervisionUrlDistribution.ROUND_ROBIN}`);
1000 urlIndex = (this.index - 1) % supervisionUrls.length;
1001 break;
1002 }
1003 return new URL(supervisionUrls[urlIndex]);
1004 }
1005 return new URL(supervisionUrls as string);
1006 }
1007
1008 private getHeartbeatInterval(): number | undefined {
1009 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
1010 if (HeartbeatInterval) {
1011 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1012 }
1013 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
1014 if (HeartBeatInterval) {
1015 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1016 }
1017 !this.stationInfo.autoRegister && logger.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
1018 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1019 }
1020
1021 private stopHeartbeat(): void {
1022 if (this.heartbeatSetInterval) {
1023 clearInterval(this.heartbeatSetInterval);
1024 }
1025 }
1026
1027 private openWSConnection(options: ClientOptions & ClientRequestArgs = this.stationInfo.wsOptions, forceCloseOpened = false): void {
1028 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
1029 if (!Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)) {
1030 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1031 }
1032 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
1033 this.wsConnection.close();
1034 }
1035 let protocol: string;
1036 switch (this.getOcppVersion()) {
1037 case OCPPVersion.VERSION_16:
1038 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1039 break;
1040 default:
1041 this.handleUnsupportedVersion(this.getOcppVersion());
1042 break;
1043 }
1044 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
1045 logger.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString());
1046 }
1047
1048 private stopMeterValues(connectorId: number) {
1049 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1050 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1051 }
1052 }
1053
1054 private startAuthorizationFileMonitoring(): void {
1055 const authorizationFile = this.getAuthorizationFile();
1056 if (authorizationFile) {
1057 try {
1058 fs.watch(authorizationFile, (event, filename) => {
1059 if (filename && event === 'change') {
1060 try {
1061 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
1062 // Initialize authorizedTags
1063 this.authorizedTags = this.getAuthorizedTags();
1064 } catch (error) {
1065 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
1066 }
1067 }
1068 });
1069 } catch (error) {
1070 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException);
1071 }
1072 } else {
1073 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
1074 }
1075 }
1076
1077 private startStationTemplateFileMonitoring(): void {
1078 try {
1079 fs.watch(this.stationTemplateFile, (event, filename): void => {
1080 if (filename && event === 'change') {
1081 try {
1082 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
1083 // Initialize
1084 this.initialize();
1085 // Restart the ATG
1086 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
1087 this.automaticTransactionGenerator) {
1088 this.automaticTransactionGenerator.stop();
1089 }
1090 this.startAutomaticTransactionGenerator();
1091 if (this.getEnableStatistics()) {
1092 this.performanceStatistics.restart();
1093 } else {
1094 this.performanceStatistics.stop();
1095 }
1096 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1097 } catch (error) {
1098 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
1099 }
1100 }
1101 });
1102 } catch (error) {
1103 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
1104 }
1105 }
1106
1107 private getReconnectExponentialDelay(): boolean | undefined {
1108 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1109 }
1110
1111 private async reconnect(code: number): Promise<void> {
1112 // Stop WebSocket ping
1113 this.stopWebSocketPing();
1114 // Stop heartbeat
1115 this.stopHeartbeat();
1116 // Stop the ATG if needed
1117 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1118 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1119 this.automaticTransactionGenerator?.started) {
1120 this.automaticTransactionGenerator.stop();
1121 }
1122 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1123 this.autoReconnectRetryCount++;
1124 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1125 const reconnectTimeout = (reconnectDelay - 100) > 0 && reconnectDelay;
1126 logger.error(`${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`);
1127 await Utils.sleep(reconnectDelay);
1128 logger.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1129 this.openWSConnection({ ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout }, true);
1130 this.wsConnectionRestarted = true;
1131 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1132 logger.error(`${this.logPrefix()} WebSocket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1133 }
1134 }
1135
1136 private initializeConnectorStatus(connectorId: number): void {
1137 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1138 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1139 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
1140 this.getConnectorStatus(connectorId).transactionStarted = false;
1141 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
1142 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
1143 }
1144 }
1145