Switch log messages to string literal
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
index fb6e9d28c1f92ee7766104dd4559a79eeb94725e..3a1c6786f9b3c9fcf5cc93f522dd541b23c1e69e 100644 (file)
@@ -1,7 +1,9 @@
-// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
+// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
 
 import { AsyncResource } from 'async_hooks';
 
+import type ChargingStation from './ChargingStation';
+import { ChargingStationUtils } from './ChargingStationUtils';
 import BaseError from '../exception/BaseError';
 import PerformanceStatistics from '../performance/PerformanceStatistics';
 import {
@@ -22,8 +24,6 @@ import {
 import Constants from '../utils/Constants';
 import logger from '../utils/Logger';
 import Utils from '../utils/Utils';
-import type ChargingStation from './ChargingStation';
-import { ChargingStationUtils } from './ChargingStationUtils';
 
 const moduleName = 'AutomaticTransactionGenerator';
 
@@ -69,6 +69,9 @@ export default class AutomaticTransactionGenerator extends AsyncResource {
   }
 
   public start(): void {
+    if (this.checkChargingStation() === false) {
+      return;
+    }
     if (this.started === true) {
       logger.warn(`${this.logPrefix()} is already started`);
       return;
@@ -87,16 +90,24 @@ export default class AutomaticTransactionGenerator extends AsyncResource {
   }
 
   public startConnector(connectorId: number): void {
+    if (this.checkChargingStation(connectorId) === false) {
+      return;
+    }
     if (this.connectorsStatus.has(connectorId) === false) {
       logger.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
       throw new BaseError(`Connector ${connectorId} does not exist`);
     }
     if (this.connectorsStatus.get(connectorId)?.start === false) {
       this.runInAsyncScope(
-        this.internalStartConnector.bind(this) as (this: this, ...args: any[]) => unknown,
+        this.internalStartConnector.bind(this) as (
+          this: AutomaticTransactionGenerator,
+          ...args: any[]
+        ) => Promise<void>,
         this,
         connectorId
-      );
+      ).catch(() => {
+        /* This is intentional */
+      });
     } else if (this.connectorsStatus.get(connectorId)?.start === true) {
       logger.warn(`${this.logPrefix(connectorId)} is already started on connector`);
     }
@@ -140,35 +151,37 @@ export default class AutomaticTransactionGenerator extends AsyncResource {
   private async internalStartConnector(connectorId: number): Promise<void> {
     this.setStartConnectorStatus(connectorId);
     logger.info(
-      this.logPrefix(connectorId) +
-        ' started on connector and will run for ' +
-        Utils.formatDurationMilliSeconds(
-          this.connectorsStatus.get(connectorId).stopDate.getTime() -
-            this.connectorsStatus.get(connectorId).startDate.getTime()
-        )
+      `${this.logPrefix(
+        connectorId
+      )} started on connector and will run for ${Utils.formatDurationMilliSeconds(
+        this.connectorsStatus.get(connectorId).stopDate.getTime() -
+          this.connectorsStatus.get(connectorId).startDate.getTime()
+      )}`
     );
     while (this.connectorsStatus.get(connectorId).start === true) {
       if (new Date() > this.connectorsStatus.get(connectorId).stopDate) {
         this.stopConnector(connectorId);
         break;
       }
-      if (!this.chargingStation.isInAcceptedState()) {
+      if (this.chargingStation.isInAcceptedState() === false) {
         logger.error(
-          this.logPrefix(connectorId) +
-            ' entered in transaction loop while the charging station is not in accepted state'
+          `${this.logPrefix(
+            connectorId
+          )} entered in transaction loop while the charging station is not in accepted state`
         );
         this.stopConnector(connectorId);
         break;
       }
-      if (!this.chargingStation.isChargingStationAvailable()) {
+      if (this.chargingStation.isChargingStationAvailable() === false) {
         logger.info(
-          this.logPrefix(connectorId) +
-            ' entered in transaction loop while the charging station is unavailable'
+          `${this.logPrefix(
+            connectorId
+          )} entered in transaction loop while the charging station is unavailable`
         );
         this.stopConnector(connectorId);
         break;
       }
-      if (!this.chargingStation.isConnectorAvailable(connectorId)) {
+      if (this.chargingStation.isConnectorAvailable(connectorId) === false) {
         logger.info(
           `${this.logPrefix(
             connectorId
@@ -193,7 +206,7 @@ export default class AutomaticTransactionGenerator extends AsyncResource {
           this.configuration.minDelayBetweenTwoTransactions
         ) * 1000;
       logger.info(
-        this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait)
+        `${this.logPrefix(connectorId)} waiting for ${Utils.formatDurationMilliSeconds(wait)}`
       );
       await Utils.sleep(wait);
       const start = Utils.secureRandom();
@@ -207,18 +220,18 @@ export default class AutomaticTransactionGenerator extends AsyncResource {
             Utils.getRandomInteger(this.configuration.maxDuration, this.configuration.minDuration) *
             1000;
           logger.info(
-            this.logPrefix(connectorId) +
-              ' transaction ' +
-              this.chargingStation.getConnectorStatus(connectorId).transactionId.toString() +
-              ' started and will stop in ' +
-              Utils.formatDurationMilliSeconds(waitTrxEnd)
+            `${this.logPrefix(connectorId)} transaction ${this.chargingStation
+              .getConnectorStatus(connectorId)
+              .transactionId.toString()} started and will stop in ${Utils.formatDurationMilliSeconds(
+              waitTrxEnd
+            )}`
           );
           await Utils.sleep(waitTrxEnd);
           // Stop transaction
           logger.info(
-            this.logPrefix(connectorId) +
-              ' stop transaction ' +
-              this.chargingStation.getConnectorStatus(connectorId).transactionId.toString()
+            `${this.logPrefix(connectorId)} stop transaction ${this.chargingStation
+              .getConnectorStatus(connectorId)
+              .transactionId.toString()}`
           );
           await this.stopTransaction(connectorId);
         }
@@ -226,24 +239,23 @@ export default class AutomaticTransactionGenerator extends AsyncResource {
         this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions++;
         this.connectorsStatus.get(connectorId).skippedTransactions++;
         logger.info(
-          this.logPrefix(connectorId) +
-            ' skipped consecutively ' +
-            this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions.toString() +
-            '/' +
-            this.connectorsStatus.get(connectorId).skippedTransactions.toString() +
-            ' transaction(s)'
+          `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
+            .get(connectorId)
+            .skippedConsecutiveTransactions.toString()}/${this.connectorsStatus
+            .get(connectorId)
+            .skippedTransactions.toString()} transaction(s)`
         );
       }
       this.connectorsStatus.get(connectorId).lastRunDate = new Date();
     }
     this.connectorsStatus.get(connectorId).stoppedDate = new Date();
     logger.info(
-      this.logPrefix(connectorId) +
-        ' stopped on connector and lasted for ' +
-        Utils.formatDurationMilliSeconds(
-          this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
-            this.connectorsStatus.get(connectorId).startDate.getTime()
-        )
+      `${this.logPrefix(
+        connectorId
+      )} stopped on connector and lasted for ${Utils.formatDurationMilliSeconds(
+        this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
+          this.connectorsStatus.get(connectorId).startDate.getTime()
+      )}`
     );
     logger.debug(
       `${this.logPrefix(connectorId)} connector status: %j`,
@@ -375,7 +387,7 @@ export default class AutomaticTransactionGenerator extends AsyncResource {
       const transactionId = this.chargingStation.getConnectorStatus(connectorId).transactionId;
       logger.warn(
         `${this.logPrefix(connectorId)} stopping a not started transaction${
-          transactionId ? ' ' + transactionId.toString() : ''
+          transactionId ? ` ${transactionId.toString()}` : ''
         }`
       );
     }
@@ -438,8 +450,16 @@ export default class AutomaticTransactionGenerator extends AsyncResource {
     if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
       this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests++;
     } else {
-      logger.warn(this.logPrefix(connectorId) + ' start transaction rejected');
+      logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
       this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests++;
     }
   }
+
+  private checkChargingStation(connectorId?: number): boolean {
+    if (this.chargingStation.started === false && this.chargingStation.starting === false) {
+      logger.warn(`${this.logPrefix(connectorId)} charging station is stopped, cannot proceed`);
+      return false;
+    }
+    return true;
+  }
 }