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