X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2Focpp%2FOCPPRequestService.ts;h=c089c86a1af4092dd57e1deb281dab48c9d7769a;hb=b0342994636646699094b2d16a767d6d902d2bde;hp=f8b6b227a90b3936e3a167d9f22f91ef21138fd5;hpb=5cc4b63bd363814ddc657bd4c9b407e5eb3150cb;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ocpp/OCPPRequestService.ts b/src/charging-station/ocpp/OCPPRequestService.ts index f8b6b227..c089c86a 100644 --- a/src/charging-station/ocpp/OCPPRequestService.ts +++ b/src/charging-station/ocpp/OCPPRequestService.ts @@ -1,60 +1,66 @@ -import { ErrorResponse, Response } from '../../types/ocpp/Responses'; +import Ajv, { type JSONSchemaType } from 'ajv'; +import ajvFormats from 'ajv-formats'; + +import OCPPError from '../../exception/OCPPError'; +import PerformanceStatistics from '../../performance/PerformanceStatistics'; +import type { EmptyObject } from '../../types/EmptyObject'; +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 { - IncomingRequestCommand, - OutgoingRequest, + type ErrorCallback, + type IncomingRequestCommand, + type OutgoingRequest, RequestCommand, - RequestParams, - ResponseType, + type RequestParams, + type ResponseCallback, + type ResponseType, } from '../../types/ocpp/Requests'; -import { JsonObject, JsonType } from '../../types/JsonType'; - -import type ChargingStation from '../ChargingStation'; +import type { ErrorResponse, Response } from '../../types/ocpp/Responses'; import Constants from '../../utils/Constants'; -import { EmptyObject } from '../../types/EmptyObject'; -import { ErrorType } from '../../types/ocpp/ErrorType'; -import { HandleErrorParams } from '../../types/Error'; -import { MessageType } from '../../types/ocpp/MessageType'; -import OCPPError from '../../exception/OCPPError'; -import type OCPPResponseService from './OCPPResponseService'; -import PerformanceStatistics from '../../performance/PerformanceStatistics'; -import Utils from '../../utils/Utils'; 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'; export default abstract class OCPPRequestService { - private static readonly instances: Map = new Map< - string, - OCPPRequestService - >(); + private static instance: OCPPRequestService | null = null; + private readonly version: OCPPVersion; + private readonly ajv: Ajv; - protected readonly chargingStation: ChargingStation; private readonly ocppResponseService: OCPPResponseService; - protected constructor( - chargingStation: ChargingStation, - ocppResponseService: OCPPResponseService - ) { - this.chargingStation = chargingStation; + protected constructor(version: OCPPVersion, ocppResponseService: OCPPResponseService) { + this.version = version; + this.ajv = new Ajv(); + ajvFormats(this.ajv); this.ocppResponseService = ocppResponseService; this.requestHandler.bind(this); + this.sendMessage.bind(this); this.sendResponse.bind(this); this.sendError.bind(this); + this.internalSendMessage.bind(this); + this.buildMessageToSend.bind(this); + this.validateRequestPayload.bind(this); } public static getInstance( - this: new (chargingStation: ChargingStation, ocppResponseService: OCPPResponseService) => T, - chargingStation: ChargingStation, + this: new (ocppResponseService: OCPPResponseService) => T, ocppResponseService: OCPPResponseService ): T { - if (!OCPPRequestService.instances.has(chargingStation.hashId)) { - OCPPRequestService.instances.set( - chargingStation.hashId, - new this(chargingStation, ocppResponseService) - ); + if (OCPPRequestService.instance === null) { + OCPPRequestService.instance = new this(ocppResponseService); } - return OCPPRequestService.instances.get(chargingStation.hashId) as T; + return OCPPRequestService.instance as T; } public async sendResponse( + chargingStation: ChargingStation, messageId: string, messagePayload: JsonType, commandName: IncomingRequestCommand @@ -62,17 +68,21 @@ export default abstract class OCPPRequestService { try { // Send response message return await this.internalSendMessage( + chargingStation, messageId, messagePayload, MessageType.CALL_RESULT_MESSAGE, commandName ); } catch (error) { - this.handleRequestError(commandName, error as Error); + this.handleSendMessageError(chargingStation, commandName, error as Error, { + throwError: true, + }); } } public async sendError( + chargingStation: ChargingStation, messageId: string, ocppError: OCPPError, commandName: RequestCommand | IncomingRequestCommand @@ -80,17 +90,19 @@ export default abstract class OCPPRequestService { try { // Send error message return await this.internalSendMessage( + chargingStation, messageId, ocppError, MessageType.CALL_ERROR_MESSAGE, commandName ); } catch (error) { - this.handleRequestError(commandName, error as Error); + this.handleSendMessageError(chargingStation, commandName, error as Error); } } protected async sendMessage( + chargingStation: ChargingStation, messageId: string, messagePayload: JsonType, commandName: RequestCommand, @@ -101,6 +113,7 @@ export default abstract class OCPPRequestService { ): Promise { try { return await this.internalSendMessage( + chargingStation, messageId, messagePayload, MessageType.CALL_MESSAGE, @@ -108,11 +121,38 @@ export default abstract class OCPPRequestService { params ); } catch (error) { - this.handleRequestError(commandName, error as Error, { throwError: false }); + this.handleSendMessageError(chargingStation, commandName, error as Error); } } + protected validateRequestPayload( + chargingStation: ChargingStation, + commandName: RequestCommand, + schema: JSONSchemaType, + payload: T + ): boolean { + if (chargingStation.getPayloadSchemaValidation() === false) { + return true; + } + const validate = this.ajv.compile(schema); + if (validate(payload)) { + return true; + } + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: 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(). + throw new OCPPError( + OCPPServiceUtils.ajvErrorsToErrorType(validate.errors), + 'Request PDU is invalid', + commandName, + JSON.stringify(validate.errors, null, 2) + ); + } + private async internalSendMessage( + chargingStation: ChargingStation, messageId: string, messagePayload: JsonType | OCPPError, messageType: MessageType, @@ -123,13 +163,13 @@ export default abstract class OCPPRequestService { } ): Promise { if ( - (this.chargingStation.isInUnknownState() && + (chargingStation.isInUnknownState() === true && commandName === RequestCommand.BOOT_NOTIFICATION) || - (!this.chargingStation.getOcppStrictCompliance() && - this.chargingStation.isInUnknownState()) || - this.chargingStation.isInAcceptedState() || - (this.chargingStation.isInPendingState() && - (params.triggerMessage || messageType === MessageType.CALL_RESULT_MESSAGE)) + (chargingStation.getOcppStrictCompliance() === false && + chargingStation.isInUnknownState() === true) || + chargingStation.isInAcceptedState() === true || + (chargingStation.isInPendingState() === true && + (params.triggerMessage === true || messageType === MessageType.CALL_RESULT_MESSAGE)) ) { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; @@ -137,6 +177,7 @@ export default abstract class OCPPRequestService { return Utils.promiseWithTimeout( new Promise((resolve, reject) => { const messageToSend = this.buildMessageToSend( + chargingStation, messageId, messagePayload, messageType, @@ -144,27 +185,24 @@ export default abstract class OCPPRequestService { responseCallback, errorCallback ); - if (this.chargingStation.getEnableStatistics()) { - this.chargingStation.performanceStatistics.addRequestStatistic( - commandName, - messageType - ); + if (chargingStation.getEnableStatistics() === true) { + chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType); } // Check if wsConnection opened - if (this.chargingStation.isWebSocketConnectionOpened()) { + if (chargingStation.isWebSocketConnectionOpened() === true) { // Yes: Send Message - const beginId = PerformanceStatistics.beginMeasure(commandName); + const beginId = PerformanceStatistics.beginMeasure(commandName as string); // FIXME: Handle sending error - this.chargingStation.wsConnection.send(messageToSend); - PerformanceStatistics.endMeasure(commandName, beginId); + chargingStation.wsConnection.send(messageToSend); + PerformanceStatistics.endMeasure(commandName as string, beginId); logger.debug( - `${this.chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString( + `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString( messageType )} payload: ${messageToSend}` ); - } else if (!params.skipBufferingOnError) { + } else if (params.skipBufferingOnError === false) { // Buffer it - this.chargingStation.bufferMessage(messageToSend); + chargingStation.bufferMessage(messageToSend); const ocppError = new OCPPError( ErrorType.GENERIC_ERROR, `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`, @@ -197,54 +235,55 @@ export default abstract class OCPPRequestService { /** * Function that will receive the request's response * - * @param payload - * @param requestPayload + * @param payload - + * @param requestPayload - */ - async function responseCallback( - payload: JsonType, - requestPayload: JsonType - ): Promise { - if (self.chargingStation.getEnableStatistics()) { - self.chargingStation.performanceStatistics.addRequestStatistic( + function responseCallback(payload: JsonType, requestPayload: JsonType): void { + if (chargingStation.getEnableStatistics() === true) { + chargingStation.performanceStatistics.addRequestStatistic( commandName, MessageType.CALL_RESULT_MESSAGE ); } // Handle the request's response - try { - await self.ocppResponseService.responseHandler( + self.ocppResponseService + .responseHandler( + chargingStation, commandName as RequestCommand, payload, requestPayload - ); - resolve(payload); - } catch (error) { - reject(error); - } finally { - self.chargingStation.requests.delete(messageId); - } + ) + .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 + * @param error - + * @param requestStatistic - */ function errorCallback(error: OCPPError, requestStatistic = true): void { - if (requestStatistic && self.chargingStation.getEnableStatistics()) { - self.chargingStation.performanceStatistics.addRequestStatistic( + if (requestStatistic === true && chargingStation.getEnableStatistics() === true) { + chargingStation.performanceStatistics.addRequestStatistic( commandName, MessageType.CALL_ERROR_MESSAGE ); } logger.error( - `${self.chargingStation.logPrefix()} Error %j occurred when calling command %s with message data %j`, - error, - commandName, - messagePayload + `${chargingStation.logPrefix()} Error occurred when calling command ${commandName} with message data ${JSON.stringify( + messagePayload + )}:`, + error ); - self.chargingStation.requests.delete(messageId); + chargingStation.requests.delete(messageId); reject(error); } }), @@ -256,25 +295,25 @@ export default abstract class OCPPRequestService { (messagePayload as JsonObject)?.details ?? {} ), () => { - messageType === MessageType.CALL_MESSAGE && - this.chargingStation.requests.delete(messageId); + messageType === MessageType.CALL_MESSAGE && chargingStation.requests.delete(messageId); } ); } throw new OCPPError( ErrorType.SECURITY_ERROR, - `Cannot send command ${commandName} payload when the charging station is in ${this.chargingStation.getRegistrationStatus()} state on the central server`, + `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`, commandName ); } private buildMessageToSend( + chargingStation: ChargingStation, messageId: string, messagePayload: JsonType | OCPPError, messageType: MessageType, commandName?: RequestCommand | IncomingRequestCommand, - responseCallback?: (payload: JsonType, requestPayload: JsonType) => Promise, - errorCallback?: (error: OCPPError, requestStatistic?: boolean) => void + responseCallback?: ResponseCallback, + errorCallback?: ErrorCallback ): string { let messageToSend: string; // Type of message @@ -282,7 +321,7 @@ export default abstract class OCPPRequestService { // Request case MessageType.CALL_MESSAGE: // Build request - this.chargingStation.requests.set(messageId, [ + chargingStation.requests.set(messageId, [ responseCallback, errorCallback, commandName, @@ -326,25 +365,23 @@ export default abstract class OCPPRequestService { } } - private handleRequestError( + private handleSendMessageError( + chargingStation: ChargingStation, commandName: RequestCommand | IncomingRequestCommand, error: Error, - params: HandleErrorParams = { throwError: true } + params: HandleErrorParams = { throwError: false } ): void { - logger.error( - this.chargingStation.logPrefix() + ' Request command %s error: %j', - commandName, - error - ); - if (params?.throwError) { + logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error); + if (params?.throwError === true) { throw error; } } // eslint-disable-next-line @typescript-eslint/no-unused-vars - public abstract requestHandler( + public abstract requestHandler( + chargingStation: ChargingStation, commandName: RequestCommand, commandParams?: JsonType, params?: RequestParams - ): Promise; + ): Promise; }