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