Consistently use idTag for RFID tag
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
index 756f5b80a6adc752d38a7e98ba20f4b1b03eb088..b27e15648792e527836a5f10868a776739789ae7 100644 (file)
@@ -9,20 +9,25 @@ import Utils from '../utils/Utils';
 import logger from '../utils/Logger';
 
 export default class AutomaticTransactionGenerator {
-  public timeToStop: boolean;
+  public started: boolean;
   private startDate!: Date;
+  private lastRunDate!: Date;
   private stopDate!: Date;
   private chargingStation: ChargingStation;
 
   constructor(chargingStation: ChargingStation) {
     this.chargingStation = chargingStation;
-    this.timeToStop = true;
+    this.started = false;
   }
 
   public start(): void {
+    const previousRunDuration = (this?.startDate && this?.lastRunDate) ? (this.lastRunDate.getTime() - this.startDate.getTime()) : 0;
     this.startDate = new Date();
-    this.stopDate = new Date(this.startDate.getTime() + (this.chargingStation.stationInfo?.AutomaticTransactionGenerator?.stopAfterHours ?? Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) * 3600 * 1000);
-    this.timeToStop = false;
+    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
+      - previousRunDuration);
+    this.started = true;
     for (const connector in this.chargingStation.connectors) {
       if (Utils.convertToInt(connector) > 0) {
         // Avoid hogging the event loop with a busy loop
@@ -31,29 +36,25 @@ export default class AutomaticTransactionGenerator {
         });
       }
     }
-    logger.info(this.logPrefix() + ' started and will run for ' + Utils.milliSecondsToHHMMSS(this.stopDate.getTime() - this.startDate.getTime()));
+    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> {
-    logger.info(this.logPrefix() + ' over. Stopping all transactions');
-    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);
-      }
+  public stop(): void {
+    if (!this.started) {
+      logger.error(`${this.logPrefix()} trying to stop while not started`);
+      return;
     }
-    this.timeToStop = true;
+    this.started = false;
+    logger.info(`${this.logPrefix()} over and lasted for ${Utils.formatDurationMilliSeconds(this.lastRunDate.getTime() - this.startDate.getTime())}. Stopping all transactions`);
   }
 
   private async startOnConnector(connectorId: number): Promise<void> {
     logger.info(this.logPrefix(connectorId) + ' started on connector');
-    let transactionSkip = 0;
-    let totalTransactionSkip = 0;
-    while (!this.timeToStop) {
+    let skippedTransactions = 0;
+    let skippedTransactionsTotal = 0;
+    while (this.started) {
       if ((new Date()) > this.stopDate) {
-        await this.stop();
+        this.stop();
         break;
       }
       if (!this.chargingStation.isRegistered()) {
@@ -62,7 +63,7 @@ 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)) {
@@ -77,11 +78,11 @@ export default class AutomaticTransactionGenerator {
       }
       const wait = Utils.getRandomInt(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDelayBetweenTwoTransactions,
         this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDelayBetweenTwoTransactions) * 1000;
-      logger.info(this.logPrefix(connectorId) + ' waiting for ' + Utils.milliSecondsToHHMMSS(wait));
+      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) {
@@ -91,20 +92,20 @@ export default class AutomaticTransactionGenerator {
           // Wait until end of transaction
           const waitTrxEnd = Utils.getRandomInt(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.milliSecondsToHHMMSS(waitTrxEnd));
+          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');
   }
 
@@ -113,38 +114,46 @@ export default class AutomaticTransactionGenerator {
     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 a 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;
   }