refactor(simulator): make OCPPIncomingRequestService class inherit from
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16ResponseService.ts
index effa3abd0ada1244ba1ec1326e92c66848415dca..5433adecf704f658deeae8683f24d31e92cfb7ce 100644 (file)
@@ -1,9 +1,5 @@
 // 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 { OCPP16ServiceUtils } from './OCPP16ServiceUtils';
@@ -93,148 +89,196 @@ export default class OCPP16ResponseService extends OCPPResponseService {
     this.jsonSchemas = new Map<OCPP16RequestCommand, JSONSchemaType<JsonObject>>([
       [
         OCPP16RequestCommand.BOOT_NOTIFICATION,
-        this.parseJsonSchemaFile<OCPP16BootNotificationResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/BootNotificationResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16BootNotificationResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/BootNotificationResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16RequestCommand.HEARTBEAT,
-        this.parseJsonSchemaFile<OCPP16HeartbeatResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/HeartbeatResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16HeartbeatResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/HeartbeatResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16RequestCommand.AUTHORIZE,
-        this.parseJsonSchemaFile<OCPP16AuthorizeResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/AuthorizeResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16AuthorizeResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/AuthorizeResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16RequestCommand.START_TRANSACTION,
-        this.parseJsonSchemaFile<OCPP16StartTransactionResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/StartTransactionResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StartTransactionResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/StartTransactionResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16RequestCommand.STOP_TRANSACTION,
-        this.parseJsonSchemaFile<OCPP16StopTransactionResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/StopTransactionResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StopTransactionResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/StopTransactionResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16RequestCommand.STATUS_NOTIFICATION,
-        this.parseJsonSchemaFile<OCPP16StatusNotificationResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/StatusNotificationResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StatusNotificationResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/StatusNotificationResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16RequestCommand.METER_VALUES,
-        this.parseJsonSchemaFile<OCPP16MeterValuesResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/MeterValuesResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16MeterValuesResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/MeterValuesResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION,
-        this.parseJsonSchemaFile<OCPP16DiagnosticsStatusNotificationResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotificationResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DiagnosticsStatusNotificationResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotificationResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16RequestCommand.DATA_TRANSFER,
-        this.parseJsonSchemaFile<OCPP16DataTransferResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/DataTransferResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/DataTransferResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION,
-        this.parseJsonSchemaFile<OCPP16FirmwareStatusNotificationResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/FirmwareStatusNotificationResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16FirmwareStatusNotificationResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/FirmwareStatusNotificationResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
     ]);
     this.jsonIncomingRequestResponseSchemas = new Map([
       [
         OCPP16IncomingRequestCommand.RESET,
-        this.parseJsonSchemaFile<GenericResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/ResetResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/ResetResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.CLEAR_CACHE,
-        this.parseJsonSchemaFile<GenericResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/ClearCacheResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/ClearCacheResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.CHANGE_AVAILABILITY,
-        this.parseJsonSchemaFile<ChangeAvailabilityResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/ChangeAvailabilityResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<ChangeAvailabilityResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/ChangeAvailabilityResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.UNLOCK_CONNECTOR,
-        this.parseJsonSchemaFile<UnlockConnectorResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/UnlockConnectorResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<UnlockConnectorResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/UnlockConnectorResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.GET_CONFIGURATION,
-        this.parseJsonSchemaFile<GetConfigurationResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/GetConfigurationResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<GetConfigurationResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/GetConfigurationResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION,
-        this.parseJsonSchemaFile<ChangeConfigurationResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/ChangeConfigurationResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<ChangeConfigurationResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/ChangeConfigurationResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE,
-        this.parseJsonSchemaFile<SetChargingProfileResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/SetChargingProfileResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<SetChargingProfileResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/SetChargingProfileResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE,
-        this.parseJsonSchemaFile<ClearChargingProfileResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/ClearChargingProfileResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<ClearChargingProfileResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/ClearChargingProfileResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION,
-        this.parseJsonSchemaFile<GenericResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/RemoteStartTransactionResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/RemoteStartTransactionResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION,
-        this.parseJsonSchemaFile<GenericResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/RemoteStopTransactionResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/RemoteStopTransactionResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
-        this.parseJsonSchemaFile<GetDiagnosticsResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/GetDiagnosticsResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<GetDiagnosticsResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/GetDiagnosticsResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.TRIGGER_MESSAGE,
-        this.parseJsonSchemaFile<OCPP16TriggerMessageResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/TriggerMessageResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16TriggerMessageResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/TriggerMessageResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.DATA_TRANSFER,
-        this.parseJsonSchemaFile<OCPP16DataTransferResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/DataTransferResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/DataTransferResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
       [
         OCPP16IncomingRequestCommand.UPDATE_FIRMWARE,
-        this.parseJsonSchemaFile<OCPP16UpdateFirmwareResponse>(
-          '../../../assets/json-schemas/ocpp/1.6/UpdateFirmwareResponse.json'
+        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16UpdateFirmwareResponse>(
+          '../../../assets/json-schemas/ocpp/1.6/UpdateFirmwareResponse.json',
+          moduleName,
+          'constructor'
         ),
       ],
     ]);
@@ -343,8 +387,7 @@ export default class OCPP16ResponseService extends OCPPResponseService {
         : logger.info(logMsg);
     } else {
       logger.error(
-        chargingStation.logPrefix() +
-          ' Charging station boot notification response received: %j with undefined registration status',
+        `${chargingStation.logPrefix()} Charging station boot notification response received: %j with undefined registration status`,
         payload
       );
     }
@@ -365,24 +408,24 @@ export default class OCPP16ResponseService extends OCPPResponseService {
         break;
       }
     }
-    const isAuthorizeConnectorIdDefined = authorizeConnectorId !== undefined;
+    const authorizeConnectorIdDefined = authorizeConnectorId !== undefined;
     if (payload.idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) {
-      isAuthorizeConnectorIdDefined &&
+      authorizeConnectorIdDefined &&
         (chargingStation.getConnectorStatus(authorizeConnectorId).idTagAuthorized = true);
       logger.debug(
         `${chargingStation.logPrefix()} IdTag '${requestPayload.idTag}' accepted${
-          isAuthorizeConnectorIdDefined ? ` on connector ${authorizeConnectorId}` : ''
+          authorizeConnectorIdDefined ? ` on connector ${authorizeConnectorId}` : ''
         }`
       );
     } else {
-      if (isAuthorizeConnectorIdDefined) {
+      if (authorizeConnectorIdDefined) {
         chargingStation.getConnectorStatus(authorizeConnectorId).idTagAuthorized = false;
-        delete chargingStation.getConnectorStatus(authorizeConnectorId).authorizeIdTag;
+        delete chargingStation.getConnectorStatus(authorizeConnectorId)?.authorizeIdTag;
       }
       logger.debug(
         `${chargingStation.logPrefix()} IdTag '${requestPayload.idTag}' rejected with status '${
           payload.idTagInfo.status
-        }'${isAuthorizeConnectorIdDefined ? ` on connector ${authorizeConnectorId}` : ''}`
+        }'${authorizeConnectorIdDefined ? ` on connector ${authorizeConnectorId}` : ''}`
       );
     }
   }
@@ -401,86 +444,73 @@ export default class OCPP16ResponseService extends OCPPResponseService {
         break;
       }
     }
-    if (!transactionConnectorId) {
+    if (Utils.isNullOrUndefined(transactionConnectorId)) {
       logger.error(
-        chargingStation.logPrefix() +
-          ' Trying to start a transaction on a non existing connector Id ' +
-          connectorId.toString()
+        `${chargingStation.logPrefix()} Trying to start a transaction on a non existing connector Id ${connectorId.toString()}`
       );
       return;
     }
     if (
-      chargingStation.getConnectorStatus(connectorId).transactionRemoteStarted === true &&
+      chargingStation.getConnectorStatus(connectorId)?.transactionRemoteStarted === true &&
       chargingStation.getAuthorizeRemoteTxRequests() === true &&
       chargingStation.getLocalAuthListEnabled() === true &&
       chargingStation.hasAuthorizedTags() &&
-      chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized === false
+      chargingStation.getConnectorStatus(connectorId)?.idTagLocalAuthorized === false
     ) {
       logger.error(
-        chargingStation.logPrefix() +
-          ' Trying to start a transaction with a not local authorized idTag ' +
-          chargingStation.getConnectorStatus(connectorId).localAuthorizeIdTag +
-          ' on connector Id ' +
-          connectorId.toString()
+        `${chargingStation.logPrefix()} Trying to start a transaction with a not local authorized idTag ${
+          chargingStation.getConnectorStatus(connectorId)?.localAuthorizeIdTag
+        } on connector Id ${connectorId.toString()}`
       );
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
       return;
     }
     if (
-      chargingStation.getConnectorStatus(connectorId).transactionRemoteStarted === true &&
+      chargingStation.getConnectorStatus(connectorId)?.transactionRemoteStarted === true &&
       chargingStation.getAuthorizeRemoteTxRequests() === true &&
       chargingStation.getMustAuthorizeAtRemoteStart() === true &&
-      chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized === false &&
-      chargingStation.getConnectorStatus(connectorId).idTagAuthorized === false
+      chargingStation.getConnectorStatus(connectorId)?.idTagLocalAuthorized === false &&
+      chargingStation.getConnectorStatus(connectorId)?.idTagAuthorized === false
     ) {
       logger.error(
-        chargingStation.logPrefix() +
-          ' Trying to start a transaction with a not authorized idTag ' +
-          chargingStation.getConnectorStatus(connectorId).authorizeIdTag +
-          ' on connector Id ' +
-          connectorId.toString()
+        `${chargingStation.logPrefix()} Trying to start a transaction with a not authorized idTag ${
+          chargingStation.getConnectorStatus(connectorId)?.authorizeIdTag
+        } on connector Id ${connectorId.toString()}`
       );
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
       return;
     }
     if (
-      chargingStation.getConnectorStatus(connectorId).idTagAuthorized &&
-      chargingStation.getConnectorStatus(connectorId).authorizeIdTag !== requestPayload.idTag
+      chargingStation.getConnectorStatus(connectorId)?.idTagAuthorized &&
+      chargingStation.getConnectorStatus(connectorId)?.authorizeIdTag !== requestPayload.idTag
     ) {
       logger.error(
-        chargingStation.logPrefix() +
-          ' Trying to start a transaction with an idTag ' +
-          requestPayload.idTag +
-          ' different from the authorize request one ' +
-          chargingStation.getConnectorStatus(connectorId).authorizeIdTag +
-          ' on connector Id ' +
-          connectorId.toString()
+        `${chargingStation.logPrefix()} Trying to start a transaction with an idTag ${
+          requestPayload.idTag
+        } different from the authorize request one ${
+          chargingStation.getConnectorStatus(connectorId)?.authorizeIdTag
+        } on connector Id ${connectorId.toString()}`
       );
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
       return;
     }
     if (
-      chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized &&
-      chargingStation.getConnectorStatus(connectorId).localAuthorizeIdTag !== requestPayload.idTag
+      chargingStation.getConnectorStatus(connectorId)?.idTagLocalAuthorized &&
+      chargingStation.getConnectorStatus(connectorId)?.localAuthorizeIdTag !== requestPayload.idTag
     ) {
       logger.error(
-        chargingStation.logPrefix() +
-          ' Trying to start a transaction with an idTag ' +
-          requestPayload.idTag +
-          ' different from the local authorized one ' +
-          chargingStation.getConnectorStatus(connectorId).localAuthorizeIdTag +
-          ' on connector Id ' +
-          connectorId.toString()
+        `${chargingStation.logPrefix()} Trying to start a transaction with an idTag ${
+          requestPayload.idTag
+        } different from the local authorized one ${
+          chargingStation.getConnectorStatus(connectorId)?.localAuthorizeIdTag
+        } on connector Id ${connectorId.toString()}`
       );
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
       return;
     }
     if (chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
       logger.debug(
-        chargingStation.logPrefix() +
-          ' Trying to start a transaction on an already used connector ' +
-          connectorId.toString() +
-          ': %j',
+        `${chargingStation.logPrefix()} Trying to start a transaction on an already used connector ${connectorId.toString()}: %j`,
         chargingStation.getConnectorStatus(connectorId)
       );
       return;
@@ -538,16 +568,9 @@ export default class OCPP16ResponseService extends OCPPResponseService {
       });
       chargingStation.getConnectorStatus(connectorId).status = OCPP16ChargePointStatus.CHARGING;
       logger.info(
-        chargingStation.logPrefix() +
-          ' Transaction ' +
-          payload.transactionId.toString() +
-          ' STARTED on ' +
-          chargingStation.stationInfo.chargingStationId +
-          '#' +
-          connectorId.toString() +
-          " for idTag '" +
-          requestPayload.idTag +
-          "'"
+        `${chargingStation.logPrefix()} Transaction ${payload.transactionId.toString()} STARTED on ${
+          chargingStation.stationInfo.chargingStationId
+        }#${connectorId.toString()} for idTag '${requestPayload.idTag}'`
       );
       if (chargingStation.stationInfo.powerSharedByConnectors) {
         chargingStation.powerDivider++;
@@ -565,14 +588,9 @@ export default class OCPP16ResponseService extends OCPPResponseService {
       );
     } else {
       logger.warn(
-        chargingStation.logPrefix() +
-          ' Starting transaction id ' +
-          payload.transactionId.toString() +
-          " REJECTED with status '" +
-          payload.idTagInfo?.status +
-          "', idTag '" +
-          requestPayload.idTag +
-          "'"
+        `${chargingStation.logPrefix()} Starting transaction id ${payload.transactionId.toString()} REJECTED with status '${
+          payload.idTagInfo?.status
+        }', idTag '${requestPayload.idTag}'`
       );
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
     }
@@ -584,7 +602,7 @@ export default class OCPP16ResponseService extends OCPPResponseService {
   ): Promise<void> {
     chargingStation.resetConnectorStatus(connectorId);
     if (
-      chargingStation.getConnectorStatus(connectorId).status !== OCPP16ChargePointStatus.AVAILABLE
+      chargingStation.getConnectorStatus(connectorId)?.status !== OCPP16ChargePointStatus.AVAILABLE
     ) {
       await chargingStation.ocppRequestService.requestHandler<
         OCPP16StatusNotificationRequest,
@@ -606,11 +624,9 @@ export default class OCPP16ResponseService extends OCPPResponseService {
     const transactionConnectorId = chargingStation.getConnectorIdByTransactionId(
       requestPayload.transactionId
     );
-    if (!transactionConnectorId) {
+    if (Utils.isNullOrUndefined(transactionConnectorId)) {
       logger.error(
-        chargingStation.logPrefix() +
-          ' Trying to stop a non existing transaction ' +
-          requestPayload.transactionId.toString()
+        `${chargingStation.logPrefix()} Trying to stop a non existing transaction ${requestPayload.transactionId.toString()}`
       );
       return;
     }
@@ -663,7 +679,7 @@ export default class OCPP16ResponseService extends OCPPResponseService {
     chargingStation.resetConnectorStatus(transactionConnectorId);
     const logMsg = `${chargingStation.logPrefix()} Transaction ${requestPayload.transactionId.toString()} STOPPED on ${
       chargingStation.stationInfo.chargingStationId
-    }#${transactionConnectorId.toString()} with status '${
+    }#${transactionConnectorId?.toString()} with status '${
       payload.idTagInfo?.status ?? 'undefined'
     }'`;
     if (
@@ -675,13 +691,4 @@ export default class OCPP16ResponseService extends OCPPResponseService {
       logger.warn(logMsg);
     }
   }
-
-  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>;
-  }
 }