README.md: document added UI protocol features
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
index a8bd79ac06d846ac6d3f0313a25de57c234856a3..bf28e55bfdcbc9e4894996f1b383d47a3e0af0b8 100644 (file)
@@ -1,5 +1,12 @@
 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
 
+import PerformanceStatistics from '../performance/PerformanceStatistics';
+import type {
+  AutomaticTransactionGeneratorConfiguration,
+  Status,
+} from '../types/AutomaticTransactionGenerator';
+import { MeterValuesRequest, RequestCommand } from '../types/ocpp/Requests';
+import type { MeterValuesResponse } from '../types/ocpp/Responses';
 import {
   AuthorizationStatus,
   AuthorizeRequest,
@@ -10,16 +17,11 @@ import {
   StopTransactionRequest,
   StopTransactionResponse,
 } from '../types/ocpp/Transaction';
-import { MeterValuesRequest, RequestCommand } from '../types/ocpp/Requests';
-
-import type ChargingStation from './ChargingStation';
 import Constants from '../utils/Constants';
-import { MeterValuesResponse } from '../types/ocpp/Responses';
-import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils';
-import PerformanceStatistics from '../performance/PerformanceStatistics';
-import { Status } from '../types/AutomaticTransactionGenerator';
-import Utils from '../utils/Utils';
 import logger from '../utils/Logger';
+import Utils from '../utils/Utils';
+import type ChargingStation from './ChargingStation';
+import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils';
 
 export default class AutomaticTransactionGenerator {
   private static readonly instances: Map<string, AutomaticTransactionGenerator> = new Map<
@@ -27,30 +29,41 @@ export default class AutomaticTransactionGenerator {
     AutomaticTransactionGenerator
   >();
 
+  public readonly configuration: AutomaticTransactionGeneratorConfiguration;
   public started: boolean;
   private readonly chargingStation: ChargingStation;
   private readonly connectorsStatus: Map<number, Status>;
 
-  private constructor(chargingStation: ChargingStation) {
+  private constructor(
+    automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration,
+    chargingStation: ChargingStation
+  ) {
+    this.configuration = automaticTransactionGeneratorConfiguration;
     this.chargingStation = chargingStation;
     this.connectorsStatus = new Map<number, Status>();
     this.stopConnectors();
     this.started = false;
   }
 
-  public static getInstance(chargingStation: ChargingStation): AutomaticTransactionGenerator {
-    if (!AutomaticTransactionGenerator.instances.has(chargingStation.hashId)) {
+  public static getInstance(
+    automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration,
+    chargingStation: ChargingStation
+  ): AutomaticTransactionGenerator {
+    if (!AutomaticTransactionGenerator.instances.has(chargingStation.stationInfo.hashId)) {
       AutomaticTransactionGenerator.instances.set(
-        chargingStation.hashId,
-        new AutomaticTransactionGenerator(chargingStation)
+        chargingStation.stationInfo.hashId,
+        new AutomaticTransactionGenerator(
+          automaticTransactionGeneratorConfiguration,
+          chargingStation
+        )
       );
     }
-    return AutomaticTransactionGenerator.instances.get(chargingStation.hashId);
+    return AutomaticTransactionGenerator.instances.get(chargingStation.stationInfo.hashId);
   }
 
   public start(): void {
-    if (this.started) {
-      logger.error(`${this.logPrefix()} trying to start while already started`);
+    if (this.started === true) {
+      logger.warn(`${this.logPrefix()} trying to start while already started`);
       return;
     }
     this.startConnectors();
@@ -58,14 +71,38 @@ export default class AutomaticTransactionGenerator {
   }
 
   public stop(): void {
-    if (!this.started) {
-      logger.error(`${this.logPrefix()} trying to stop while not started`);
+    if (this.started === false) {
+      logger.warn(`${this.logPrefix()} trying to stop while not started`);
       return;
     }
     this.stopConnectors();
     this.started = false;
   }
 
+  public startConnector(connectorId: number): void {
+    if (this.chargingStation.connectors.has(connectorId) === false) {
+      logger.warn(`${this.logPrefix(connectorId)} trying to start on non existing connector`);
+      return;
+    }
+    if (this.connectorsStatus.get(connectorId)?.start === false) {
+      // Avoid hogging the event loop with a busy loop
+      setImmediate(() => {
+        this.internalStartConnector(connectorId).catch(() => {
+          /* This is intentional */
+        });
+      });
+    } else if (this.connectorsStatus.get(connectorId)?.start === true) {
+      logger.warn(`${this.logPrefix(connectorId)} already started on connector`);
+    }
+  }
+
+  public stopConnector(connectorId: number): void {
+    this.connectorsStatus.set(connectorId, {
+      ...this.connectorsStatus.get(connectorId),
+      start: false,
+    });
+  }
+
   private startConnectors(): void {
     if (
       this.connectorsStatus?.size > 0 &&
@@ -89,7 +126,7 @@ export default class AutomaticTransactionGenerator {
   }
 
   private async internalStartConnector(connectorId: number): Promise<void> {
-    this.initStartConnectorStatus(connectorId);
+    this.initializeConnectorStatus(connectorId);
     logger.info(
       this.logPrefix(connectorId) +
         ' started on connector and will run for ' +
@@ -98,7 +135,7 @@ export default class AutomaticTransactionGenerator {
             this.connectorsStatus.get(connectorId).startDate.getTime()
         )
     );
-    while (this.connectorsStatus.get(connectorId).start) {
+    while (this.connectorsStatus.get(connectorId).start === true) {
       if (new Date() > this.connectorsStatus.get(connectorId).stopDate) {
         this.stopConnector(connectorId);
         break;
@@ -140,19 +177,15 @@ export default class AutomaticTransactionGenerator {
       }
       const wait =
         Utils.getRandomInteger(
-          this.chargingStation.stationInfo.AutomaticTransactionGenerator
-            .maxDelayBetweenTwoTransactions,
-          this.chargingStation.stationInfo.AutomaticTransactionGenerator
-            .minDelayBetweenTwoTransactions
+          this.configuration.maxDelayBetweenTwoTransactions,
+          this.configuration.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
-      ) {
+      if (start < this.configuration.probabilityOfStart) {
         this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
         // Start transaction
         const startResponse = await this.startTransaction(connectorId);
@@ -163,10 +196,8 @@ export default class AutomaticTransactionGenerator {
         } else {
           // Wait until end of transaction
           const waitTrxEnd =
-            Utils.getRandomInteger(
-              this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDuration,
-              this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDuration
-            ) * 1000;
+            Utils.getRandomInteger(this.configuration.maxDuration, this.configuration.minDuration) *
+            1000;
           logger.info(
             this.logPrefix(connectorId) +
               ' transaction ' +
@@ -209,28 +240,12 @@ export default class AutomaticTransactionGenerator {
         )
     );
     logger.debug(
-      `${this.logPrefix(connectorId)} connector status %j`,
+      `${this.logPrefix(connectorId)} connector status: %j`,
       this.connectorsStatus.get(connectorId)
     );
   }
 
-  private startConnector(connectorId: number): void {
-    // Avoid hogging the event loop with a busy loop
-    setImmediate(() => {
-      this.internalStartConnector(connectorId).catch(() => {
-        /* This is intentional */
-      });
-    });
-  }
-
-  private stopConnector(connectorId: number): void {
-    this.connectorsStatus.set(connectorId, {
-      ...this.connectorsStatus.get(connectorId),
-      start: false,
-    });
-  }
-
-  private initStartConnectorStatus(connectorId: number): void {
+  private initializeConnectorStatus(connectorId: number): void {
     this.connectorsStatus.get(connectorId).authorizeRequests =
       this?.connectorsStatus.get(connectorId)?.authorizeRequests ?? 0;
     this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests =
@@ -257,7 +272,7 @@ export default class AutomaticTransactionGenerator {
     this.connectorsStatus.get(connectorId).startDate = new Date();
     this.connectorsStatus.get(connectorId).stopDate = new Date(
       this.connectorsStatus.get(connectorId).startDate.getTime() +
-        (this.chargingStation.stationInfo?.AutomaticTransactionGenerator?.stopAfterHours ??
+        (this.configuration.stopAfterHours ??
           Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) *
           3600 *
           1000 -
@@ -274,25 +289,28 @@ export default class AutomaticTransactionGenerator {
     let startResponse: StartTransactionResponse;
     if (this.chargingStation.hasAuthorizedTags()) {
       const idTag = this.chargingStation.getRandomIdTag();
-      if (this.chargingStation.getAutomaticTransactionGeneratorRequireAuthorize()) {
+      const startTransactionLogMsg = `${this.logPrefix(
+        connectorId
+      )} start transaction for idTag '${idTag}'`;
+      if (this.getRequireAuthorize()) {
         this.chargingStation.getConnectorStatus(connectorId).authorizeIdTag = idTag;
         // Authorize idTag
         const authorizeResponse: AuthorizeResponse =
-          await this.chargingStation.ocppRequestService.sendMessageHandler<
+          await this.chargingStation.ocppRequestService.requestHandler<
             AuthorizeRequest,
             AuthorizeResponse
-          >(RequestCommand.AUTHORIZE, {
+          >(this.chargingStation, RequestCommand.AUTHORIZE, {
             idTag,
           });
         this.connectorsStatus.get(connectorId).authorizeRequests++;
         if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
           this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests++;
-          logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
+          logger.info(startTransactionLogMsg);
           // Start transaction
-          startResponse = await this.chargingStation.ocppRequestService.sendMessageHandler<
+          startResponse = await this.chargingStation.ocppRequestService.requestHandler<
             StartTransactionRequest,
             StartTransactionResponse
-          >(RequestCommand.START_TRANSACTION, {
+          >(this.chargingStation, RequestCommand.START_TRANSACTION, {
             connectorId,
             idTag,
           });
@@ -303,23 +321,23 @@ export default class AutomaticTransactionGenerator {
         PerformanceStatistics.endMeasure(measureId, beginId);
         return authorizeResponse;
       }
-      logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
+      logger.info(startTransactionLogMsg);
       // Start transaction
-      startResponse = await this.chargingStation.ocppRequestService.sendMessageHandler<
+      startResponse = await this.chargingStation.ocppRequestService.requestHandler<
         StartTransactionRequest,
         StartTransactionResponse
-      >(RequestCommand.START_TRANSACTION, {
+      >(this.chargingStation, RequestCommand.START_TRANSACTION, {
         connectorId,
         idTag,
       });
       PerformanceStatistics.endMeasure(measureId, beginId);
       return startResponse;
     }
-    logger.info(this.logPrefix(connectorId) + ' start transaction without an idTag');
-    startResponse = await this.chargingStation.ocppRequestService.sendMessageHandler<
+    logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
+    startResponse = await this.chargingStation.ocppRequestService.requestHandler<
       StartTransactionRequest,
       StartTransactionResponse
-    >(RequestCommand.START_TRANSACTION, { connectorId });
+    >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
     PerformanceStatistics.endMeasure(measureId, beginId);
     return startResponse;
   }
@@ -345,21 +363,24 @@ export default class AutomaticTransactionGenerator {
           connectorId,
           this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId)
         );
-        await this.chargingStation.ocppRequestService.sendMessageHandler<
+        await this.chargingStation.ocppRequestService.requestHandler<
           MeterValuesRequest,
           MeterValuesResponse
-        >(RequestCommand.METER_VALUES, {
+        >(this.chargingStation, RequestCommand.METER_VALUES, {
           connectorId,
           transactionId,
-          meterValue: transactionEndMeterValue,
+          meterValue: [transactionEndMeterValue],
         });
       }
-      stopResponse = await this.chargingStation.ocppRequestService.sendMessageHandler<
+      stopResponse = await this.chargingStation.ocppRequestService.requestHandler<
         StopTransactionRequest,
         StopTransactionResponse
-      >(RequestCommand.STOP_TRANSACTION, {
+      >(this.chargingStation, RequestCommand.STOP_TRANSACTION, {
         transactionId,
-        meterStop: this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
+        meterStop: this.chargingStation.getEnergyActiveImportRegisterByTransactionId(
+          transactionId,
+          true
+        ),
         idTag: this.chargingStation.getTransactionIdTag(transactionId),
         reason,
       });
@@ -375,16 +396,15 @@ export default class AutomaticTransactionGenerator {
     return stopResponse;
   }
 
+  private getRequireAuthorize(): boolean {
+    return this.configuration?.requireAuthorize ?? true;
+  }
+
   private logPrefix(connectorId?: number): string {
-    if (connectorId) {
-      return Utils.logPrefix(
-        ' ' +
-          this.chargingStation.stationInfo.chargingStationId +
-          ' | ATG on connector #' +
-          connectorId.toString() +
-          ':'
-      );
-    }
-    return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG:');
+    return Utils.logPrefix(
+      ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
+        connectorId !== undefined ? ` on connector #${connectorId.toString()}` : ''
+      }:`
+    );
   }
 }