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