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