Fix OCPP request handler arguments usage in the inter-workers
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
index 232ad2cd4533ce68ac79e05b676599cf4eeafd42..60760be136ff773cc047092a46f5df4e151bfaf0 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`);
     }
@@ -442,4 +453,12 @@ export default class AutomaticTransactionGenerator extends AsyncResource {
       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;
+  }
 }