Fixes to OCA OCPP 2.0.1 JSON schemas
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPRequestService.ts
index da39fb9e4367f6dfa7a0ad93388c987d7a88190d..e4890a91d8a6a88e2c8d282fcd603c2b2c31baef 100644 (file)
@@ -1,5 +1,4 @@
-import type { JSONSchemaType } from 'ajv';
-import Ajv from 'ajv-draft-04';
+import Ajv, { type JSONSchemaType } from 'ajv';
 import ajvFormats from 'ajv-formats';
 
 import OCPPError from '../../exception/OCPPError';
@@ -9,14 +8,15 @@ import type { HandleErrorParams } from '../../types/Error';
 import type { JsonObject, JsonType } from '../../types/JsonType';
 import { ErrorType } from '../../types/ocpp/ErrorType';
 import { MessageType } from '../../types/ocpp/MessageType';
+import type { OCPPVersion } from '../../types/ocpp/OCPPVersion';
 import {
-  ErrorCallback,
-  IncomingRequestCommand,
-  OutgoingRequest,
+  type ErrorCallback,
+  type IncomingRequestCommand,
+  type OutgoingRequest,
   RequestCommand,
-  RequestParams,
-  ResponseCallback,
-  ResponseType,
+  type RequestParams,
+  type ResponseCallback,
+  type ResponseType,
 } from '../../types/ocpp/Requests';
 import type { ErrorResponse, Response } from '../../types/ocpp/Responses';
 import Constants from '../../utils/Constants';
@@ -30,14 +30,19 @@ const moduleName = 'OCPPRequestService';
 
 export default abstract class OCPPRequestService {
   private static instance: OCPPRequestService | null = null;
+  private readonly version: OCPPVersion;
   private readonly ajv: Ajv;
 
   private readonly ocppResponseService: OCPPResponseService;
 
-  protected constructor(ocppResponseService: OCPPResponseService) {
-    this.ocppResponseService = ocppResponseService;
-    this.ajv = new Ajv();
+  protected constructor(version: OCPPVersion, ocppResponseService: OCPPResponseService) {
+    this.version = version;
+    this.ajv = new Ajv({
+      keywords: ['javaType'],
+      multipleOfPrecision: 2,
+    });
     ajvFormats(this.ajv);
+    this.ocppResponseService = ocppResponseService;
     this.requestHandler.bind(this);
     this.sendMessage.bind(this);
     this.sendResponse.bind(this);
@@ -125,19 +130,23 @@ export default abstract class OCPPRequestService {
 
   protected validateRequestPayload<T extends JsonType>(
     chargingStation: ChargingStation,
-    commandName: RequestCommand,
-    schema: JSONSchemaType<T>,
+    commandName: RequestCommand | IncomingRequestCommand,
     payload: T
   ): boolean {
     if (chargingStation.getPayloadSchemaValidation() === false) {
       return true;
     }
+    const schema = this.getRequestPayloadValidationSchema(chargingStation, commandName);
+    if (schema === false) {
+      return true;
+    }
     const validate = this.ajv.compile(schema);
+    OCPPServiceUtils.convertDateToISOString<T>(payload);
     if (validate(payload)) {
       return true;
     }
     logger.error(
-      `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Request PDU is invalid: %j`,
+      `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Command '${commandName}' request PDU is invalid: %j`,
       validate.errors
     );
     // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
@@ -189,10 +198,10 @@ export default abstract class OCPPRequestService {
           // Check if wsConnection opened
           if (chargingStation.isWebSocketConnectionOpened() === true) {
             // Yes: Send Message
-            const beginId = PerformanceStatistics.beginMeasure(commandName);
+            const beginId = PerformanceStatistics.beginMeasure(commandName as string);
             // FIXME: Handle sending error
             chargingStation.wsConnection.send(messageToSend);
-            PerformanceStatistics.endMeasure(commandName, beginId);
+            PerformanceStatistics.endMeasure(commandName as string, beginId);
             logger.debug(
               `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
                 messageType
@@ -325,6 +334,7 @@ export default abstract class OCPPRequestService {
           commandName,
           messagePayload as JsonType,
         ]);
+        this.validateRequestPayload(chargingStation, commandName, messagePayload as JsonType);
         messageToSend = JSON.stringify([
           messageType,
           messageId,
@@ -335,6 +345,7 @@ export default abstract class OCPPRequestService {
       // Response
       case MessageType.CALL_RESULT_MESSAGE:
         // Build response
+        // FIXME: Validate response payload
         messageToSend = JSON.stringify([messageType, messageId, messagePayload] as Response);
         break;
       // Error Message
@@ -376,10 +387,15 @@ export default abstract class OCPPRequestService {
   }
 
   // eslint-disable-next-line @typescript-eslint/no-unused-vars
-  public abstract requestHandler<RequestType extends JsonType, ResponseType extends JsonType>(
+  public abstract requestHandler<ReqType extends JsonType, ResType extends JsonType>(
     chargingStation: ChargingStation,
     commandName: RequestCommand,
     commandParams?: JsonType,
     params?: RequestParams
-  ): Promise<ResponseType>;
+  ): Promise<ResType>;
+
+  protected abstract getRequestPayloadValidationSchema(
+    chargingStation: ChargingStation,
+    commandName: RequestCommand | IncomingRequestCommand
+  ): JSONSchemaType<JsonObject> | false;
 }