Rename types definition files for the sake of namespace consitency.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
CommitLineData
efa43e52 1import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
e118beaa 2import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
84d4e562 3import ChargingStationTemplate, { PowerOutType, VoltageOut } from '../types/ChargingStationTemplate';
10570d97 4import Connectors, { Connector } from '../types/Connectors';
6af9012e 5import { PerformanceObserver, performance } from 'perf_hooks';
c0560973 6import Requests, { AvailabilityType, BootNotificationRequest, IncomingRequest, IncomingRequestCommand } from '../types/ocpp/Requests';
136c90ba 7import WebSocket, { MessageEvent } from 'ws';
3f40bc9c 8
6af9012e 9import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
c0560973
JB
10import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
11import { ChargingProfile } from '../types/ocpp/ChargingProfile';
9ac86a7e 12import ChargingStationInfo from '../types/ChargingStationInfo';
6af9012e 13import Configuration from '../utils/Configuration';
63b48f77 14import Constants from '../utils/Constants';
d2a64eb5 15import { MessageType } from '../types/ocpp/MessageType';
c0560973
JB
16import { MeterValueMeasurand } from '../types/ocpp/MeterValues';
17import OCPP16IncomingRequestService from './ocpp/1.6/OCCP16IncomingRequestService';
18import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
19import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
63b48f77 20import OCPPError from './OcppError';
c0560973
JB
21import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
22import OCPPRequestService from './ocpp/OCPPRequestService';
23import { OCPPVersion } from '../types/ocpp/OCPPVersion';
24import { StandardParametersKey } from '../types/ocpp/Configuration';
6af9012e 25import Statistics from '../utils/Statistics';
c0560973 26import { StopTransactionReason } from '../types/ocpp/Transaction';
6af9012e 27import Utils from '../utils/Utils';
32a1eb7a 28import { WebSocketCloseEventStatusCode } from '../types/WebSocket';
3f40bc9c
JB
29import crypto from 'crypto';
30import fs from 'fs';
6af9012e 31import logger from '../utils/Logger';
3f40bc9c
JB
32
33export default class ChargingStation {
c0560973
JB
34 public stationTemplateFile: string;
35 public authorizedTags: string[];
ad2f27c3
JB
36 public stationInfo: ChargingStationInfo;
37 public connectors: Connectors;
c0560973
JB
38 public configuration: ChargingStationConfiguration;
39 public hasStopped: boolean;
40 public wsConnection: WebSocket;
41 public requests: Requests;
42 public messageQueue: string[];
ad2f27c3 43 public statistics: Statistics;
c0560973
JB
44 public heartbeatSetInterval: NodeJS.Timeout;
45 public ocppIncomingRequestService: OCPPIncomingRequestService;
46 public ocppRequestService: OCPPRequestService;
ad2f27c3 47 private index: number;
ad2f27c3
JB
48 private bootNotificationRequest: BootNotificationRequest;
49 private bootNotificationResponse: BootNotificationResponse;
ad2f27c3
JB
50 private connectorsConfigurationHash: string;
51 private supervisionUrl: string;
52 private wsConnectionUrl: string;
ad2f27c3
JB
53 private hasSocketRestarted: boolean;
54 private autoReconnectRetryCount: number;
ad2f27c3 55 private automaticTransactionGeneration: AutomaticTransactionGenerator;
ad2f27c3 56 private performanceObserver: PerformanceObserver;
c0560973 57 private webSocketPingSetInterval: NodeJS.Timeout;
6af9012e
JB
58
59 constructor(index: number, stationTemplateFile: string) {
ad2f27c3
JB
60 this.index = index;
61 this.stationTemplateFile = stationTemplateFile;
62 this.connectors = {} as Connectors;
c0560973 63 this.initialize();
2e6f5966 64
ad2f27c3
JB
65 this.hasStopped = false;
66 this.hasSocketRestarted = false;
67 this.autoReconnectRetryCount = 0;
2e6f5966 68
ad2f27c3
JB
69 this.requests = {} as Requests;
70 this.messageQueue = [] as string[];
2e6f5966 71
c0560973
JB
72 this.authorizedTags = this.getAuthorizedTags();
73 }
74
75 public logPrefix(): string {
76 return Utils.logPrefix(` ${this.stationInfo.chargingStationId}:`);
77 }
78
79 public getRandomTagId(): string {
80 const index = Math.floor(Math.random() * this.authorizedTags.length);
81 return this.authorizedTags[index];
82 }
83
84 public hasAuthorizedTags(): boolean {
85 return !Utils.isEmptyArray(this.authorizedTags);
86 }
87
88 public getEnableStatistics(): boolean {
89 return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true;
90 }
91
92 public getNumberOfPhases(): number {
93 switch (this.getPowerOutType()) {
94 case PowerOutType.AC:
95 return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3;
96 case PowerOutType.DC:
97 return 0;
98 }
99 }
100
101 public isWebSocketOpen(): boolean {
102 return this.wsConnection?.readyState === WebSocket.OPEN;
103 }
104
105 public isRegistered(): boolean {
106 return this.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
107 }
108
109 public isChargingStationAvailable(): boolean {
110 return this.getConnector(0).availability === AvailabilityType.OPERATIVE;
111 }
112
113 public isConnectorAvailable(id: number): boolean {
114 return this.getConnector(id).availability === AvailabilityType.OPERATIVE;
115 }
116
117 public getConnector(id: number): Connector {
118 return this.connectors[id];
119 }
120
121 public getPowerOutType(): PowerOutType {
122 return !Utils.isUndefined(this.stationInfo.powerOutType) ? this.stationInfo.powerOutType : PowerOutType.AC;
123 }
124
125 public getVoltageOut(): number {
126 const errMsg = `${this.logPrefix()} Unknown ${this.getPowerOutType()} powerOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
127 let defaultVoltageOut: number;
128 switch (this.getPowerOutType()) {
129 case PowerOutType.AC:
130 defaultVoltageOut = VoltageOut.VOLTAGE_230;
131 break;
132 case PowerOutType.DC:
133 defaultVoltageOut = VoltageOut.VOLTAGE_400;
134 break;
135 default:
136 logger.error(errMsg);
137 throw Error(errMsg);
138 }
139 return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut;
140 }
141
142 public getTransactionIdTag(transactionId: number): string {
143 for (const connector in this.connectors) {
144 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
145 return this.getConnector(Utils.convertToInt(connector)).idTag;
146 }
147 }
148 }
149
150 public getTransactionMeterStop(transactionId: number): number {
151 for (const connector in this.connectors) {
152 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
153 return this.getConnector(Utils.convertToInt(connector)).lastEnergyActiveImportRegisterValue;
154 }
155 }
156 }
157
158 public getAuthorizeRemoteTxRequests(): boolean {
159 const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests);
160 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
161 }
162
163 public getLocalAuthListEnabled(): boolean {
164 const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled);
165 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
166 }
167
168 public restartWebSocketPing(): void {
169 // Stop WebSocket ping
170 this.stopWebSocketPing();
171 // Start WebSocket ping
172 this.startWebSocketPing();
173 }
174
175 public startHeartbeat(): void {
176 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
71623267
JB
177 // eslint-disable-next-line @typescript-eslint/no-misused-promises
178 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
c0560973
JB
179 await this.ocppRequestService.sendHeartbeat();
180 }, this.getHeartbeatInterval());
181 logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
182 } else if (this.heartbeatSetInterval) {
183 logger.info(this.logPrefix() + ' Heartbeat every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) + ' already started');
184 } else {
185 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
186 }
187 }
188
189 public restartHeartbeat(): void {
190 // Stop heartbeat
191 this.stopHeartbeat();
192 // Start heartbeat
193 this.startHeartbeat();
194 }
195
196 public startMeterValues(connectorId: number, interval: number): void {
197 if (connectorId === 0) {
198 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
199 return;
200 }
201 if (!this.getConnector(connectorId)) {
202 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
203 return;
204 }
205 if (!this.getConnector(connectorId)?.transactionStarted) {
206 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
207 return;
208 } else if (this.getConnector(connectorId)?.transactionStarted && !this.getConnector(connectorId)?.transactionId) {
209 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
210 return;
211 }
212 if (interval > 0) {
71623267
JB
213 // eslint-disable-next-line @typescript-eslint/no-misused-promises
214 this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
c0560973
JB
215 if (this.getEnableStatistics()) {
216 const sendMeterValues = performance.timerify(this.ocppRequestService.sendMeterValues);
217 this.performanceObserver.observe({
218 entryTypes: ['function'],
219 });
220 await sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
221 } else {
222 await this.ocppRequestService.sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
223 }
224 }, interval);
225 } else {
226 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`);
227 }
228 }
229
230 public start(): void {
231 this.openWSConnection();
232 // Monitor authorization file
233 this.startAuthorizationFileMonitoring();
234 // Monitor station template file
235 this.startStationTemplateFileMonitoring();
236 // Handle Socket incoming messages
237 this.wsConnection.on('message', this.onMessage.bind(this));
238 // Handle Socket error
239 this.wsConnection.on('error', this.onError.bind(this));
240 // Handle Socket close
241 this.wsConnection.on('close', this.onClose.bind(this));
242 // Handle Socket opening connection
243 this.wsConnection.on('open', this.onOpen.bind(this));
244 // Handle Socket ping
245 this.wsConnection.on('ping', this.onPing.bind(this));
246 // Handle Socket pong
247 this.wsConnection.on('pong', this.onPong.bind(this));
248 }
249
250 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
251 // Stop message sequence
252 await this.stopMessageSequence(reason);
253 for (const connector in this.connectors) {
254 if (Utils.convertToInt(connector) > 0) {
255 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE);
256 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.UNAVAILABLE;
257 }
258 }
259 if (this.isWebSocketOpen()) {
260 this.wsConnection.close();
261 }
262 this.bootNotificationResponse = null;
263 this.hasStopped = true;
264 }
265
266 public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey {
267 const configurationKey: ConfigurationKey = this.configuration.configurationKey.find((configElement) => {
268 if (caseInsensitive) {
269 return configElement.key.toLowerCase() === key.toLowerCase();
270 }
271 return configElement.key === key;
272 });
273 return configurationKey;
274 }
275
276 public addConfigurationKey(key: string | StandardParametersKey, value: string, readonly = false, visible = true, reboot = false): void {
277 const keyFound = this.getConfigurationKey(key);
278 if (!keyFound) {
279 this.configuration.configurationKey.push({
280 key,
281 readonly,
282 value,
283 visible,
284 reboot,
285 });
286 } else {
287 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound);
288 }
289 }
290
291 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
292 const keyFound = this.getConfigurationKey(key);
293 if (keyFound) {
294 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
295 this.configuration.configurationKey[keyIndex].value = value;
296 } else {
297 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value });
298 }
299 }
300
301 public setChargingProfile(connectorId: number, cp: ChargingProfile): boolean {
302 if (!Utils.isEmptyArray(this.getConnector(connectorId).chargingProfiles)) {
303 this.getConnector(connectorId).chargingProfiles.forEach((chargingProfile: ChargingProfile, index: number) => {
304 if (chargingProfile.chargingProfileId === cp.chargingProfileId
305 || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
306 this.getConnector(connectorId).chargingProfiles[index] = cp;
307 return true;
308 }
309 });
310 }
311 this.getConnector(connectorId).chargingProfiles.push(cp);
312 return true;
313 }
314
315 public resetTransactionOnConnector(connectorId: number): void {
316 this.initTransactionOnConnector(connectorId);
317 if (this.getConnector(connectorId)?.transactionSetInterval) {
318 clearInterval(this.getConnector(connectorId).transactionSetInterval);
319 }
2e6f5966
JB
320 }
321
c0560973 322 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
ef6076c1
J
323 // In case of multiple instances: add instance index to charging station id
324 let instanceIndex = process.env.CF_INSTANCE_INDEX ? process.env.CF_INSTANCE_INDEX : 0;
325 instanceIndex = instanceIndex > 0 ? instanceIndex : '';
5fdab605 326 const idSuffix = stationTemplate.nameSuffix ? stationTemplate.nameSuffix : '';
ad2f27c3 327 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
5ad8570f
JB
328 }
329
c0560973 330 private buildStationInfo(): ChargingStationInfo {
9ac86a7e 331 let stationTemplateFromFile: ChargingStationTemplate;
5ad8570f
JB
332 try {
333 // Load template file
ad2f27c3 334 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
9ac86a7e 335 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
5ad8570f
JB
336 fs.closeSync(fileDescriptor);
337 } catch (error) {
ad2f27c3 338 logger.error('Template file ' + this.stationTemplateFile + ' loading error: %j', error);
cdd9fed5 339 throw error;
5ad8570f 340 }
9ac86a7e 341 const stationInfo: ChargingStationInfo = stationTemplateFromFile || {} as ChargingStationInfo;
0a60c33c 342 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
9ac86a7e
JB
343 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
344 stationInfo.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
5ad8570f 345 } else {
9ac86a7e 346 stationInfo.maxPower = stationTemplateFromFile.power as number;
5ad8570f 347 }
c0560973 348 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
9ac86a7e
JB
349 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
350 return stationInfo;
5ad8570f
JB
351 }
352
c0560973
JB
353 private getOCPPVersion(): OCPPVersion {
354 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
355 }
356
357 private handleUnsupportedVersion(version: OCPPVersion) {
358 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
359 logger.error(errMsg);
360 throw new Error(errMsg);
361 }
362
363 private initialize(): void {
364 this.stationInfo = this.buildStationInfo();
ad2f27c3
JB
365 this.bootNotificationRequest = {
366 chargePointModel: this.stationInfo.chargePointModel,
367 chargePointVendor: this.stationInfo.chargePointVendor,
368 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
369 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
2e6f5966 370 };
c0560973
JB
371 this.configuration = this.getTemplateChargingStationConfiguration();
372 this.supervisionUrl = this.getSupervisionURL();
ad2f27c3 373 this.wsConnectionUrl = this.supervisionUrl + '/' + this.stationInfo.chargingStationId;
0a60c33c 374 // Build connectors if needed
c0560973 375 const maxConnectors = this.getMaxNumberOfConnectors();
6ecb15e4 376 if (maxConnectors <= 0) {
c0560973 377 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
7abfea5f 378 }
c0560973 379 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
7abfea5f 380 if (templateMaxConnectors <= 0) {
c0560973 381 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
593cf3f9 382 }
ad2f27c3 383 if (!this.stationInfo.Connectors[0]) {
c0560973 384 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
7abfea5f
JB
385 }
386 // Sanity check
ad2f27c3 387 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
c0560973 388 logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
ad2f27c3 389 this.stationInfo.randomConnectors = true;
6ecb15e4 390 }
ad2f27c3 391 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
de1f5008 392 // FIXME: Handle shrinking the number of connectors
ad2f27c3
JB
393 if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
394 this.connectorsConfigurationHash = connectorsConfigHash;
7abfea5f 395 // Add connector Id 0
6af9012e 396 let lastConnector = '0';
ad2f27c3 397 for (lastConnector in this.stationInfo.Connectors) {
c0560973 398 if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
ad2f27c3
JB
399 this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
400 this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
418106c8
JB
401 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
402 this.connectors[lastConnector].chargingProfiles = [];
403 }
0a60c33c
JB
404 }
405 }
0a60c33c 406 // Generate all connectors
ad2f27c3 407 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
7abfea5f 408 for (let index = 1; index <= maxConnectors; index++) {
ad2f27c3
JB
409 const randConnectorID = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
410 this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorID]);
411 this.connectors[index].availability = AvailabilityType.OPERATIVE;
418106c8
JB
412 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
413 this.connectors[index].chargingProfiles = [];
414 }
7abfea5f 415 }
0a60c33c
JB
416 }
417 }
d4a73fb7 418 // Avoid duplication of connectors related information
ad2f27c3 419 delete this.stationInfo.Connectors;
0a60c33c 420 // Initialize transaction attributes on connectors
ad2f27c3 421 for (const connector in this.connectors) {
593cf3f9 422 if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
c0560973 423 this.initTransactionOnConnector(Utils.convertToInt(connector));
0a60c33c
JB
424 }
425 }
c0560973
JB
426 switch (this.getOCPPVersion()) {
427 case OCPPVersion.VERSION_16:
428 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
429 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
430 break;
431 default:
432 this.handleUnsupportedVersion(this.getOCPPVersion());
433 break;
434 }
7abfea5f 435 // OCPP parameters
c0560973
JB
436 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true);
437 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
438 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
7abfea5f 439 }
c0560973 440 this.stationInfo.powerDivider = this.getPowerDivider();
8bce55bf 441 if (this.getEnableStatistics()) {
418106c8 442 this.statistics = new Statistics(this.stationInfo.chargingStationId);
ad2f27c3 443 this.performanceObserver = new PerformanceObserver((list) => {
8bce55bf 444 const entry = list.getEntries()[0];
ad2f27c3
JB
445 this.statistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
446 this.performanceObserver.disconnect();
8bce55bf
JB
447 });
448 }
7dde0b73
JB
449 }
450
c0560973
JB
451 private async onOpen(): Promise<void> {
452 logger.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
453 if (!this.isRegistered()) {
454 // Send BootNotification
455 let registrationRetryCount = 0;
456 do {
457 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel, this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
458 if (!this.isRegistered()) {
459 registrationRetryCount++;
460 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
461 }
462 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
594dc437 463 } else if (this.isRegistered()) {
c0560973 464 await this.startMessageSequence();
3ba49ba9 465 this.hasStopped && (this.hasStopped = false);
c0560973
JB
466 if (this.hasSocketRestarted && this.isWebSocketOpen()) {
467 if (!Utils.isEmptyArray(this.messageQueue)) {
468 this.messageQueue.forEach((message, index) => {
469 this.messageQueue.splice(index, 1);
470 this.wsConnection.send(message);
471 });
472 }
2e6f5966
JB
473 }
474 } else {
c0560973 475 logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
2e6f5966 476 }
c0560973
JB
477 this.autoReconnectRetryCount = 0;
478 this.hasSocketRestarted = false;
2e6f5966
JB
479 }
480
c0560973
JB
481 private async onClose(closeEvent): Promise<void> {
482 switch (closeEvent) {
483 case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close
484 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
485 logger.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
486 this.autoReconnectRetryCount = 0;
487 break;
488 default: // Abnormal close
489 logger.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
490 await this.reconnect(closeEvent);
491 break;
492 }
2e6f5966
JB
493 }
494
c0560973
JB
495 private async onMessage(messageEvent: MessageEvent): Promise<void> {
496 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
497 let responseCallback: (payload?: Record<string, unknown> | string, requestPayload?: Record<string, unknown>) => void;
498 let rejectCallback: (error: OCPPError) => void;
499 let requestPayload: Record<string, unknown>;
500 let errMsg: string;
501 try {
502 // Parse the message
503 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest;
5ad8570f 504
c0560973
JB
505 // Check the Type of message
506 switch (messageType) {
507 // Incoming Message
508 case MessageType.CALL_MESSAGE:
509 if (this.getEnableStatistics()) {
510 this.statistics.addMessage(commandName, messageType);
511 }
512 // Process the call
513 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
514 break;
515 // Outcome Message
516 case MessageType.CALL_RESULT_MESSAGE:
517 // Respond
518 if (Utils.isIterable(this.requests[messageId])) {
519 [responseCallback, , requestPayload] = this.requests[messageId];
520 } else {
521 throw new Error(`Response request for message id ${messageId} is not iterable`);
522 }
523 if (!responseCallback) {
524 // Error
525 throw new Error(`Response request for unknown message id ${messageId}`);
526 }
527 delete this.requests[messageId];
528 responseCallback(commandName, requestPayload);
529 break;
530 // Error Message
531 case MessageType.CALL_ERROR_MESSAGE:
532 if (!this.requests[messageId]) {
533 // Error
534 throw new Error(`Error request for unknown message id ${messageId}`);
535 }
536 if (Utils.isIterable(this.requests[messageId])) {
537 [, rejectCallback] = this.requests[messageId];
538 } else {
539 throw new Error(`Error request for message id ${messageId} is not iterable`);
540 }
541 delete this.requests[messageId];
542 rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails));
543 break;
544 // Error
545 default:
546 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
547 logger.error(errMsg);
548 throw new Error(errMsg);
549 }
550 } catch (error) {
551 // Log
552 logger.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent, error, this.requests[messageId]);
553 // Send error
554 messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
555 }
2328be1e
JB
556 }
557
c0560973
JB
558 private onPing(): void {
559 logger.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
560 }
561
562 private onPong(): void {
563 logger.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
564 }
565
566 private async onError(errorEvent): Promise<void> {
567 logger.error(this.logPrefix() + ' Socket error: %j', errorEvent);
568 // pragma switch (errorEvent.code) {
569 // case 'ECONNREFUSED':
570 // await this._reconnect(errorEvent);
571 // break;
572 // }
573 }
574
575 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
576 return this.stationInfo.Configuration ? this.stationInfo.Configuration : {} as ChargingStationConfiguration;
577 }
578
579 private getAuthorizationFile(): string {
580 return this.stationInfo.authorizationFile && this.stationInfo.authorizationFile;
581 }
582
583 private getAuthorizedTags(): string[] {
584 let authorizedTags: string[] = [];
585 const authorizationFile = this.getAuthorizationFile();
586 if (authorizationFile) {
587 try {
588 // Load authorization file
589 const fileDescriptor = fs.openSync(authorizationFile, 'r');
590 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
591 fs.closeSync(fileDescriptor);
592 } catch (error) {
593 logger.error(this.logPrefix() + ' Authorization file ' + authorizationFile + ' loading error: %j', error);
594 throw error;
595 }
596 } else {
597 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
8c4da341 598 }
c0560973
JB
599 return authorizedTags;
600 }
601
602 private getUseConnectorId0(): boolean {
603 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
8bce55bf
JB
604 }
605
c0560973 606 private getNumberOfRunningTransactions(): number {
6ecb15e4 607 let trxCount = 0;
ad2f27c3 608 for (const connector in this.connectors) {
593cf3f9 609 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
6ecb15e4
JB
610 trxCount++;
611 }
612 }
613 return trxCount;
614 }
615
1f761b9a 616 // 0 for disabling
c0560973 617 private getConnectionTimeout(): number {
ad2f27c3
JB
618 if (!Utils.isUndefined(this.stationInfo.connectionTimeout)) {
619 return this.stationInfo.connectionTimeout;
3574dfd3
JB
620 }
621 if (!Utils.isUndefined(Configuration.getConnectionTimeout())) {
622 return Configuration.getConnectionTimeout();
623 }
624 return 30;
625 }
626
1f761b9a 627 // -1 for unlimited, 0 for disabling
c0560973 628 private getAutoReconnectMaxRetries(): number {
ad2f27c3
JB
629 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
630 return this.stationInfo.autoReconnectMaxRetries;
3574dfd3
JB
631 }
632 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
633 return Configuration.getAutoReconnectMaxRetries();
634 }
635 return -1;
636 }
637
ec977daf 638 // 0 for disabling
c0560973 639 private getRegistrationMaxRetries(): number {
ad2f27c3
JB
640 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
641 return this.stationInfo.registrationMaxRetries;
32a1eb7a
JB
642 }
643 return -1;
644 }
645
c0560973
JB
646 private getPowerDivider(): number {
647 let powerDivider = this.getNumberOfConnectors();
ad2f27c3 648 if (this.stationInfo.powerSharedByConnectors) {
c0560973 649 powerDivider = this.getNumberOfRunningTransactions();
6ecb15e4
JB
650 }
651 return powerDivider;
652 }
653
c0560973 654 private getTemplateMaxNumberOfConnectors(): number {
ad2f27c3 655 return Object.keys(this.stationInfo.Connectors).length;
7abfea5f
JB
656 }
657
c0560973 658 private getMaxNumberOfConnectors(): number {
5ad8570f 659 let maxConnectors = 0;
ad2f27c3
JB
660 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
661 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
6ecb15e4 662 // Distribute evenly the number of connectors
ad2f27c3
JB
663 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
664 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
665 maxConnectors = this.stationInfo.numberOfConnectors as number;
488fd3a7 666 } else {
c0560973 667 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
5ad8570f
JB
668 }
669 return maxConnectors;
2e6f5966
JB
670 }
671
c0560973 672 private getNumberOfConnectors(): number {
ad2f27c3 673 return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length;
6ecb15e4
JB
674 }
675
c0560973 676 private async startMessageSequence(): Promise<void> {
136c90ba 677 // Start WebSocket ping
c0560973 678 this.startWebSocketPing();
5ad8570f 679 // Start heartbeat
c0560973 680 this.startHeartbeat();
0a60c33c 681 // Initialize connectors status
ad2f27c3 682 for (const connector in this.connectors) {
593cf3f9
JB
683 if (Utils.convertToInt(connector) === 0) {
684 continue;
ad2f27c3 685 } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
136c90ba 686 // Send status in template at startup
c0560973
JB
687 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
688 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
ad2f27c3 689 } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
136c90ba 690 // Send status in template after reset
c0560973
JB
691 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
692 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
ad2f27c3 693 } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) {
136c90ba 694 // Send previous status at template reload
c0560973 695 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
5ad8570f 696 } else {
136c90ba 697 // Send default status
c0560973
JB
698 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
699 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE;
5ad8570f
JB
700 }
701 }
0a60c33c 702 // Start the ATG
ad2f27c3
JB
703 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
704 if (!this.automaticTransactionGeneration) {
705 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
5ad8570f 706 }
ad2f27c3 707 if (this.automaticTransactionGeneration.timeToStop) {
e268356b 708 await this.automaticTransactionGeneration.start();
5ad8570f
JB
709 }
710 }
8bce55bf 711 if (this.getEnableStatistics()) {
ad2f27c3 712 this.statistics.start();
8bce55bf 713 }
5ad8570f
JB
714 }
715
c0560973 716 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
136c90ba 717 // Stop WebSocket ping
c0560973 718 this.stopWebSocketPing();
79411696 719 // Stop heartbeat
c0560973 720 this.stopHeartbeat();
79411696 721 // Stop the ATG
ad2f27c3
JB
722 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
723 this.automaticTransactionGeneration &&
724 !this.automaticTransactionGeneration.timeToStop) {
725 await this.automaticTransactionGeneration.stop(reason);
79411696 726 } else {
ad2f27c3 727 for (const connector in this.connectors) {
593cf3f9 728 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
c0560973
JB
729 const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
730 await this.ocppRequestService.sendStopTransaction(transactionId, this.getTransactionMeterStop(transactionId), this.getTransactionIdTag(transactionId), reason);
79411696
JB
731 }
732 }
733 }
734 }
735
c0560973
JB
736 private startWebSocketPing(): void {
737 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval) ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value) : 0;
ad2f27c3
JB
738 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
739 this.webSocketPingSetInterval = setInterval(() => {
c0560973 740 if (this.isWebSocketOpen()) {
ad2f27c3 741 this.wsConnection.ping((): void => { });
136c90ba
JB
742 }
743 }, webSocketPingInterval * 1000);
c0560973 744 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
ad2f27c3 745 } else if (this.webSocketPingSetInterval) {
c0560973 746 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
136c90ba 747 } else {
c0560973 748 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
136c90ba
JB
749 }
750 }
751
c0560973 752 private stopWebSocketPing(): void {
ad2f27c3
JB
753 if (this.webSocketPingSetInterval) {
754 clearInterval(this.webSocketPingSetInterval);
755 this.webSocketPingSetInterval = null;
136c90ba
JB
756 }
757 }
758
c0560973
JB
759 private getSupervisionURL(): string {
760 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs());
761 let indexUrl = 0;
762 if (!Utils.isEmptyArray(supervisionUrls)) {
763 if (Configuration.getDistributeStationsToTenantsEqually()) {
764 indexUrl = this.index % supervisionUrls.length;
765 } else {
766 // Get a random url
767 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
768 }
769 return supervisionUrls[indexUrl];
770 }
771 return supervisionUrls as string;
136c90ba
JB
772 }
773
c0560973
JB
774 private getHeartbeatInterval(): number {
775 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
776 if (HeartbeatInterval) {
777 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
778 }
779 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
780 if (HeartBeatInterval) {
781 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
0a60c33c
JB
782 }
783 }
784
c0560973 785 private stopHeartbeat(): void {
ad2f27c3
JB
786 if (this.heartbeatSetInterval) {
787 clearInterval(this.heartbeatSetInterval);
788 this.heartbeatSetInterval = null;
7dde0b73 789 }
5ad8570f
JB
790 }
791
c0560973
JB
792 private openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void {
793 if (Utils.isUndefined(options)) {
794 options = {} as WebSocket.ClientOptions;
795 }
796 if (Utils.isUndefined(options.handshakeTimeout)) {
797 options.handshakeTimeout = this.getConnectionTimeout() * 1000;
798 }
799 if (this.isWebSocketOpen() && forceCloseOpened) {
800 this.wsConnection.close();
801 }
802 let protocol;
803 switch (this.getOCPPVersion()) {
804 case OCPPVersion.VERSION_16:
805 protocol = 'ocpp' + OCPPVersion.VERSION_16;
806 break;
807 default:
808 this.handleUnsupportedVersion(this.getOCPPVersion());
809 break;
810 }
811 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
812 logger.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl);
136c90ba
JB
813 }
814
c0560973
JB
815 private startAuthorizationFileMonitoring(): void {
816 fs.watch(this.getAuthorizationFile()).on('change', (e) => {
5ad8570f 817 try {
c0560973 818 logger.debug(this.logPrefix() + ' Authorization file ' + this.getAuthorizationFile() + ' have changed, reload');
adeb9b56 819 // Initialize authorizedTags
c0560973 820 this.authorizedTags = this.getAuthorizedTags();
5ad8570f 821 } catch (error) {
c0560973 822 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
5ad8570f
JB
823 }
824 });
825 }
826
c0560973 827 private startStationTemplateFileMonitoring(): void {
71623267 828 // eslint-disable-next-line @typescript-eslint/no-misused-promises
e268356b 829 fs.watch(this.stationTemplateFile).on('change', async (e): Promise<void> => {
5ad8570f 830 try {
c0560973 831 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
5ad8570f 832 // Initialize
c0560973 833 this.initialize();
ef6076c1 834 // Stop the ATG
ad2f27c3
JB
835 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
836 this.automaticTransactionGeneration) {
e268356b 837 await this.automaticTransactionGeneration.stop();
79411696 838 }
ef6076c1 839 // Start the ATG
ad2f27c3
JB
840 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
841 if (!this.automaticTransactionGeneration) {
842 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
ef6076c1 843 }
ad2f27c3 844 if (this.automaticTransactionGeneration.timeToStop) {
e268356b 845 await this.automaticTransactionGeneration.start();
ef6076c1
J
846 }
847 }
136c90ba 848 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
5ad8570f 849 } catch (error) {
c0560973 850 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
5ad8570f
JB
851 }
852 });
853 }
854
c0560973
JB
855 private getReconnectExponentialDelay(): boolean {
856 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
5ad8570f
JB
857 }
858
c0560973 859 private async reconnect(error): Promise<void> {
136c90ba 860 // Stop heartbeat
c0560973 861 this.stopHeartbeat();
5ad8570f 862 // Stop the ATG if needed
ad2f27c3
JB
863 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
864 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
865 this.automaticTransactionGeneration &&
866 !this.automaticTransactionGeneration.timeToStop) {
867 this.automaticTransactionGeneration.stop().catch(() => { });
868 }
c0560973 869 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
ad2f27c3 870 this.autoReconnectRetryCount++;
c0560973
JB
871 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
872 logger.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
032d6efc 873 await Utils.sleep(reconnectDelay);
c0560973
JB
874 logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
875 this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
ad2f27c3 876 this.hasSocketRestarted = true;
c0560973
JB
877 } else if (this.getAutoReconnectMaxRetries() !== -1) {
878 logger.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
5ad8570f
JB
879 }
880 }
881
c0560973 882 private initTransactionOnConnector(connectorId: number): void {
8bce55bf
JB
883 this.getConnector(connectorId).transactionStarted = false;
884 this.getConnector(connectorId).transactionId = null;
885 this.getConnector(connectorId).idTag = null;
886 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1;
0a60c33c 887 }
7dde0b73
JB
888}
889