Fix isEmptyString() semantic
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPRequestService.ts
index aba9bfd00edc28949779c23eaac079f116324ca6..6a7729950de33b2532fb1b8c0153dc170280a957 100644 (file)
@@ -1,6 +1,8 @@
 import Ajv, { type JSONSchemaType } from 'ajv';
 import ajvFormats from 'ajv-formats';
 
+import type OCPPResponseService from './OCPPResponseService';
+import { OCPPServiceUtils } from './OCPPServiceUtils';
 import OCPPError from '../../exception/OCPPError';
 import PerformanceStatistics from '../../performance/PerformanceStatistics';
 import type { EmptyObject } from '../../types/EmptyObject';
@@ -23,8 +25,6 @@ import Constants from '../../utils/Constants';
 import logger from '../../utils/Logger';
 import Utils from '../../utils/Utils';
 import type ChargingStation from '../ChargingStation';
-import type OCPPResponseService from './OCPPResponseService';
-import { OCPPServiceUtils } from './OCPPServiceUtils';
 
 const moduleName = 'OCPPRequestService';
 
@@ -211,7 +211,7 @@ export default abstract class OCPPRequestService {
     messageId: string,
     messagePayload: JsonType | OCPPError,
     messageType: MessageType,
-    commandName?: RequestCommand | IncomingRequestCommand,
+    commandName: RequestCommand | IncomingRequestCommand,
     params: RequestParams = {
       skipBufferingOnError: false,
       triggerMessage: false,
@@ -231,6 +231,9 @@ export default abstract class OCPPRequestService {
       // Send a message through wsConnection
       return Utils.promiseWithTimeout(
         new Promise((resolve, reject) => {
+          if (chargingStation.getEnableStatistics() === true) {
+            chargingStation.performanceStatistics?.addRequestStatistic(commandName, messageType);
+          }
           const messageToSend = this.buildMessageToSend(
             chargingStation,
             messageId,
@@ -240,27 +243,30 @@ export default abstract class OCPPRequestService {
             responseCallback,
             errorCallback
           );
-          if (chargingStation.getEnableStatistics() === true) {
-            chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
-          }
           let sendError = false;
           // Check if wsConnection opened
-          if (chargingStation.isWebSocketConnectionOpened() === true) {
-            const beginId = PerformanceStatistics.beginMeasure(commandName as string);
+          const wsOpened = chargingStation.isWebSocketConnectionOpened() === true;
+          if (wsOpened) {
+            const beginId = PerformanceStatistics.beginMeasure(commandName);
             try {
-              chargingStation.wsConnection.send(messageToSend);
+              chargingStation.wsConnection?.send(messageToSend);
+              logger.debug(
+                `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${OCPPServiceUtils.getMessageTypeString(
+                  messageType
+                )} payload: ${messageToSend}`
+              );
             } catch (error) {
+              logger.error(
+                `${chargingStation.logPrefix()} >> Command '${commandName}' failed to send ${OCPPServiceUtils.getMessageTypeString(
+                  messageType
+                )} payload: ${messageToSend}:`,
+                error
+              );
               sendError = true;
             }
-            PerformanceStatistics.endMeasure(commandName as string, beginId);
-            logger.debug(
-              `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
-                messageType
-              )} payload: ${messageToSend}`
-            );
+            PerformanceStatistics.endMeasure(commandName, beginId);
           }
-          const wsClosedOrErrored =
-            chargingStation.isWebSocketConnectionOpened() === false || sendError === true;
+          const wsClosedOrErrored = !wsOpened || sendError === true;
           if (wsClosedOrErrored && params.skipBufferingOnError === false) {
             // Buffer
             chargingStation.bufferMessage(messageToSend);
@@ -300,7 +306,7 @@ export default abstract class OCPPRequestService {
            */
           function responseCallback(payload: JsonType, requestPayload: JsonType): void {
             if (chargingStation.getEnableStatistics() === true) {
-              chargingStation.performanceStatistics.addRequestStatistic(
+              chargingStation.performanceStatistics?.addRequestStatistic(
                 commandName,
                 MessageType.CALL_RESULT_MESSAGE
               );
@@ -332,13 +338,13 @@ export default abstract class OCPPRequestService {
            */
           function errorCallback(error: OCPPError, requestStatistic = true): void {
             if (requestStatistic === true && chargingStation.getEnableStatistics() === true) {
-              chargingStation.performanceStatistics.addRequestStatistic(
+              chargingStation.performanceStatistics?.addRequestStatistic(
                 commandName,
                 MessageType.CALL_ERROR_MESSAGE
               );
             }
             logger.error(
-              `${chargingStation.logPrefix()} Error occurred at ${self.getMessageTypeString(
+              `${chargingStation.logPrefix()} Error occurred at ${OCPPServiceUtils.getMessageTypeString(
                 messageType
               )} command ${commandName} with PDU %j:`,
               messagePayload,
@@ -372,9 +378,9 @@ export default abstract class OCPPRequestService {
     messageId: string,
     messagePayload: JsonType | OCPPError,
     messageType: MessageType,
-    commandName?: RequestCommand | IncomingRequestCommand,
-    responseCallback?: ResponseCallback,
-    errorCallback?: ErrorCallback
+    commandName: RequestCommand | IncomingRequestCommand,
+    responseCallback: ResponseCallback,
+    errorCallback: ErrorCallback
   ): string {
     let messageToSend: string;
     // Type of message
@@ -382,13 +388,13 @@ export default abstract class OCPPRequestService {
       // Request
       case MessageType.CALL_MESSAGE:
         // Build request
+        this.validateRequestPayload(chargingStation, commandName, messagePayload as JsonObject);
         chargingStation.requests.set(messageId, [
           responseCallback,
           errorCallback,
           commandName,
           messagePayload as JsonType,
         ]);
-        this.validateRequestPayload(chargingStation, commandName, messagePayload as JsonObject);
         messageToSend = JSON.stringify([
           messageType,
           messageId,
@@ -421,17 +427,6 @@ export default abstract class OCPPRequestService {
     return messageToSend;
   }
 
-  private getMessageTypeString(messageType: MessageType): string {
-    switch (messageType) {
-      case MessageType.CALL_MESSAGE:
-        return 'request';
-      case MessageType.CALL_RESULT_MESSAGE:
-        return 'response';
-      case MessageType.CALL_ERROR_MESSAGE:
-        return 'error';
-    }
-  }
-
   private handleSendMessageError(
     chargingStation: ChargingStation,
     commandName: RequestCommand | IncomingRequestCommand,