Improve vscode debug setup.
[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 {
eb87fe87 226 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
c0560973
JB
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
77f00f84 322 public addToMessageQueue(message: string): void {
3ba2381e
JB
323 let dups = false;
324 // Handle dups in buffer
325 for (const bufferedMessage of this.messageQueue) {
326 // Same message
327 if (message === bufferedMessage) {
328 dups = true;
329 break;
330 }
331 }
332 if (!dups) {
333 // Buffer message
334 this.messageQueue.push(message);
335 }
336 }
337
77f00f84
JB
338 private flushMessageQueue() {
339 if (!Utils.isEmptyArray(this.messageQueue)) {
340 this.messageQueue.forEach((message, index) => {
341 this.messageQueue.splice(index, 1);
342 this.wsConnection.send(message);
343 });
344 }
345 }
346
c0560973 347 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
ef6076c1
J
348 // In case of multiple instances: add instance index to charging station id
349 let instanceIndex = process.env.CF_INSTANCE_INDEX ? process.env.CF_INSTANCE_INDEX : 0;
350 instanceIndex = instanceIndex > 0 ? instanceIndex : '';
5fdab605 351 const idSuffix = stationTemplate.nameSuffix ? stationTemplate.nameSuffix : '';
ad2f27c3 352 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
5ad8570f
JB
353 }
354
c0560973 355 private buildStationInfo(): ChargingStationInfo {
9ac86a7e 356 let stationTemplateFromFile: ChargingStationTemplate;
5ad8570f
JB
357 try {
358 // Load template file
ad2f27c3 359 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
9ac86a7e 360 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
5ad8570f
JB
361 fs.closeSync(fileDescriptor);
362 } catch (error) {
ad2f27c3 363 logger.error('Template file ' + this.stationTemplateFile + ' loading error: %j', error);
cdd9fed5 364 throw error;
5ad8570f 365 }
9ac86a7e 366 const stationInfo: ChargingStationInfo = stationTemplateFromFile || {} as ChargingStationInfo;
0a60c33c 367 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
9ac86a7e
JB
368 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
369 stationInfo.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
5ad8570f 370 } else {
9ac86a7e 371 stationInfo.maxPower = stationTemplateFromFile.power as number;
5ad8570f 372 }
c0560973 373 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
9ac86a7e
JB
374 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
375 return stationInfo;
5ad8570f
JB
376 }
377
c0560973
JB
378 private getOCPPVersion(): OCPPVersion {
379 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
380 }
381
382 private handleUnsupportedVersion(version: OCPPVersion) {
383 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
384 logger.error(errMsg);
385 throw new Error(errMsg);
386 }
387
388 private initialize(): void {
389 this.stationInfo = this.buildStationInfo();
ad2f27c3
JB
390 this.bootNotificationRequest = {
391 chargePointModel: this.stationInfo.chargePointModel,
392 chargePointVendor: this.stationInfo.chargePointVendor,
393 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
394 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
2e6f5966 395 };
c0560973
JB
396 this.configuration = this.getTemplateChargingStationConfiguration();
397 this.supervisionUrl = this.getSupervisionURL();
ad2f27c3 398 this.wsConnectionUrl = this.supervisionUrl + '/' + this.stationInfo.chargingStationId;
0a60c33c 399 // Build connectors if needed
c0560973 400 const maxConnectors = this.getMaxNumberOfConnectors();
6ecb15e4 401 if (maxConnectors <= 0) {
c0560973 402 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
7abfea5f 403 }
c0560973 404 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
7abfea5f 405 if (templateMaxConnectors <= 0) {
c0560973 406 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
593cf3f9 407 }
ad2f27c3 408 if (!this.stationInfo.Connectors[0]) {
c0560973 409 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
7abfea5f
JB
410 }
411 // Sanity check
ad2f27c3 412 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
c0560973 413 logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
ad2f27c3 414 this.stationInfo.randomConnectors = true;
6ecb15e4 415 }
ad2f27c3 416 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
de1f5008 417 // FIXME: Handle shrinking the number of connectors
ad2f27c3
JB
418 if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
419 this.connectorsConfigurationHash = connectorsConfigHash;
7abfea5f 420 // Add connector Id 0
6af9012e 421 let lastConnector = '0';
ad2f27c3 422 for (lastConnector in this.stationInfo.Connectors) {
c0560973 423 if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
ad2f27c3
JB
424 this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
425 this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
418106c8
JB
426 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
427 this.connectors[lastConnector].chargingProfiles = [];
428 }
0a60c33c
JB
429 }
430 }
0a60c33c 431 // Generate all connectors
ad2f27c3 432 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
7abfea5f 433 for (let index = 1; index <= maxConnectors; index++) {
ad2f27c3
JB
434 const randConnectorID = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
435 this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorID]);
436 this.connectors[index].availability = AvailabilityType.OPERATIVE;
418106c8
JB
437 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
438 this.connectors[index].chargingProfiles = [];
439 }
7abfea5f 440 }
0a60c33c
JB
441 }
442 }
d4a73fb7 443 // Avoid duplication of connectors related information
ad2f27c3 444 delete this.stationInfo.Connectors;
0a60c33c 445 // Initialize transaction attributes on connectors
ad2f27c3 446 for (const connector in this.connectors) {
593cf3f9 447 if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
c0560973 448 this.initTransactionOnConnector(Utils.convertToInt(connector));
0a60c33c
JB
449 }
450 }
c0560973
JB
451 switch (this.getOCPPVersion()) {
452 case OCPPVersion.VERSION_16:
453 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
454 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
455 break;
456 default:
457 this.handleUnsupportedVersion(this.getOCPPVersion());
458 break;
459 }
7abfea5f 460 // OCPP parameters
c0560973
JB
461 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true);
462 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
463 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
7abfea5f 464 }
c0560973 465 this.stationInfo.powerDivider = this.getPowerDivider();
8bce55bf 466 if (this.getEnableStatistics()) {
418106c8 467 this.statistics = new Statistics(this.stationInfo.chargingStationId);
ad2f27c3 468 this.performanceObserver = new PerformanceObserver((list) => {
8bce55bf 469 const entry = list.getEntries()[0];
ad2f27c3
JB
470 this.statistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
471 this.performanceObserver.disconnect();
8bce55bf
JB
472 });
473 }
7dde0b73
JB
474 }
475
c0560973
JB
476 private async onOpen(): Promise<void> {
477 logger.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
478 if (!this.isRegistered()) {
479 // Send BootNotification
480 let registrationRetryCount = 0;
481 do {
482 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel, this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
483 if (!this.isRegistered()) {
484 registrationRetryCount++;
485 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
486 }
487 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
c7db4718
JB
488 }
489 if (this.isRegistered()) {
c0560973 490 await this.startMessageSequence();
3ba49ba9 491 this.hasStopped && (this.hasStopped = false);
c0560973 492 if (this.hasSocketRestarted && this.isWebSocketOpen()) {
77f00f84 493 this.flushMessageQueue();
2e6f5966
JB
494 }
495 } else {
c0560973 496 logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
2e6f5966 497 }
c0560973
JB
498 this.autoReconnectRetryCount = 0;
499 this.hasSocketRestarted = false;
2e6f5966
JB
500 }
501
c0560973
JB
502 private async onClose(closeEvent): Promise<void> {
503 switch (closeEvent) {
504 case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close
505 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
506 logger.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
507 this.autoReconnectRetryCount = 0;
508 break;
509 default: // Abnormal close
510 logger.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
511 await this.reconnect(closeEvent);
512 break;
513 }
2e6f5966
JB
514 }
515
c0560973
JB
516 private async onMessage(messageEvent: MessageEvent): Promise<void> {
517 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
518 let responseCallback: (payload?: Record<string, unknown> | string, requestPayload?: Record<string, unknown>) => void;
519 let rejectCallback: (error: OCPPError) => void;
520 let requestPayload: Record<string, unknown>;
521 let errMsg: string;
522 try {
523 // Parse the message
524 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest;
5ad8570f 525
c0560973
JB
526 // Check the Type of message
527 switch (messageType) {
528 // Incoming Message
529 case MessageType.CALL_MESSAGE:
530 if (this.getEnableStatistics()) {
531 this.statistics.addMessage(commandName, messageType);
532 }
533 // Process the call
534 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
535 break;
536 // Outcome Message
537 case MessageType.CALL_RESULT_MESSAGE:
538 // Respond
539 if (Utils.isIterable(this.requests[messageId])) {
540 [responseCallback, , requestPayload] = this.requests[messageId];
541 } else {
542 throw new Error(`Response request for message id ${messageId} is not iterable`);
543 }
544 if (!responseCallback) {
545 // Error
546 throw new Error(`Response request for unknown message id ${messageId}`);
547 }
548 delete this.requests[messageId];
549 responseCallback(commandName, requestPayload);
550 break;
551 // Error Message
552 case MessageType.CALL_ERROR_MESSAGE:
553 if (!this.requests[messageId]) {
554 // Error
555 throw new Error(`Error request for unknown message id ${messageId}`);
556 }
557 if (Utils.isIterable(this.requests[messageId])) {
558 [, rejectCallback] = this.requests[messageId];
559 } else {
560 throw new Error(`Error request for message id ${messageId} is not iterable`);
561 }
562 delete this.requests[messageId];
563 rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails));
564 break;
565 // Error
566 default:
567 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
568 logger.error(errMsg);
569 throw new Error(errMsg);
570 }
571 } catch (error) {
572 // Log
573 logger.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent, error, this.requests[messageId]);
574 // Send error
575 messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
576 }
2328be1e
JB
577 }
578
c0560973
JB
579 private onPing(): void {
580 logger.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
581 }
582
583 private onPong(): void {
584 logger.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
585 }
586
587 private async onError(errorEvent): Promise<void> {
588 logger.error(this.logPrefix() + ' Socket error: %j', errorEvent);
589 // pragma switch (errorEvent.code) {
590 // case 'ECONNREFUSED':
591 // await this._reconnect(errorEvent);
592 // break;
593 // }
594 }
595
596 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
597 return this.stationInfo.Configuration ? this.stationInfo.Configuration : {} as ChargingStationConfiguration;
598 }
599
600 private getAuthorizationFile(): string {
601 return this.stationInfo.authorizationFile && this.stationInfo.authorizationFile;
602 }
603
604 private getAuthorizedTags(): string[] {
605 let authorizedTags: string[] = [];
606 const authorizationFile = this.getAuthorizationFile();
607 if (authorizationFile) {
608 try {
609 // Load authorization file
610 const fileDescriptor = fs.openSync(authorizationFile, 'r');
611 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
612 fs.closeSync(fileDescriptor);
613 } catch (error) {
614 logger.error(this.logPrefix() + ' Authorization file ' + authorizationFile + ' loading error: %j', error);
615 throw error;
616 }
617 } else {
618 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
8c4da341 619 }
c0560973
JB
620 return authorizedTags;
621 }
622
623 private getUseConnectorId0(): boolean {
624 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
8bce55bf
JB
625 }
626
c0560973 627 private getNumberOfRunningTransactions(): number {
6ecb15e4 628 let trxCount = 0;
ad2f27c3 629 for (const connector in this.connectors) {
593cf3f9 630 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
6ecb15e4
JB
631 trxCount++;
632 }
633 }
634 return trxCount;
635 }
636
1f761b9a 637 // 0 for disabling
c0560973 638 private getConnectionTimeout(): number {
ad2f27c3
JB
639 if (!Utils.isUndefined(this.stationInfo.connectionTimeout)) {
640 return this.stationInfo.connectionTimeout;
3574dfd3
JB
641 }
642 if (!Utils.isUndefined(Configuration.getConnectionTimeout())) {
643 return Configuration.getConnectionTimeout();
644 }
645 return 30;
646 }
647
1f761b9a 648 // -1 for unlimited, 0 for disabling
c0560973 649 private getAutoReconnectMaxRetries(): number {
ad2f27c3
JB
650 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
651 return this.stationInfo.autoReconnectMaxRetries;
3574dfd3
JB
652 }
653 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
654 return Configuration.getAutoReconnectMaxRetries();
655 }
656 return -1;
657 }
658
ec977daf 659 // 0 for disabling
c0560973 660 private getRegistrationMaxRetries(): number {
ad2f27c3
JB
661 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
662 return this.stationInfo.registrationMaxRetries;
32a1eb7a
JB
663 }
664 return -1;
665 }
666
c0560973
JB
667 private getPowerDivider(): number {
668 let powerDivider = this.getNumberOfConnectors();
ad2f27c3 669 if (this.stationInfo.powerSharedByConnectors) {
c0560973 670 powerDivider = this.getNumberOfRunningTransactions();
6ecb15e4
JB
671 }
672 return powerDivider;
673 }
674
c0560973 675 private getTemplateMaxNumberOfConnectors(): number {
ad2f27c3 676 return Object.keys(this.stationInfo.Connectors).length;
7abfea5f
JB
677 }
678
c0560973 679 private getMaxNumberOfConnectors(): number {
5ad8570f 680 let maxConnectors = 0;
ad2f27c3
JB
681 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
682 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
6ecb15e4 683 // Distribute evenly the number of connectors
ad2f27c3
JB
684 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
685 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
686 maxConnectors = this.stationInfo.numberOfConnectors as number;
488fd3a7 687 } else {
c0560973 688 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
5ad8570f
JB
689 }
690 return maxConnectors;
2e6f5966
JB
691 }
692
c0560973 693 private getNumberOfConnectors(): number {
ad2f27c3 694 return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length;
6ecb15e4
JB
695 }
696
c0560973 697 private async startMessageSequence(): Promise<void> {
136c90ba 698 // Start WebSocket ping
c0560973 699 this.startWebSocketPing();
5ad8570f 700 // Start heartbeat
c0560973 701 this.startHeartbeat();
0a60c33c 702 // Initialize connectors status
ad2f27c3 703 for (const connector in this.connectors) {
593cf3f9
JB
704 if (Utils.convertToInt(connector) === 0) {
705 continue;
ad2f27c3 706 } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
136c90ba 707 // Send status in template at startup
c0560973
JB
708 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
709 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
ad2f27c3 710 } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
136c90ba 711 // Send status in template after reset
c0560973
JB
712 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
713 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
ad2f27c3 714 } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) {
136c90ba 715 // Send previous status at template reload
c0560973 716 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
5ad8570f 717 } else {
136c90ba 718 // Send default status
c0560973
JB
719 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
720 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE;
5ad8570f
JB
721 }
722 }
0a60c33c 723 // Start the ATG
ad2f27c3
JB
724 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
725 if (!this.automaticTransactionGeneration) {
726 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
5ad8570f 727 }
ad2f27c3 728 if (this.automaticTransactionGeneration.timeToStop) {
e268356b 729 await this.automaticTransactionGeneration.start();
5ad8570f
JB
730 }
731 }
8bce55bf 732 if (this.getEnableStatistics()) {
ad2f27c3 733 this.statistics.start();
8bce55bf 734 }
5ad8570f
JB
735 }
736
c0560973 737 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
136c90ba 738 // Stop WebSocket ping
c0560973 739 this.stopWebSocketPing();
79411696 740 // Stop heartbeat
c0560973 741 this.stopHeartbeat();
79411696 742 // Stop the ATG
ad2f27c3
JB
743 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
744 this.automaticTransactionGeneration &&
745 !this.automaticTransactionGeneration.timeToStop) {
746 await this.automaticTransactionGeneration.stop(reason);
79411696 747 } else {
ad2f27c3 748 for (const connector in this.connectors) {
593cf3f9 749 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
c0560973
JB
750 const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
751 await this.ocppRequestService.sendStopTransaction(transactionId, this.getTransactionMeterStop(transactionId), this.getTransactionIdTag(transactionId), reason);
79411696
JB
752 }
753 }
754 }
755 }
756
c0560973
JB
757 private startWebSocketPing(): void {
758 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval) ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value) : 0;
ad2f27c3
JB
759 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
760 this.webSocketPingSetInterval = setInterval(() => {
c0560973 761 if (this.isWebSocketOpen()) {
ad2f27c3 762 this.wsConnection.ping((): void => { });
136c90ba
JB
763 }
764 }, webSocketPingInterval * 1000);
c0560973 765 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
ad2f27c3 766 } else if (this.webSocketPingSetInterval) {
c0560973 767 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
136c90ba 768 } else {
c0560973 769 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
136c90ba
JB
770 }
771 }
772
c0560973 773 private stopWebSocketPing(): void {
ad2f27c3
JB
774 if (this.webSocketPingSetInterval) {
775 clearInterval(this.webSocketPingSetInterval);
776 this.webSocketPingSetInterval = null;
136c90ba
JB
777 }
778 }
779
c0560973
JB
780 private getSupervisionURL(): string {
781 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs());
782 let indexUrl = 0;
783 if (!Utils.isEmptyArray(supervisionUrls)) {
784 if (Configuration.getDistributeStationsToTenantsEqually()) {
785 indexUrl = this.index % supervisionUrls.length;
786 } else {
787 // Get a random url
788 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
789 }
790 return supervisionUrls[indexUrl];
791 }
792 return supervisionUrls as string;
136c90ba
JB
793 }
794
c0560973
JB
795 private getHeartbeatInterval(): number {
796 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
797 if (HeartbeatInterval) {
798 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
799 }
800 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
801 if (HeartBeatInterval) {
802 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
0a60c33c
JB
803 }
804 }
805
c0560973 806 private stopHeartbeat(): void {
ad2f27c3
JB
807 if (this.heartbeatSetInterval) {
808 clearInterval(this.heartbeatSetInterval);
809 this.heartbeatSetInterval = null;
7dde0b73 810 }
5ad8570f
JB
811 }
812
c0560973
JB
813 private openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void {
814 if (Utils.isUndefined(options)) {
815 options = {} as WebSocket.ClientOptions;
816 }
817 if (Utils.isUndefined(options.handshakeTimeout)) {
818 options.handshakeTimeout = this.getConnectionTimeout() * 1000;
819 }
820 if (this.isWebSocketOpen() && forceCloseOpened) {
821 this.wsConnection.close();
822 }
823 let protocol;
824 switch (this.getOCPPVersion()) {
825 case OCPPVersion.VERSION_16:
826 protocol = 'ocpp' + OCPPVersion.VERSION_16;
827 break;
828 default:
829 this.handleUnsupportedVersion(this.getOCPPVersion());
830 break;
831 }
832 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
833 logger.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl);
136c90ba
JB
834 }
835
c0560973
JB
836 private startAuthorizationFileMonitoring(): void {
837 fs.watch(this.getAuthorizationFile()).on('change', (e) => {
5ad8570f 838 try {
c0560973 839 logger.debug(this.logPrefix() + ' Authorization file ' + this.getAuthorizationFile() + ' have changed, reload');
adeb9b56 840 // Initialize authorizedTags
c0560973 841 this.authorizedTags = this.getAuthorizedTags();
5ad8570f 842 } catch (error) {
c0560973 843 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
5ad8570f
JB
844 }
845 });
846 }
847
c0560973 848 private startStationTemplateFileMonitoring(): void {
71623267 849 // eslint-disable-next-line @typescript-eslint/no-misused-promises
e268356b 850 fs.watch(this.stationTemplateFile).on('change', async (e): Promise<void> => {
5ad8570f 851 try {
c0560973 852 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
5ad8570f 853 // Initialize
c0560973 854 this.initialize();
ef6076c1 855 // Stop the ATG
ad2f27c3
JB
856 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
857 this.automaticTransactionGeneration) {
e268356b 858 await this.automaticTransactionGeneration.stop();
79411696 859 }
ef6076c1 860 // Start the ATG
ad2f27c3
JB
861 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
862 if (!this.automaticTransactionGeneration) {
863 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
ef6076c1 864 }
ad2f27c3 865 if (this.automaticTransactionGeneration.timeToStop) {
e268356b 866 await this.automaticTransactionGeneration.start();
ef6076c1
J
867 }
868 }
136c90ba 869 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
5ad8570f 870 } catch (error) {
c0560973 871 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
5ad8570f
JB
872 }
873 });
874 }
875
c0560973
JB
876 private getReconnectExponentialDelay(): boolean {
877 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
5ad8570f
JB
878 }
879
c0560973 880 private async reconnect(error): Promise<void> {
136c90ba 881 // Stop heartbeat
c0560973 882 this.stopHeartbeat();
5ad8570f 883 // Stop the ATG if needed
ad2f27c3
JB
884 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
885 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
886 this.automaticTransactionGeneration &&
887 !this.automaticTransactionGeneration.timeToStop) {
888 this.automaticTransactionGeneration.stop().catch(() => { });
889 }
c0560973 890 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
ad2f27c3 891 this.autoReconnectRetryCount++;
c0560973
JB
892 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
893 logger.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
032d6efc 894 await Utils.sleep(reconnectDelay);
c0560973
JB
895 logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
896 this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
ad2f27c3 897 this.hasSocketRestarted = true;
c0560973
JB
898 } else if (this.getAutoReconnectMaxRetries() !== -1) {
899 logger.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
5ad8570f
JB
900 }
901 }
902
c0560973 903 private initTransactionOnConnector(connectorId: number): void {
8bce55bf
JB
904 this.getConnector(connectorId).transactionStarted = false;
905 this.getConnector(connectorId).transactionId = null;
906 this.getConnector(connectorId).idTag = null;
907 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1;
0a60c33c 908 }
7dde0b73
JB
909}
910