Hook the OCPP 2.0 stack into the main code
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16RequestService.ts
index 75e113d21162efaecb375b069ab60e124552242c..dce1e44a87a5ad636b4d415820f7aa55bde59f56 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 type { JSONSchemaType } from 'ajv';
 
-import type ChargingStation from '../../ChargingStation';
-import Constants from '../../../utils/Constants';
-import { ErrorType } from '../../../types/ocpp/ErrorType';
-import { JsonType } from '../../../types/JsonType';
-import { OCPP16RequestCommand } from '../../../types/ocpp/1.6/Requests';
-import { OCPP16ServiceUtils } from './OCPP16ServiceUtils';
 import OCPPError from '../../../exception/OCPPError';
+import type { JsonObject, JsonType } from '../../../types/JsonType';
+import type { OCPP16MeterValuesRequest } from '../../../types/ocpp/1.6/MeterValues';
+import {
+  type DiagnosticsStatusNotificationRequest,
+  type OCPP16BootNotificationRequest,
+  type OCPP16DataTransferRequest,
+  type OCPP16HeartbeatRequest,
+  OCPP16RequestCommand,
+  type OCPP16StatusNotificationRequest,
+} from '../../../types/ocpp/1.6/Requests';
+import type {
+  OCPP16AuthorizeRequest,
+  OCPP16StartTransactionRequest,
+  OCPP16StopTransactionRequest,
+} from '../../../types/ocpp/1.6/Transaction';
+import { ErrorType } from '../../../types/ocpp/ErrorType';
+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 OCPPRequestService from '../OCPPRequestService';
 import type OCPPResponseService from '../OCPPResponseService';
-import { RequestParams } from '../../../types/ocpp/Requests';
-import Utils from '../../../utils/Utils';
+import { OCPP16ServiceUtils } from './OCPP16ServiceUtils';
 
 const moduleName = 'OCPP16RequestService';
 
 export default class OCPP16RequestService extends OCPPRequestService {
-  public constructor(chargingStation: ChargingStation, ocppResponseService: OCPPResponseService) {
+  private 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(chargingStation, ocppResponseService);
+    super(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>,
+      ],
+      [
+        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>,
+      ],
+      [
+        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>,
+      ],
+      [
+        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>,
+      ],
+      [
+        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>,
+      ],
+      [
+        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>,
+      ],
+      [
+        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>,
+      ],
+      [
+        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>,
+      ],
+      [
+        OCPP16RequestCommand.DATA_TRANSFER,
+        JSON.parse(
+          fs.readFileSync(
+            path.resolve(
+              path.dirname(fileURLToPath(import.meta.url)),
+              '../../../assets/json-schemas/ocpp/1.6/DataTransfer.json'
+            ),
+            'utf8'
+          )
+        ) as JSONSchemaType<OCPP16DataTransferRequest>,
+      ],
+    ]);
+    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> {
-    if (Object.values(OCPP16RequestCommand).includes(commandName)) {
+  ): 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(),
-        this.buildRequestPayload<Request>(commandName, commandParams),
+        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,
-      { commandName }
+      commandParams
     );
   }
 
   private buildRequestPayload<Request extends JsonType>(
+    chargingStation: ChargingStation,
     commandName: OCPP16RequestCommand,
     commandParams?: JsonType
   ): Request {
     let connectorId: number;
+    let energyActiveImportRegister: number;
+    commandParams = commandParams as JsonObject;
     switch (commandName) {
       case OCPP16RequestCommand.AUTHORIZE:
         return {
@@ -87,9 +233,7 @@ export default class OCPP16RequestService extends OCPPRequestService {
         return {
           connectorId: commandParams?.connectorId,
           transactionId: commandParams?.transactionId,
-          meterValue: Array.isArray(commandParams?.meterValue)
-            ? commandParams?.meterValue
-            : [commandParams?.meterValue],
+          meterValue: commandParams?.meterValue,
         } as unknown as Request;
       case OCPP16RequestCommand.STATUS_NOTIFICATION:
         return {
@@ -103,40 +247,70 @@ export default class OCPP16RequestService extends OCPPRequestService {
           ...(!Utils.isUndefined(commandParams?.idTag)
             ? { idTag: commandParams?.idTag }
             : { idTag: Constants.DEFAULT_IDTAG }),
-          meterStart: this.chargingStation.getEnergyActiveImportRegisterByConnectorId(
+          meterStart: chargingStation.getEnergyActiveImportRegisterByConnectorId(
             commandParams?.connectorId as number
           ),
           timestamp: new Date().toISOString(),
         } as unknown as Request;
       case OCPP16RequestCommand.STOP_TRANSACTION:
-        connectorId = this.chargingStation.getConnectorIdByTransactionId(
+        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,
+          idTag:
+            commandParams?.idTag ??
+            chargingStation.getTransactionIdTag(commandParams?.transactionId as number),
+          meterStop: commandParams?.meterStop ?? energyActiveImportRegister,
           timestamp: new Date().toISOString(),
-          ...(commandParams?.reason && { reason: commandParams.reason }),
-          ...(this.chargingStation.getTransactionDataMeterValues() && {
+          reason: commandParams?.reason,
+          ...(chargingStation.getTransactionDataMeterValues() && {
             transactionData: OCPP16ServiceUtils.buildTransactionDataMeterValues(
-              this.chargingStation.getConnectorStatus(connectorId).transactionBeginMeterValue,
+              chargingStation.getConnectorStatus(connectorId).transactionBeginMeterValue,
               OCPP16ServiceUtils.buildTransactionEndMeterValue(
-                this.chargingStation,
+                chargingStation,
                 connectorId,
-                commandParams?.meterStop as number
+                (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,
-          { 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;
+  }
 }