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