X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;ds=sidebyside;f=src%2Fcharging-station%2Focpp%2FOCPPRequestService.ts;h=07793a8fd7f5ba498cb5a23581f6d60a84d4c019;hb=9aa1a33f94dfe5b96a4715f87fb630a63b3250a6;hp=69fb503eaf303beee1378157fce587c25393bc9b;hpb=0b0ca54f0a74240531646827584b7c2738aa7ea1;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ocpp/OCPPRequestService.ts b/src/charging-station/ocpp/OCPPRequestService.ts index 69fb503e..07793a8f 100644 --- a/src/charging-station/ocpp/OCPPRequestService.ts +++ b/src/charging-station/ocpp/OCPPRequestService.ts @@ -12,7 +12,6 @@ import { type ErrorResponse, ErrorType, type IncomingRequestCommand, - type JsonObject, type JsonType, MessageType, type OCPPVersion, @@ -24,11 +23,11 @@ import { type ResponseType, } from '../../types'; import { - Constants, cloneObject, + formatDurationMilliSeconds, handleSendMessageError, + isNullOrUndefined, logger, - promiseWithTimeout, } from '../../utils'; const moduleName = 'OCPPRequestService'; @@ -99,8 +98,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 ( chargingStation: ChargingStation, @@ -321,145 +318,160 @@ 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((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 new Promise((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(reject) + .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 ocppError - + * @param requestStatistic - + */ + const errorCallback = (ocppError: 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, + ocppError, ); - 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, + chargingStation.requests.delete(messageId); + reject(ocppError); + }; + + const handleSendError = (ocppError: OCPPError): void => { + if (params?.skipBufferingOnError === false) { + // Buffer + chargingStation.bufferMessage(messageToSend); + if (messageType === MessageType.CALL_MESSAGE) { + this.cacheRequestPromise( + chargingStation, + messageId, + messagePayload as JsonType, + commandName, + responseCallback, + errorCallback, ); - sendError = true; } - PerformanceStatistics.endMeasure(commandName, beginId); + } else if ( + params?.skipBufferingOnError === true && + messageType === MessageType.CALL_MESSAGE + ) { + // Remove request from the cache + chargingStation.requests.delete(messageId); } - const wsClosedOrErrored = !wsOpened || sendError === true; - if (wsClosedOrErrored && params?.skipBufferingOnError === false) { - // Buffer - chargingStation.bufferMessage(messageToSend); - // Reject and keep request in the cache - return reject( + return reject(ocppError); + }; + + 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 handleSendError( new OCPPError( ErrorType.GENERIC_ERROR, - `WebSocket closed or errored for buffered message id '${messageId}' with content '${messageToSend}'`, + `Timeout ${formatDurationMilliSeconds( + OCPPConstants.OCPP_WEBSOCKET_TIMEOUT, + )} reached for ${ + params?.skipBufferingOnError === false ? '' : 'non ' + }buffered message id '${messageId}' with content '${messageToSend}`, commandName, - (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FROZEN_OBJECT, + (messagePayload as OCPPError).details, ), ); - } else if (wsClosedOrErrored) { - const ocppError = new OCPPError( + }, OCPPConstants.OCPP_WEBSOCKET_TIMEOUT); + chargingStation.wsConnection?.send(messageToSend, (error?: Error) => { + PerformanceStatistics.endMeasure(commandName, beginId); + clearTimeout(sendTimeout); + if (isNullOrUndefined(error)) { + logger.debug( + `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${OCPPServiceUtils.getMessageTypeString( + messageType, + )} payload: ${messageToSend}`, + ); + if (messageType === MessageType.CALL_MESSAGE) { + this.cacheRequestPromise( + chargingStation, + messageId, + messagePayload as JsonType, + commandName, + responseCallback, + errorCallback, + ); + } else { + // Resolve response + return resolve(messagePayload); + } + } else if (error) { + return handleSendError( + 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 }, + ), + ); + } + }); + } else { + return handleSendError( + new OCPPError( ErrorType.GENERIC_ERROR, - `WebSocket closed or errored for non buffered message id '${messageId}' with content '${messageToSend}'`, + `WebSocket closed for ${ + params?.skipBufferingOnError === false ? '' : 'non ' + }buffered message id '${messageId}' with content '${messageToSend}'`, commandName, - (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FROZEN_OBJECT, - ); - // 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); - } - }), - 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); - }, - ); + (messagePayload as OCPPError).details, + ), + ); + } + }); } throw new OCPPError( ErrorType.SECURITY_ERROR, @@ -474,8 +486,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 +494,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, @@ -513,15 +517,33 @@ export abstract class OCPPRequestService { messageToSend = JSON.stringify([ messageType, messageId, - (messagePayload as OCPPError)?.code ?? ErrorType.GENERIC_ERROR, - (messagePayload as OCPPError)?.message ?? '', - (messagePayload as OCPPError)?.details ?? { commandName }, + (messagePayload as OCPPError).code, + (messagePayload as OCPPError).message, + (messagePayload as OCPPError).details ?? { + command: (messagePayload as OCPPError).command ?? commandName, + }, ] as ErrorResponse); break; } 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( chargingStation: ChargingStation,