Strong type protocols payloads
[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 index: number;
56 private bootNotificationRequest!: BootNotificationRequest;
57 private bootNotificationResponse!: BootNotificationResponse | null;
58 private connectorsConfigurationHash!: string;
59 private ocppIncomingRequestService!: OCPPIncomingRequestService;
60 private readonly messageBuffer: Set<string>;
61 private wsConfiguredConnectionUrl!: URL;
62 private wsConnectionRestarted: boolean;
63 private stopped: boolean;
64 private autoReconnectRetryCount: number;
65 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
66 private webSocketPingSetInterval!: NodeJS.Timeout;
67
68 constructor(index: number, stationTemplateFile: string) {
69 this.index = index;
70 this.stationTemplateFile = stationTemplateFile;
71 this.connectors = new Map<number, ConnectorStatus>();
72 this.initialize();
73
74 this.stopped = false;
75 this.wsConnectionRestarted = false;
76 this.autoReconnectRetryCount = 0;
77
78 this.requests = new Map<string, CachedRequest>();
79 this.messageBuffer = new Set<string>();
80
81 this.authorizedTags = this.getAuthorizedTags();
82 }
83
84 get wsConnectionUrl(): URL {
85 return this.getSupervisionUrlOcppConfiguration() ? new URL(this.getConfigurationKey(this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl).value + '/' + this.stationInfo.chargingStationId) : this.wsConfiguredConnectionUrl;
86 }
87
88 public logPrefix(): string {
89 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
90 }
91
92 public getBootNotificationRequest(): BootNotificationRequest {
93 return this.bootNotificationRequest;
94 }
95
96 public getRandomIdTag(): string {
97 const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
98 return this.authorizedTags[index];
99 }
100
101 public hasAuthorizedTags(): boolean {
102 return !Utils.isEmptyArray(this.authorizedTags);
103 }
104
105 public getEnableStatistics(): boolean | undefined {
106 return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true;
107 }
108
109 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
110 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
111 }
112
113 public getNumberOfPhases(): number | undefined {
114 switch (this.getCurrentOutType()) {
115 case CurrentType.AC:
116 return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3;
117 case CurrentType.DC:
118 return 0;
119 }
120 }
121
122 public isWebSocketConnectionOpened(): boolean {
123 return this?.wsConnection?.readyState === OPEN;
124 }
125
126 public isInPendingState(): boolean {
127 return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING;
128 }
129
130 public isInAcceptedState(): boolean {
131 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
132 }
133
134 public isInRejectedState(): boolean {
135 return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED;
136 }
137
138 public isRegistered(): boolean {
139 return this.isInAcceptedState() || this.isInPendingState();
140 }
141
142 public isChargingStationAvailable(): boolean {
143 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
144 }
145
146 public isConnectorAvailable(id: number): boolean {
147 return this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
148 }
149
150 public getNumberOfConnectors(): number {
151 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
152 }
153
154 public getConnectorStatus(id: number): ConnectorStatus {
155 return this.connectors.get(id);
156 }
157
158 public getCurrentOutType(): CurrentType | undefined {
159 return this.stationInfo.currentOutType ?? CurrentType.AC;
160 }
161
162 public getVoltageOut(): number | undefined {
163 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
164 let defaultVoltageOut: number;
165 switch (this.getCurrentOutType()) {
166 case CurrentType.AC:
167 defaultVoltageOut = Voltage.VOLTAGE_230;
168 break;
169 case CurrentType.DC:
170 defaultVoltageOut = Voltage.VOLTAGE_400;
171 break;
172 default:
173 logger.error(errMsg);
174 throw new Error(errMsg);
175 }
176 return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut;
177 }
178
179 public getTransactionIdTag(transactionId: number): string | undefined {
180 for (const connectorId of this.connectors.keys()) {
181 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
182 return this.getConnectorStatus(connectorId).transactionIdTag;
183 }
184 }
185 }
186
187 public getOutOfOrderEndMeterValues(): boolean {
188 return this.stationInfo.outOfOrderEndMeterValues ?? false;
189 }
190
191 public getBeginEndMeterValues(): boolean {
192 return this.stationInfo.beginEndMeterValues ?? false;
193 }
194
195 public getMeteringPerTransaction(): boolean {
196 return this.stationInfo.meteringPerTransaction ?? true;
197 }
198
199 public getTransactionDataMeterValues(): boolean {
200 return this.stationInfo.transactionDataMeterValues ?? false;
201 }
202
203 public getMainVoltageMeterValues(): boolean {
204 return this.stationInfo.mainVoltageMeterValues ?? true;
205 }
206
207 public getPhaseLineToLineVoltageMeterValues(): boolean {
208 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
209 }
210
211 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
212 if (this.getMeteringPerTransaction()) {
213 for (const connectorId of this.connectors.keys()) {
214 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
215 return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
216 }
217 }
218 }
219 for (const connectorId of this.connectors.keys()) {
220 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
221 return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
222 }
223 }
224 }
225
226 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
227 if (this.getMeteringPerTransaction()) {
228 return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
229 }
230 return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
231 }
232
233 public getAuthorizeRemoteTxRequests(): boolean {
234 const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests);
235 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
236 }
237
238 public getLocalAuthListEnabled(): boolean {
239 const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled);
240 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
241 }
242
243 public restartWebSocketPing(): void {
244 // Stop WebSocket ping
245 this.stopWebSocketPing();
246 // Start WebSocket ping
247 this.startWebSocketPing();
248 }
249
250 public getSampledValueTemplate(connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
251 phase?: MeterValuePhase): SampledValueTemplate | undefined {
252 if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
253 logger.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
254 return;
255 }
256 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
257 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`);
258 return;
259 }
260 const sampledValueTemplates: SampledValueTemplate[] = this.getConnectorStatus(connectorId).MeterValues;
261 for (let index = 0; !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length; index++) {
262 if (!Constants.SUPPORTED_MEASURANDS.includes(sampledValueTemplates[index]?.measurand ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER)) {
263 logger.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
264 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
265 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
266 return sampledValueTemplates[index];
267 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
268 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
269 return sampledValueTemplates[index];
270 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
271 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
272 return sampledValueTemplates[index];
273 }
274 }
275 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
276 const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
277 logger.error(errorMsg);
278 throw new Error(errorMsg);
279 }
280 logger.debug(`${this.logPrefix()} No MeterValues for measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
281 }
282
283 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
284 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
285 }
286
287 public startHeartbeat(): void {
288 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
289 // eslint-disable-next-line @typescript-eslint/no-misused-promises
290 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
291 await this.ocppRequestService.sendHeartbeat();
292 }, this.getHeartbeatInterval());
293 logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()));
294 } else if (this.heartbeatSetInterval) {
295 logger.info(this.logPrefix() + ' Heartbeat already started every ' + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()));
296 } else {
297 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
298 }
299 }
300
301 public restartHeartbeat(): void {
302 // Stop heartbeat
303 this.stopHeartbeat();
304 // Start heartbeat
305 this.startHeartbeat();
306 }
307
308 public startMeterValues(connectorId: number, interval: number): void {
309 if (connectorId === 0) {
310 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
311 return;
312 }
313 if (!this.getConnectorStatus(connectorId)) {
314 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
315 return;
316 }
317 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
318 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
319 return;
320 } else if (this.getConnectorStatus(connectorId)?.transactionStarted && !this.getConnectorStatus(connectorId)?.transactionId) {
321 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
322 return;
323 }
324 if (interval > 0) {
325 // eslint-disable-next-line @typescript-eslint/no-misused-promises
326 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
327 await this.ocppRequestService.sendMeterValues(connectorId, this.getConnectorStatus(connectorId).transactionId, interval);
328 }, interval);
329 } else {
330 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
331 }
332 }
333
334 public start(): void {
335 if (this.getEnableStatistics()) {
336 this.performanceStatistics.start();
337 }
338 this.openWSConnection();
339 // Monitor authorization file
340 this.startAuthorizationFileMonitoring();
341 // Monitor station template file
342 this.startStationTemplateFileMonitoring();
343 // Handle WebSocket message
344 this.wsConnection.on('message', this.onMessage.bind(this));
345 // Handle WebSocket error
346 this.wsConnection.on('error', this.onError.bind(this));
347 // Handle WebSocket close
348 this.wsConnection.on('close', this.onClose.bind(this));
349 // Handle WebSocket open
350 this.wsConnection.on('open', this.onOpen.bind(this));
351 // Handle WebSocket ping
352 this.wsConnection.on('ping', this.onPing.bind(this));
353 // Handle WebSocket pong
354 this.wsConnection.on('pong', this.onPong.bind(this));
355 parentPort.postMessage({ id: ChargingStationWorkerMessageEvents.STARTED, data: { id: this.stationInfo.chargingStationId } });
356 }
357
358 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
359 // Stop message sequence
360 await this.stopMessageSequence(reason);
361 for (const connectorId of this.connectors.keys()) {
362 if (connectorId > 0) {
363 await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.UNAVAILABLE);
364 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
365 }
366 }
367 if (this.isWebSocketConnectionOpened()) {
368 this.wsConnection.close();
369 }
370 if (this.getEnableStatistics()) {
371 this.performanceStatistics.stop();
372 }
373 this.bootNotificationResponse = null;
374 parentPort.postMessage({ id: ChargingStationWorkerMessageEvents.STOPPED, data: { id: this.stationInfo.chargingStationId } });
375 this.stopped = true;
376 }
377
378 public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey | undefined {
379 return this.configuration.configurationKey.find((configElement) => {
380 if (caseInsensitive) {
381 return configElement.key.toLowerCase() === key.toLowerCase();
382 }
383 return configElement.key === key;
384 });
385 }
386
387 public addConfigurationKey(key: string | StandardParametersKey, value: string, options: { readonly?: boolean, visible?: boolean, reboot?: boolean } = { readonly: false, visible: true, reboot: false }): void {
388 const keyFound = this.getConfigurationKey(key);
389 const readonly = options.readonly;
390 const visible = options.visible;
391 const reboot = options.reboot;
392 if (!keyFound) {
393 this.configuration.configurationKey.push({
394 key,
395 readonly,
396 value,
397 visible,
398 reboot,
399 });
400 } else {
401 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound);
402 }
403 }
404
405 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
406 const keyFound = this.getConfigurationKey(key);
407 if (keyFound) {
408 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
409 this.configuration.configurationKey[keyIndex].value = value;
410 } else {
411 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value });
412 }
413 }
414
415 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
416 let cpReplaced = false;
417 if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
418 this.getConnectorStatus(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => {
419 if (chargingProfile.chargingProfileId === cp.chargingProfileId
420 || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
421 this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
422 cpReplaced = true;
423 }
424 });
425 }
426 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
427 }
428
429 public resetConnectorStatus(connectorId: number): void {
430 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
431 this.getConnectorStatus(connectorId).idTagAuthorized = false;
432 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
433 this.getConnectorStatus(connectorId).transactionStarted = false;
434 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
435 delete this.getConnectorStatus(connectorId).authorizeIdTag;
436 delete this.getConnectorStatus(connectorId).transactionId;
437 delete this.getConnectorStatus(connectorId).transactionIdTag;
438 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
439 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
440 this.stopMeterValues(connectorId);
441 }
442
443 public bufferMessage(message: string): void {
444 this.messageBuffer.add(message);
445 }
446
447 private flushMessageBuffer() {
448 if (this.messageBuffer.size > 0) {
449 this.messageBuffer.forEach((message) => {
450 // TODO: evaluate the need to track performance
451 this.wsConnection.send(message);
452 this.messageBuffer.delete(message);
453 });
454 }
455 }
456
457 private getSupervisionUrlOcppConfiguration(): boolean {
458 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
459 }
460
461 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
462 // In case of multiple instances: add instance index to charging station id
463 const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
464 const idSuffix = stationTemplate.nameSuffix ?? '';
465 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
466 }
467
468 private buildStationInfo(): ChargingStationInfo {
469 let stationTemplateFromFile: ChargingStationTemplate;
470 try {
471 // Load template file
472 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
473 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
474 fs.closeSync(fileDescriptor);
475 } catch (error) {
476 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
477 }
478 const chargingStationId = this.getChargingStationId(stationTemplateFromFile);
479 // Deprecation template keys section
480 this.warnDeprecatedTemplateKey(stationTemplateFromFile, 'supervisionUrl', chargingStationId, 'Use \'supervisionUrls\' instead');
481 this.convertDeprecatedTemplateKey(stationTemplateFromFile, 'supervisionUrl', 'supervisionUrls');
482 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
483 stationInfo.wsOptions = stationTemplateFromFile?.wsOptions ?? {};
484 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
485 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
486 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplateFromFile.power.length);
487 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
488 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
489 : stationTemplateFromFile.power[powerArrayRandomIndex];
490 } else {
491 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
492 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
493 ? stationTemplateFromFile.power * 1000
494 : stationTemplateFromFile.power;
495 }
496 delete stationInfo.power;
497 delete stationInfo.powerUnit;
498 stationInfo.chargingStationId = chargingStationId;
499 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
500 return stationInfo;
501 }
502
503 private getOcppVersion(): OCPPVersion {
504 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
505 }
506
507 private handleUnsupportedVersion(version: OCPPVersion) {
508 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
509 logger.error(errMsg);
510 throw new Error(errMsg);
511 }
512
513 private initialize(): void {
514 this.stationInfo = this.buildStationInfo();
515 this.configuration = this.getTemplateChargingStationConfiguration();
516 delete this.stationInfo.Configuration;
517 this.bootNotificationRequest = {
518 chargePointModel: this.stationInfo.chargePointModel,
519 chargePointVendor: this.stationInfo.chargePointVendor,
520 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
521 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
522 };
523 // Build connectors if needed
524 const maxConnectors = this.getMaxNumberOfConnectors();
525 if (maxConnectors <= 0) {
526 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
527 }
528 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
529 if (templateMaxConnectors <= 0) {
530 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
531 }
532 if (!this.stationInfo.Connectors[0]) {
533 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
534 }
535 // Sanity check
536 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
537 logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
538 this.stationInfo.randomConnectors = true;
539 }
540 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
541 const connectorsConfigChanged = this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
542 if (this.connectors?.size === 0 || connectorsConfigChanged) {
543 connectorsConfigChanged && (this.connectors.clear());
544 this.connectorsConfigurationHash = connectorsConfigHash;
545 // Add connector Id 0
546 let lastConnector = '0';
547 for (lastConnector in this.stationInfo.Connectors) {
548 const lastConnectorId = Utils.convertToInt(lastConnector);
549 if (lastConnectorId === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
550 this.connectors.set(lastConnectorId, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector]));
551 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
552 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
553 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
554 }
555 }
556 }
557 // Generate all connectors
558 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
559 for (let index = 1; index <= maxConnectors; index++) {
560 const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1) : index;
561 this.connectors.set(index, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId]));
562 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
563 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
564 this.getConnectorStatus(index).chargingProfiles = [];
565 }
566 }
567 }
568 }
569 // Avoid duplication of connectors related information
570 delete this.stationInfo.Connectors;
571 // Initialize transaction attributes on connectors
572 for (const connectorId of this.connectors.keys()) {
573 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
574 this.initializeConnectorStatus(connectorId);
575 }
576 }
577 this.wsConfiguredConnectionUrl = new URL(this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId);
578 switch (this.getOcppVersion()) {
579 case OCPPVersion.VERSION_16:
580 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
581 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
582 break;
583 default:
584 this.handleUnsupportedVersion(this.getOcppVersion());
585 break;
586 }
587 // OCPP parameters
588 this.initOcppParameters();
589 if (this.stationInfo.autoRegister) {
590 this.bootNotificationResponse = {
591 currentTime: new Date().toISOString(),
592 interval: this.getHeartbeatInterval() / 1000,
593 status: RegistrationStatus.ACCEPTED
594 };
595 }
596 this.stationInfo.powerDivider = this.getPowerDivider();
597 if (this.getEnableStatistics()) {
598 this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId, this.wsConnectionUrl);
599 }
600 }
601
602 private initOcppParameters(): void {
603 if (this.getSupervisionUrlOcppConfiguration() && !this.getConfigurationKey(this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl)) {
604 this.addConfigurationKey(VendorDefaultParametersKey.ConnectionUrl, this.getConfiguredSupervisionUrl().href, { reboot: true });
605 }
606 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
607 this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
608 }
609 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), { readonly: true });
610 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
611 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
612 }
613 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
614 const connectorPhaseRotation = [];
615 for (const connectorId of this.connectors.keys()) {
616 // AC/DC
617 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
618 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
619 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
620 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
621 // AC
622 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
623 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
624 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
625 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
626 }
627 }
628 this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString());
629 }
630 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
631 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
632 }
633 if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled)
634 && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) {
635 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
636 }
637 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
638 this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString());
639 }
640 }
641
642 private async onOpen(): Promise<void> {
643 logger.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
644 if (!this.isRegistered()) {
645 // Send BootNotification
646 let registrationRetryCount = 0;
647 do {
648 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
649 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
650 if (!this.isRegistered()) {
651 registrationRetryCount++;
652 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
653 }
654 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
655 }
656 if (this.isRegistered() && this.stationInfo.autoRegister) {
657 await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
658 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
659 }
660 if (this.isInAcceptedState()) {
661 await this.startMessageSequence();
662 this.stopped && (this.stopped = false);
663 if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) {
664 this.flushMessageBuffer();
665 }
666 } else if (this.isInPendingState()) {
667 // The central server shall issue a TriggerMessage to the charging station for the boot notification at the end of its configuration process
668 while (!this.isInAcceptedState()) {
669 await Utils.sleep(Constants.CHARGING_STATION_DEFAULT_START_SEQUENCE_DELAY);
670 }
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 // Start WebSocket ping
880 this.startWebSocketPing();
881 // Start heartbeat
882 this.startHeartbeat();
883 // Initialize connectors status
884 for (const connectorId of this.connectors.keys()) {
885 if (connectorId === 0) {
886 continue;
887 } else if (!this.stopped && !this.getConnectorStatus(connectorId)?.status && this.getConnectorStatus(connectorId)?.bootStatus) {
888 // Send status in template at startup
889 await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).bootStatus);
890 this.getConnectorStatus(connectorId).status = this.getConnectorStatus(connectorId).bootStatus;
891 } else if (this.stopped && this.getConnectorStatus(connectorId)?.status && this.getConnectorStatus(connectorId)?.bootStatus) {
892 // Send status in template after reset
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) {
896 // Send previous status at template reload
897 await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).status);
898 } else {
899 // Send default status
900 await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE);
901 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
902 }
903 }
904 // Start the ATG
905 this.startAutomaticTransactionGenerator();
906 }
907
908 private startAutomaticTransactionGenerator() {
909 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
910 if (!this.automaticTransactionGenerator) {
911 this.automaticTransactionGenerator = new AutomaticTransactionGenerator(this);
912 }
913 if (!this.automaticTransactionGenerator.started) {
914 this.automaticTransactionGenerator.start();
915 }
916 }
917 }
918
919 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
920 // Stop WebSocket ping
921 this.stopWebSocketPing();
922 // Stop heartbeat
923 this.stopHeartbeat();
924 // Stop the ATG
925 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
926 this.automaticTransactionGenerator &&
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 &&
1119 this.automaticTransactionGenerator.started) {
1120 this.automaticTransactionGenerator.stop();
1121 }
1122 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1123 this.autoReconnectRetryCount++;
1124 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1125 const reconnectTimeout = (reconnectDelay - 100) > 0 && reconnectDelay;
1126 logger.error(`${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`);
1127 await Utils.sleep(reconnectDelay);
1128 logger.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1129 this.openWSConnection({ ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout }, true);
1130 this.wsConnectionRestarted = true;
1131 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1132 logger.error(`${this.logPrefix()} WebSocket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1133 }
1134 }
1135
1136 private initializeConnectorStatus(connectorId: number): void {
1137 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1138 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1139 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
1140 this.getConnectorStatus(connectorId).transactionStarted = false;
1141 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
1142 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
1143 }
1144 }
1145