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