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