Simplify stop transaction payload handling
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16RequestService.ts
index 3ff3bdcbddd6758b4020633663928747ba95004a..fef9d86daa6cbe3a855b8e9c3d09b27584ae9eee 100644 (file)
@@ -4,11 +4,11 @@ import fs from 'fs';
 import path from 'path';
 import { fileURLToPath } from 'url';
 
-import { JSONSchemaType } from 'ajv';
+import type { JSONSchemaType } from 'ajv';
 
 import OCPPError from '../../../exception/OCPPError';
-import { JsonObject, JsonType } from '../../../types/JsonType';
-import { OCPP16MeterValuesRequest } from '../../../types/ocpp/1.6/MeterValues';
+import type { JsonObject, JsonType } from '../../../types/JsonType';
+import type { OCPP16MeterValuesRequest } from '../../../types/ocpp/1.6/MeterValues';
 import {
   DiagnosticsStatusNotificationRequest,
   OCPP16BootNotificationRequest,
@@ -16,13 +16,13 @@ import {
   OCPP16RequestCommand,
   OCPP16StatusNotificationRequest,
 } from '../../../types/ocpp/1.6/Requests';
-import {
+import type {
   OCPP16AuthorizeRequest,
   OCPP16StartTransactionRequest,
   OCPP16StopTransactionRequest,
 } from '../../../types/ocpp/1.6/Transaction';
 import { ErrorType } from '../../../types/ocpp/ErrorType';
-import { RequestParams } from '../../../types/ocpp/Requests';
+import type { RequestParams } from '../../../types/ocpp/Requests';
 import Constants from '../../../utils/Constants';
 import logger from '../../../utils/Logger';
 import Utils from '../../../utils/Utils';
@@ -140,43 +140,34 @@ export default class OCPP16RequestService extends OCPPRequestService {
         ) as JSONSchemaType<OCPP16StopTransactionRequest>,
       ],
     ]);
+    this.buildRequestPayload.bind(this);
+    this.validatePayload.bind(this);
   }
 
-  public async requestHandler<Request extends JsonType, Response extends JsonType>(
+  public async requestHandler<RequestType extends JsonType, ResponseType extends JsonType>(
     chargingStation: ChargingStation,
     commandName: OCPP16RequestCommand,
     commandParams?: JsonType,
     params?: RequestParams
-  ): Promise<Response> {
+  ): Promise<ResponseType> {
     if (ChargingStationUtils.isRequestCommandSupported(commandName, chargingStation)) {
-      const requestPayload = this.buildRequestPayload<Request>(
+      const requestPayload = this.buildRequestPayload<RequestType>(
         chargingStation,
         commandName,
         commandParams
       );
-      if (this.jsonSchemas.has(commandName)) {
-        this.validateRequestPayload(
-          chargingStation,
-          commandName,
-          this.jsonSchemas.get(commandName),
-          requestPayload
-        );
-      } else {
-        logger.warn(
-          `${chargingStation.logPrefix()} ${moduleName}.requestHandler: No JSON schema found for command ${commandName} PDU validation`
-        );
-      }
+      this.validatePayload(chargingStation, commandName, requestPayload);
       return (await this.sendMessage(
         chargingStation,
         Utils.generateUUID(),
         requestPayload,
         commandName,
         params
-      )) as unknown as Response;
+      )) as unknown as ResponseType;
     }
     throw new OCPPError(
       ErrorType.NOT_SUPPORTED,
-      `${moduleName}.requestHandler: Unsupported OCPP command '${commandName}'`,
+      `Unsupported OCPP command '${commandName}'`,
       commandName,
       commandParams
     );
@@ -188,6 +179,7 @@ export default class OCPP16RequestService extends OCPPRequestService {
     commandParams?: JsonType
   ): Request {
     let connectorId: number;
+    let energyActiveImportRegister: number;
     commandParams = commandParams as JsonObject;
     switch (commandName) {
       case OCPP16RequestCommand.AUTHORIZE:
@@ -251,19 +243,25 @@ export default class OCPP16RequestService extends OCPPRequestService {
         connectorId = chargingStation.getConnectorIdByTransactionId(
           commandParams?.transactionId as number
         );
+        energyActiveImportRegister = chargingStation.getEnergyActiveImportRegisterByTransactionId(
+          commandParams?.transactionId as number,
+          true
+        );
         return {
           transactionId: commandParams?.transactionId,
-          ...(!Utils.isUndefined(commandParams?.idTag) && { idTag: commandParams.idTag }),
-          meterStop: commandParams?.meterStop,
+          idTag:
+            commandParams?.idTag ??
+            chargingStation.getTransactionIdTag(commandParams?.transactionId as number),
+          meterStop: commandParams?.meterStop ?? energyActiveImportRegister,
           timestamp: new Date().toISOString(),
-          ...(commandParams?.reason && { reason: commandParams.reason }),
+          reason: commandParams?.reason,
           ...(chargingStation.getTransactionDataMeterValues() && {
             transactionData: OCPP16ServiceUtils.buildTransactionDataMeterValues(
               chargingStation.getConnectorStatus(connectorId).transactionBeginMeterValue,
               OCPP16ServiceUtils.buildTransactionEndMeterValue(
                 chargingStation,
                 connectorId,
-                commandParams?.meterStop as number
+                (commandParams?.meterStop as number) ?? energyActiveImportRegister
               )
             ),
           }),
@@ -272,10 +270,29 @@ export default class OCPP16RequestService extends OCPPRequestService {
         throw new OCPPError(
           ErrorType.NOT_SUPPORTED,
           // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
-          `${moduleName}.buildRequestPayload: Unsupported OCPP command '${commandName}'`,
+          `Unsupported OCPP command '${commandName}'`,
           commandName,
           commandParams
         );
     }
   }
+
+  private validatePayload<Request extends JsonType>(
+    chargingStation: ChargingStation,
+    commandName: OCPP16RequestCommand,
+    requestPayload: Request
+  ): boolean {
+    if (this.jsonSchemas.has(commandName)) {
+      return this.validateRequestPayload(
+        chargingStation,
+        commandName,
+        this.jsonSchemas.get(commandName),
+        requestPayload
+      );
+    }
+    logger.warn(
+      `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation`
+    );
+    return false;
+  }
 }