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