Allow to specify more OCPP command payload fields while using the UI
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16RequestService.ts
index 5a0e0bc1fd2995f951259cf308aec352f4bb79fe..0671af3386336e5025045d3c347f407a5e4d8951 100644 (file)
-// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
+// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
 
 import fs from 'fs';
 import path from 'path';
 import { fileURLToPath } from 'url';
 
-import { JSONSchemaType } from 'ajv';
+import type { JSONSchemaType } from 'ajv';
 
+import { OCPP16ServiceUtils } from './OCPP16ServiceUtils';
 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,
-  OCPP16HeartbeatRequest,
+  type OCPP16BootNotificationRequest,
+  type OCPP16DataTransferRequest,
+  type OCPP16DiagnosticsStatusNotificationRequest,
+  type OCPP16FirmwareStatusNotificationRequest,
+  type OCPP16HeartbeatRequest,
   OCPP16RequestCommand,
-  OCPP16StatusNotificationRequest,
+  type 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 { OCPPVersion } from '../../../types/ocpp/OCPPVersion';
+import type { RequestParams } from '../../../types/ocpp/Requests';
 import Constants from '../../../utils/Constants';
-import logger from '../../../utils/Logger';
 import Utils from '../../../utils/Utils';
 import type ChargingStation from '../../ChargingStation';
-import { ChargingStationUtils } from '../../ChargingStationUtils';
 import OCPPRequestService from '../OCPPRequestService';
 import type OCPPResponseService from '../OCPPResponseService';
-import { OCPP16ServiceUtils } from './OCPP16ServiceUtils';
 
 const moduleName = 'OCPP16RequestService';
 
 export default class OCPP16RequestService extends OCPPRequestService {
-  private jsonSchemas: Map<OCPP16RequestCommand, JSONSchemaType<JsonObject>>;
+  protected jsonSchemas: Map<OCPP16RequestCommand, JSONSchemaType<JsonObject>>;
 
   public constructor(ocppResponseService: OCPPResponseService) {
     if (new.target?.name === moduleName) {
       throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
     }
-    super(ocppResponseService);
+    super(OCPPVersion.VERSION_16, ocppResponseService);
     this.jsonSchemas = new Map<OCPP16RequestCommand, JSONSchemaType<JsonObject>>([
       [
         OCPP16RequestCommand.AUTHORIZE,
-        JSON.parse(
-          fs.readFileSync(
-            path.resolve(
-              path.dirname(fileURLToPath(import.meta.url)),
-              '../../../assets/json-schemas/ocpp/1.6/Authorize.json'
-            ),
-            'utf8'
-          )
-        ) as JSONSchemaType<OCPP16AuthorizeRequest>,
+        this.parseJsonSchemaFile<OCPP16AuthorizeRequest>(
+          '../../../assets/json-schemas/ocpp/1.6/Authorize.json'
+        ),
       ],
       [
         OCPP16RequestCommand.BOOT_NOTIFICATION,
-        JSON.parse(
-          fs.readFileSync(
-            path.resolve(
-              path.dirname(fileURLToPath(import.meta.url)),
-              '../../../assets/json-schemas/ocpp/1.6/BootNotification.json'
-            ),
-            'utf8'
-          )
-        ) as JSONSchemaType<OCPP16BootNotificationRequest>,
+        this.parseJsonSchemaFile<OCPP16BootNotificationRequest>(
+          '../../../assets/json-schemas/ocpp/1.6/BootNotification.json'
+        ),
       ],
       [
         OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION,
-        JSON.parse(
-          fs.readFileSync(
-            path.resolve(
-              path.dirname(fileURLToPath(import.meta.url)),
-              '../../../assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotification.json'
-            ),
-            'utf8'
-          )
-        ) as JSONSchemaType<DiagnosticsStatusNotificationRequest>,
+        this.parseJsonSchemaFile<OCPP16DiagnosticsStatusNotificationRequest>(
+          '../../../assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotification.json'
+        ),
       ],
       [
         OCPP16RequestCommand.HEARTBEAT,
-        JSON.parse(
-          fs.readFileSync(
-            path.resolve(
-              path.dirname(fileURLToPath(import.meta.url)),
-              '../../../assets/json-schemas/ocpp/1.6/Heartbeat.json'
-            ),
-            'utf8'
-          )
-        ) as JSONSchemaType<OCPP16HeartbeatRequest>,
+        this.parseJsonSchemaFile<OCPP16HeartbeatRequest>(
+          '../../../assets/json-schemas/ocpp/1.6/Heartbeat.json'
+        ),
       ],
       [
         OCPP16RequestCommand.METER_VALUES,
-        JSON.parse(
-          fs.readFileSync(
-            path.resolve(
-              path.dirname(fileURLToPath(import.meta.url)),
-              '../../../assets/json-schemas/ocpp/1.6/MeterValues.json'
-            ),
-            'utf8'
-          )
-        ) as JSONSchemaType<OCPP16MeterValuesRequest>,
+        this.parseJsonSchemaFile<OCPP16MeterValuesRequest>(
+          '../../../assets/json-schemas/ocpp/1.6/MeterValues.json'
+        ),
       ],
       [
         OCPP16RequestCommand.STATUS_NOTIFICATION,
-        JSON.parse(
-          fs.readFileSync(
-            path.resolve(
-              path.dirname(fileURLToPath(import.meta.url)),
-              '../../../assets/json-schemas/ocpp/1.6/StatusNotification.json'
-            ),
-            'utf8'
-          )
-        ) as JSONSchemaType<OCPP16StatusNotificationRequest>,
+        this.parseJsonSchemaFile<OCPP16StatusNotificationRequest>(
+          '../../../assets/json-schemas/ocpp/1.6/StatusNotification.json'
+        ),
       ],
       [
         OCPP16RequestCommand.START_TRANSACTION,
-        JSON.parse(
-          fs.readFileSync(
-            path.resolve(
-              path.dirname(fileURLToPath(import.meta.url)),
-              '../../../assets/json-schemas/ocpp/1.6/StartTransaction.json'
-            ),
-            'utf8'
-          )
-        ) as JSONSchemaType<OCPP16StartTransactionRequest>,
+        this.parseJsonSchemaFile<OCPP16StartTransactionRequest>(
+          '../../../assets/json-schemas/ocpp/1.6/StartTransaction.json'
+        ),
       ],
       [
         OCPP16RequestCommand.STOP_TRANSACTION,
-        JSON.parse(
-          fs.readFileSync(
-            path.resolve(
-              path.dirname(fileURLToPath(import.meta.url)),
-              '../../../assets/json-schemas/ocpp/1.6/StopTransaction.json'
-            ),
-            'utf8'
-          )
-        ) as JSONSchemaType<OCPP16StopTransactionRequest>,
+        this.parseJsonSchemaFile<OCPP16StopTransactionRequest>(
+          '../../../assets/json-schemas/ocpp/1.6/StopTransaction.json'
+        ),
+      ],
+      [
+        OCPP16RequestCommand.DATA_TRANSFER,
+        this.parseJsonSchemaFile<OCPP16DataTransferRequest>(
+          '../../../assets/json-schemas/ocpp/1.6/DataTransfer.json'
+        ),
+      ],
+      [
+        OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION,
+        this.parseJsonSchemaFile<OCPP16FirmwareStatusNotificationRequest>(
+          '../../../assets/json-schemas/ocpp/1.6/FirmwareStatusNotification.json'
+        ),
       ],
     ]);
+    this.buildRequestPayload.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> {
-    if (ChargingStationUtils.isRequestCommandSupported(commandName, chargingStation)) {
-      const requestPayload = this.buildRequestPayload<Request>(
+  ): Promise<ResponseType> {
+    if (OCPP16ServiceUtils.isRequestCommandSupported(chargingStation, commandName) === true) {
+      const requestPayload = this.buildRequestPayload<RequestType>(
         chargingStation,
         commandName,
         commandParams
       );
-      this.validatePayload(chargingStation, commandName, requestPayload);
       return (await this.sendMessage(
         chargingStation,
         Utils.generateUUID(),
         requestPayload,
         commandName,
         params
-      )) as unknown as Response;
+      )) as unknown as ResponseType;
     }
+    // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
     throw new OCPPError(
       ErrorType.NOT_SUPPORTED,
-      `${moduleName}.requestHandler: Unsupported OCPP command '${commandName}'`,
+      `Unsupported OCPP command '${commandName}'`,
       commandName,
       commandParams
     );
@@ -177,6 +143,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:
@@ -208,8 +175,9 @@ export default class OCPP16RequestService extends OCPPRequestService {
           }),
         } as unknown as Request;
       case OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION:
+      case OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION:
         return {
-          status: commandParams?.diagnosticsStatus,
+          status: commandParams?.status,
         } as unknown as Request;
       case OCPP16RequestCommand.HEARTBEAT:
         return {} as unknown as Request;
@@ -224,6 +192,18 @@ export default class OCPP16RequestService extends OCPPRequestService {
           connectorId: commandParams?.connectorId,
           status: commandParams?.status,
           errorCode: commandParams?.errorCode,
+          ...(!Utils.isUndefined(commandParams?.info) && {
+            info: commandParams?.info,
+          }),
+          ...(!Utils.isUndefined(commandParams?.timestamp) && {
+            timestamp: commandParams?.timestamp,
+          }),
+          ...(!Utils.isUndefined(commandParams?.vendorId) && {
+            vendorId: commandParams?.vendorId,
+          }),
+          ...(!Utils.isUndefined(commandParams?.vendorErrorCode) && {
+            vendorErrorCode: commandParams?.vendorErrorCode,
+          }),
         } as unknown as Request;
       case OCPP16RequestCommand.START_TRANSACTION:
         return {
@@ -231,59 +211,71 @@ export default class OCPP16RequestService extends OCPPRequestService {
           ...(!Utils.isUndefined(commandParams?.idTag)
             ? { idTag: commandParams?.idTag }
             : { idTag: Constants.DEFAULT_IDTAG }),
-          meterStart: chargingStation.getEnergyActiveImportRegisterByConnectorId(
-            commandParams?.connectorId as number
-          ),
-          timestamp: new Date().toISOString(),
+          meterStart:
+            commandParams?.meterStart ??
+            chargingStation.getEnergyActiveImportRegisterByConnectorId(
+              commandParams?.connectorId as number
+            ),
+          timestamp: commandParams?.timestamp ?? new Date(),
+          ...(!Utils.isUndefined(commandParams?.reservationId) && {
+            reservationId: commandParams?.reservationId,
+          }),
         } as unknown as Request;
       case OCPP16RequestCommand.STOP_TRANSACTION:
-        connectorId = chargingStation.getConnectorIdByTransactionId(
-          commandParams?.transactionId as number
-        );
+        chargingStation.getTransactionDataMeterValues() &&
+          Utils.isUndefined(commandParams?.transactionData) &&
+          (connectorId = chargingStation.getConnectorIdByTransactionId(
+            commandParams?.transactionId as number
+          ));
+        !commandParams?.meterStop &&
+          (energyActiveImportRegister =
+            chargingStation.getEnergyActiveImportRegisterByTransactionId(
+              commandParams?.transactionId as number,
+              true
+            ));
         return {
           transactionId: commandParams?.transactionId,
-          ...(!Utils.isUndefined(commandParams?.idTag) && { idTag: commandParams.idTag }),
-          meterStop: commandParams?.meterStop,
-          timestamp: new Date().toISOString(),
-          ...(commandParams?.reason && { reason: commandParams.reason }),
-          ...(chargingStation.getTransactionDataMeterValues() && {
-            transactionData: OCPP16ServiceUtils.buildTransactionDataMeterValues(
-              chargingStation.getConnectorStatus(connectorId).transactionBeginMeterValue,
-              OCPP16ServiceUtils.buildTransactionEndMeterValue(
-                chargingStation,
-                connectorId,
-                commandParams?.meterStop as number
-              )
-            ),
+          idTag:
+            commandParams?.idTag ??
+            chargingStation.getTransactionIdTag(commandParams?.transactionId as number),
+          meterStop: commandParams?.meterStop ?? energyActiveImportRegister,
+          timestamp: commandParams?.timestamp ?? new Date(),
+          ...(!Utils.isUndefined(commandParams?.reason) && {
+            reason: commandParams?.reason,
           }),
+          ...(!Utils.isUndefined(commandParams?.transactionData)
+            ? { transactionData: commandParams?.transactionData }
+            : chargingStation.getTransactionDataMeterValues() && {
+                transactionData: OCPP16ServiceUtils.buildTransactionDataMeterValues(
+                  chargingStation.getConnectorStatus(connectorId).transactionBeginMeterValue,
+                  OCPP16ServiceUtils.buildTransactionEndMeterValue(
+                    chargingStation,
+                    connectorId,
+                    (commandParams?.meterStop as number) ?? energyActiveImportRegister
+                  )
+                ),
+              }),
         } as unknown as Request;
+      case OCPP16RequestCommand.DATA_TRANSFER:
+        return commandParams as unknown as Request;
       default:
+        // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
         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}.requestHandler: No JSON schema found for command ${commandName} PDU validation`
-    );
-    return false;
+  private parseJsonSchemaFile<T extends JsonType>(relativePath: string): JSONSchemaType<T> {
+    return JSON.parse(
+      fs.readFileSync(
+        path.resolve(path.dirname(fileURLToPath(import.meta.url)), relativePath),
+        'utf8'
+      )
+    ) as JSONSchemaType<T>;
   }
 }