build(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPRequestService.ts
index 69fb503eaf303beee1378157fce587c25393bc9b..076dfb2166e3d38ca4bbe4c0ba67cd727c1bc514 100644 (file)
@@ -23,13 +23,7 @@ import {
   type ResponseCallback,
   type ResponseType,
 } from '../../types';
-import {
-  Constants,
-  cloneObject,
-  handleSendMessageError,
-  logger,
-  promiseWithTimeout,
-} from '../../utils';
+import { Constants, cloneObject, handleSendMessageError, logger } from '../../utils';
 
 const moduleName = 'OCPPRequestService';
 
@@ -99,8 +93,6 @@ export abstract class OCPPRequestService {
       messagePayload: JsonType | OCPPError,
       messageType: MessageType,
       commandName: RequestCommand | IncomingRequestCommand,
-      responseCallback: ResponseCallback,
-      errorCallback: ErrorCallback,
     ) => string;
     this.validateRequestPayload = this.validateRequestPayload.bind(this) as <T extends JsonType>(
       chargingStation: ChargingStation,
@@ -321,145 +313,161 @@ export abstract class OCPPRequestService {
       // eslint-disable-next-line @typescript-eslint/no-this-alias
       const self = this;
       // Send a message through wsConnection
-      return promiseWithTimeout(
-        new Promise<ResponseType>((resolve, reject) => {
-          /**
-           * Function that will receive the request's response
-           *
-           * @param payload -
-           * @param requestPayload -
-           */
-          const responseCallback = (payload: JsonType, requestPayload: JsonType): void => {
-            if (chargingStation.stationInfo?.enableStatistics === true) {
-              chargingStation.performanceStatistics?.addRequestStatistic(
-                commandName,
-                MessageType.CALL_RESULT_MESSAGE,
-              );
-            }
-            // Handle the request's response
-            self.ocppResponseService
-              .responseHandler(
-                chargingStation,
-                commandName as RequestCommand,
-                payload,
-                requestPayload,
-              )
-              .then(() => {
-                resolve(payload);
-              })
-              .catch((error) => {
-                reject(error);
-              })
-              .finally(() => {
-                chargingStation.requests.delete(messageId);
-              });
-          };
-
-          /**
-           * Function that will receive the request's error response
-           *
-           * @param error -
-           * @param requestStatistic -
-           */
-          const errorCallback = (error: OCPPError, requestStatistic = true): void => {
-            if (
-              requestStatistic === true &&
-              chargingStation.stationInfo?.enableStatistics === true
-            ) {
-              chargingStation.performanceStatistics?.addRequestStatistic(
-                commandName,
-                MessageType.CALL_ERROR_MESSAGE,
-              );
-            }
-            logger.error(
-              `${chargingStation.logPrefix()} Error occurred at ${OCPPServiceUtils.getMessageTypeString(
-                messageType,
-              )} command ${commandName} with PDU %j:`,
-              messagePayload,
-              error,
+      return await new Promise<ResponseType>((resolve, reject) => {
+        /**
+         * Function that will receive the request's response
+         *
+         * @param payload -
+         * @param requestPayload -
+         */
+        const responseCallback = (payload: JsonType, requestPayload: JsonType): void => {
+          if (chargingStation.stationInfo?.enableStatistics === true) {
+            chargingStation.performanceStatistics?.addRequestStatistic(
+              commandName,
+              MessageType.CALL_RESULT_MESSAGE,
             );
-            chargingStation.requests.delete(messageId);
-            reject(error);
-          };
+          }
+          // Handle the request's response
+          self.ocppResponseService
+            .responseHandler(
+              chargingStation,
+              commandName as RequestCommand,
+              payload,
+              requestPayload,
+            )
+            .then(() => {
+              resolve(payload);
+            })
+            .catch((error) => {
+              reject(error);
+            })
+            .finally(() => {
+              chargingStation.requests.delete(messageId);
+            });
+        };
 
-          if (chargingStation.stationInfo?.enableStatistics === true) {
-            chargingStation.performanceStatistics?.addRequestStatistic(commandName, messageType);
+        /**
+         * Function that will receive the request's error response
+         *
+         * @param error -
+         * @param requestStatistic -
+         */
+        const errorCallback = (error: OCPPError, requestStatistic = true): void => {
+          if (requestStatistic === true && chargingStation.stationInfo?.enableStatistics === true) {
+            chargingStation.performanceStatistics?.addRequestStatistic(
+              commandName,
+              MessageType.CALL_ERROR_MESSAGE,
+            );
           }
-          const messageToSend = this.buildMessageToSend(
-            chargingStation,
-            messageId,
+          logger.error(
+            `${chargingStation.logPrefix()} Error occurred at ${OCPPServiceUtils.getMessageTypeString(
+              messageType,
+            )} command ${commandName} with PDU %j:`,
             messagePayload,
-            messageType,
-            commandName,
-            responseCallback,
-            errorCallback,
+            error,
           );
-          let sendError = false;
-          // Check if wsConnection opened
-          const wsOpened = chargingStation.isWebSocketConnectionOpened() === true;
-          if (wsOpened) {
-            const beginId = PerformanceStatistics.beginMeasure(commandName);
-            try {
-              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, beginId);
-          }
-          const wsClosedOrErrored = !wsOpened || sendError === true;
-          if (wsClosedOrErrored && params?.skipBufferingOnError === false) {
-            // Buffer
-            chargingStation.bufferMessage(messageToSend);
-            // Reject and keep request in the cache
-            return reject(
+          chargingStation.requests.delete(messageId);
+          reject(error);
+        };
+
+        if (chargingStation.stationInfo?.enableStatistics === true) {
+          chargingStation.performanceStatistics?.addRequestStatistic(commandName, messageType);
+        }
+        const messageToSend = this.buildMessageToSend(
+          chargingStation,
+          messageId,
+          messagePayload,
+          messageType,
+          commandName,
+        );
+        // Check if wsConnection opened
+        if (chargingStation.isWebSocketConnectionOpened() === true) {
+          const beginId = PerformanceStatistics.beginMeasure(commandName);
+          const sendTimeout = setTimeout(() => {
+            return errorCallback(
               new OCPPError(
                 ErrorType.GENERIC_ERROR,
-                `WebSocket closed or errored for buffered message id '${messageId}' with content '${messageToSend}'`,
+                `Timeout for message id '${messageId}'`,
                 commandName,
                 (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FROZEN_OBJECT,
               ),
+              false,
             );
-          } else if (wsClosedOrErrored) {
-            const ocppError = new OCPPError(
-              ErrorType.GENERIC_ERROR,
-              `WebSocket closed or errored for non buffered message id '${messageId}' with content '${messageToSend}'`,
+          }, OCPPConstants.OCPP_WEBSOCKET_TIMEOUT);
+          chargingStation.wsConnection?.send(messageToSend, (error?: Error) => {
+            clearTimeout(sendTimeout);
+            if (error) {
+              const ocppError = new OCPPError(
+                ErrorType.GENERIC_ERROR,
+                `WebSocket errored for ${
+                  params?.skipBufferingOnError === false ? '' : 'non '
+                }buffered message id '${messageId}' with content '${messageToSend}'`,
+                commandName,
+                { name: error.name, message: error.message, stack: error.stack } ??
+                  Constants.EMPTY_FROZEN_OBJECT,
+              );
+              if (params?.skipBufferingOnError === false) {
+                // Buffer
+                chargingStation.bufferMessage(messageToSend);
+                // Reject and keep request in the cache
+                return reject(ocppError);
+              }
+              // Reject response
+              if (messageType !== MessageType.CALL_MESSAGE) {
+                return reject(ocppError);
+              }
+              // Reject and remove request from the cache
+              return errorCallback(ocppError, false);
+            }
+          });
+          if (messageType === MessageType.CALL_MESSAGE) {
+            this.cacheRequestPromise(
+              chargingStation,
+              messageId,
+              messagePayload as JsonType,
               commandName,
-              (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FROZEN_OBJECT,
+              responseCallback,
+              errorCallback,
             );
-            // Reject response
-            if (messageType !== MessageType.CALL_MESSAGE) {
-              return reject(ocppError);
-            }
-            // Reject and remove request from the cache
-            return errorCallback(ocppError, false);
           }
-          // Resolve response
-          if (messageType !== MessageType.CALL_MESSAGE) {
-            return resolve(messagePayload);
+          logger.debug(
+            `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${OCPPServiceUtils.getMessageTypeString(
+              messageType,
+            )} payload: ${messageToSend}`,
+          );
+          PerformanceStatistics.endMeasure(commandName, beginId);
+        } else {
+          if (params?.skipBufferingOnError === false) {
+            // Buffer
+            chargingStation.bufferMessage(messageToSend);
+            if (messageType === MessageType.CALL_MESSAGE) {
+              this.cacheRequestPromise(
+                chargingStation,
+                messageId,
+                messagePayload as JsonType,
+                commandName,
+                responseCallback,
+                errorCallback,
+              );
+            }
           }
-        }),
-        OCPPConstants.OCPP_WEBSOCKET_TIMEOUT,
-        new OCPPError(
-          ErrorType.GENERIC_ERROR,
-          `Timeout for message id '${messageId}'`,
-          commandName,
-          (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FROZEN_OBJECT,
-        ),
-        () => {
-          messageType === MessageType.CALL_MESSAGE && chargingStation.requests.delete(messageId);
-        },
-      );
+          // Reject and keep request in the cache
+          return reject(
+            new OCPPError(
+              ErrorType.GENERIC_ERROR,
+              `WebSocket closed for ${
+                params?.skipBufferingOnError === false ? '' : 'non '
+              }buffered message id '${messageId}' with content '${messageToSend}'`,
+              commandName,
+              (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FROZEN_OBJECT,
+            ),
+          );
+        }
+        // Resolve response
+        if (messageType !== MessageType.CALL_MESSAGE) {
+          return resolve(messagePayload);
+        }
+      });
     }
     throw new OCPPError(
       ErrorType.SECURITY_ERROR,
@@ -474,8 +482,6 @@ export abstract class OCPPRequestService {
     messagePayload: JsonType | OCPPError,
     messageType: MessageType,
     commandName: RequestCommand | IncomingRequestCommand,
-    responseCallback: ResponseCallback,
-    errorCallback: ErrorCallback,
   ): string {
     let messageToSend: string;
     // Type of message
@@ -484,12 +490,6 @@ export abstract class OCPPRequestService {
       case MessageType.CALL_MESSAGE:
         // Build request
         this.validateRequestPayload(chargingStation, commandName, messagePayload as JsonType);
-        chargingStation.requests.set(messageId, [
-          responseCallback,
-          errorCallback,
-          commandName,
-          messagePayload as JsonType,
-        ]);
         messageToSend = JSON.stringify([
           messageType,
           messageId,
@@ -522,6 +522,22 @@ export abstract class OCPPRequestService {
     return messageToSend;
   }
 
+  private cacheRequestPromise(
+    chargingStation: ChargingStation,
+    messageId: string,
+    messagePayload: JsonType,
+    commandName: RequestCommand | IncomingRequestCommand,
+    responseCallback: ResponseCallback,
+    errorCallback: ErrorCallback,
+  ): void {
+    chargingStation.requests.set(messageId, [
+      responseCallback,
+      errorCallback,
+      commandName,
+      messagePayload,
+    ]);
+  }
+
   // eslint-disable-next-line @typescript-eslint/no-unused-vars
   public abstract requestHandler<ReqType extends JsonType, ResType extends JsonType>(
     chargingStation: ChargingStation,