Ensure the ATG will stop on unavaible connector
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
index 5181beed404b0d8865f9c7baf307c24ed630d691..b32e794885326c6c768dbdf2857ba4d65a7e1693 100644 (file)
@@ -10,58 +10,74 @@ import logger from '../utils/Logger';
 
 export default class AutomaticTransactionGenerator {
   public started: boolean;
+  private chargingStation: ChargingStation;
+  private connectorsStartStatus: Record<number, boolean>;
   private startDate!: Date;
   private lastRunDate!: Date;
   private stopDate!: Date;
-  private chargingStation: ChargingStation;
 
   constructor(chargingStation: ChargingStation) {
     this.chargingStation = chargingStation;
+    this.connectorsStartStatus = {} as Record<number, boolean>;
+    this.stopConnectors();
     this.started = false;
   }
 
   public start(): void {
+    if (this.started) {
+      logger.error(`${this.logPrefix()} trying to start while already started`);
+      return;
+    }
+    const previousRunDuration = (this?.startDate && this?.lastRunDate) ? (this.lastRunDate.getTime() - this.startDate.getTime()) : 0;
     this.startDate = new Date();
-    this.lastRunDate = this?.lastRunDate ?? this.startDate;
+    this.lastRunDate = this.startDate;
     this.stopDate = new Date(this.startDate.getTime()
       + (this.chargingStation.stationInfo?.AutomaticTransactionGenerator?.stopAfterHours ?? Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) * 3600 * 1000
-      - (this.lastRunDate.getTime() - this.startDate.getTime()));
+      - previousRunDuration);
+    this.startConnectors();
     this.started = true;
-    for (const connector in this.chargingStation.connectors) {
-      if (Utils.convertToInt(connector) > 0) {
-        // Avoid hogging the event loop with a busy loop
-        setImmediate(() => {
-          this.startOnConnector(Utils.convertToInt(connector)).catch(() => { /* This is intentional */ });
-        });
-      }
-    }
     logger.info(this.logPrefix() + ' started and will run for ' + Utils.formatDurationMilliSeconds(this.stopDate.getTime() - this.startDate.getTime()));
   }
 
-  public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
+  public stop(): void {
     if (!this.started) {
       logger.error(`${this.logPrefix()} trying to stop while not started`);
       return;
     }
+    this.stopConnectors();
+    this.started = false;
     logger.info(`${this.logPrefix()} over and lasted for ${Utils.formatDurationMilliSeconds(this.lastRunDate.getTime() - this.startDate.getTime())}. Stopping all transactions`);
+  }
+
+  private startConnectors(): void {
     for (const connector in this.chargingStation.connectors) {
-      const transactionId = this.chargingStation.getConnector(Utils.convertToInt(connector)).transactionId;
-      if (this.chargingStation.getConnector(Utils.convertToInt(connector)).transactionStarted) {
-        logger.info(this.logPrefix(Utils.convertToInt(connector)) + ' over. Stop transaction ' + transactionId.toString());
-        await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId, this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
-          this.chargingStation.getTransactionIdTag(transactionId), reason);
+      const connectorId = Utils.convertToInt(connector);
+      if (connectorId > 0) {
+        // Avoid hogging the event loop with a busy loop
+        setImmediate(() => {
+          this.startConnector(connectorId).catch(() => { /* This is intentional */ });
+        });
+      }
+    }
+  }
+
+  private stopConnectors(): void {
+    for (const connector in this.chargingStation.connectors) {
+      const connectorId = Utils.convertToInt(connector);
+      if (connectorId > 0) {
+        this.stopConnector(connectorId);
       }
     }
-    this.started = false;
   }
 
-  private async startOnConnector(connectorId: number): Promise<void> {
+  private async startConnector(connectorId: number): Promise<void> {
     logger.info(this.logPrefix(connectorId) + ' started on connector');
-    let transactionSkip = 0;
-    let totalTransactionSkip = 0;
-    while (this.started) {
+    let skippedTransactions = 0;
+    let skippedTransactionsTotal = 0;
+    this.connectorsStartStatus[connectorId] = true;
+    while (this.connectorsStartStatus[connectorId]) {
       if ((new Date()) > this.stopDate) {
-        await this.stop();
+        this.stop();
         break;
       }
       if (!this.chargingStation.isRegistered()) {
@@ -70,11 +86,12 @@ export default class AutomaticTransactionGenerator {
       }
       if (!this.chargingStation.isChargingStationAvailable()) {
         logger.info(this.logPrefix(connectorId) + ' Entered in transaction loop while the charging station is unavailable');
-        await this.stop();
+        this.stop();
         break;
       }
       if (!this.chargingStation.isConnectorAvailable(connectorId)) {
         logger.info(`${this.logPrefix(connectorId)} Entered in transaction loop while the connector ${connectorId} is unavailable, stop it`);
+        this.stopConnector(connectorId);
         break;
       }
       if (!this.chargingStation?.ocppRequestService) {
@@ -83,13 +100,13 @@ export default class AutomaticTransactionGenerator {
           await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
         } while (!this.chargingStation?.ocppRequestService);
       }
-      const wait = Utils.getRandomInt(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDelayBetweenTwoTransactions,
+      const wait = Utils.getRandomInteger(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDelayBetweenTwoTransactions,
         this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDelayBetweenTwoTransactions) * 1000;
       logger.info(this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait));
       await Utils.sleep(wait);
       const start = Utils.secureRandom();
       if (start < this.chargingStation.stationInfo.AutomaticTransactionGenerator.probabilityOfStart) {
-        transactionSkip = 0;
+        skippedTransactions = 0;
         // Start transaction
         const startResponse = await this.startTransaction(connectorId);
         if (startResponse?.idTagInfo?.status !== AuthorizationStatus.ACCEPTED) {
@@ -97,63 +114,74 @@ export default class AutomaticTransactionGenerator {
           await Utils.sleep(Constants.CHARGING_STATION_ATG_WAIT_TIME);
         } else {
           // Wait until end of transaction
-          const waitTrxEnd = Utils.getRandomInt(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDuration,
+          const waitTrxEnd = Utils.getRandomInteger(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDuration,
             this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDuration) * 1000;
           logger.info(this.logPrefix(connectorId) + ' transaction ' + this.chargingStation.getConnector(connectorId).transactionId.toString() + ' will stop in ' + Utils.formatDurationMilliSeconds(waitTrxEnd));
           await Utils.sleep(waitTrxEnd);
           // Stop transaction
-          if (this.chargingStation.getConnector(connectorId)?.transactionStarted) {
-            logger.info(this.logPrefix(connectorId) + ' stop transaction ' + this.chargingStation.getConnector(connectorId).transactionId.toString());
-            await this.stopTransaction(connectorId);
-          }
+          logger.info(this.logPrefix(connectorId) + ' stop transaction ' + this.chargingStation.getConnector(connectorId).transactionId.toString());
+          await this.stopTransaction(connectorId);
         }
       } else {
-        transactionSkip++;
-        totalTransactionSkip++;
-        logger.info(this.logPrefix(connectorId) + ' skipped transaction ' + transactionSkip.toString() + '/' + totalTransactionSkip.toString());
+        skippedTransactions++;
+        skippedTransactionsTotal++;
+        logger.info(this.logPrefix(connectorId) + ' skipped transaction ' + skippedTransactions.toString() + '/' + skippedTransactionsTotal.toString());
       }
       this.lastRunDate = new Date();
     }
+    await this.stopTransaction(connectorId);
     logger.info(this.logPrefix(connectorId) + ' stopped on connector');
   }
 
+  private stopConnector(connectorId: number): void {
+    this.connectorsStartStatus[connectorId] = false;
+  }
+
   private async startTransaction(connectorId: number): Promise<StartTransactionResponse | AuthorizeResponse> {
     const measureId = 'StartTransaction with ATG';
     const beginId = PerformanceStatistics.beginMeasure(measureId);
     let startResponse: StartTransactionResponse;
     if (this.chargingStation.hasAuthorizedTags()) {
-      const tagId = this.chargingStation.getRandomTagId();
+      const idTag = this.chargingStation.getRandomIdTag();
       if (this.chargingStation.getAutomaticTransactionGeneratorRequireAuthorize()) {
-        // Authorize tagId
-        const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(connectorId, tagId);
+        // Authorize idTag
+        const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(connectorId, idTag);
         if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
-          logger.info(this.logPrefix(connectorId) + ' start transaction for tagID ' + tagId);
+          logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
           // Start transaction
-          startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, tagId);
+          startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, idTag);
           PerformanceStatistics.endMeasure(measureId, beginId);
           return startResponse;
         }
         PerformanceStatistics.endMeasure(measureId, beginId);
         return authorizeResponse;
       }
-      logger.info(this.logPrefix(connectorId) + ' start transaction for tagID ' + tagId);
+      logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
       // Start transaction
-      startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, tagId);
+      startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, idTag);
       PerformanceStatistics.endMeasure(measureId, beginId);
       return startResponse;
     }
-    logger.info(this.logPrefix(connectorId) + ' start transaction without a tagID');
+    logger.info(this.logPrefix(connectorId) + ' start transaction without an idTag');
     startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId);
     PerformanceStatistics.endMeasure(measureId, beginId);
     return startResponse;
   }
 
-  private async stopTransaction(connectorId: number): Promise<StopTransactionResponse> {
+  private async stopTransaction(connectorId: number, reason: StopTransactionReason = StopTransactionReason.NONE): Promise<StopTransactionResponse> {
     const measureId = 'StopTransaction with ATG';
     const beginId = PerformanceStatistics.beginMeasure(measureId);
-    const transactionId = this.chargingStation.getConnector(connectorId).transactionId;
-    const stopResponse = this.chargingStation.ocppRequestService.sendStopTransaction(transactionId,
-      this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId), this.chargingStation.getTransactionIdTag(transactionId));
+    let transactionId = 0;
+    let stopResponse: StopTransactionResponse;
+    if (this.chargingStation.getConnector(connectorId)?.transactionStarted) {
+      transactionId = this.chargingStation.getConnector(connectorId).transactionId;
+      stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId,
+        this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
+        this.chargingStation.getTransactionIdTag(transactionId),
+        reason);
+    } else {
+      logger.warn(`${this.logPrefix(connectorId)} trying to stop a not started transaction${transactionId ? ' ' + transactionId.toString() : ''}`);
+    }
     PerformanceStatistics.endMeasure(measureId, beginId);
     return stopResponse;
   }