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