X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2Focpp%2FOCPPRequestService.ts;h=e78ca0c6dfa4d8fcec3049d05b67a11d62df82de;hb=0afed85fd7e6cb8f4b5ea0d18800a8d7b3bd78a7;hp=e906daf8a45169f485cebfe69532a8365160c7b4;hpb=a2d1c0f1f3008198a96d932bab7c933c084ffeca;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ocpp/OCPPRequestService.ts b/src/charging-station/ocpp/OCPPRequestService.ts index e906daf8..e78ca0c6 100644 --- a/src/charging-station/ocpp/OCPPRequestService.ts +++ b/src/charging-station/ocpp/OCPPRequestService.ts @@ -1,4 +1,14 @@ -import { ErrorResponse, Response } from '../../types/ocpp/Responses'; +import type { JSONSchemaType } from 'ajv'; +import Ajv from 'ajv-draft-04'; +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 { IncomingRequestCommand, OutgoingRequest, @@ -6,55 +16,46 @@ import { RequestParams, ResponseType, } from '../../types/ocpp/Requests'; - -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 { JsonType } from '../../types/JsonType'; -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 ajv: Ajv; - protected readonly chargingStation: ChargingStation; private readonly ocppResponseService: OCPPResponseService; - protected constructor( - chargingStation: ChargingStation, - ocppResponseService: OCPPResponseService - ) { - this.chargingStation = chargingStation; + protected constructor(ocppResponseService: OCPPResponseService) { this.ocppResponseService = ocppResponseService; + this.ajv = new Ajv(); + ajvFormats(this.ajv); this.requestHandler.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 +63,19 @@ 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.handleRequestError(chargingStation, commandName, error as Error); } } public async sendError( + chargingStation: ChargingStation, messageId: string, ocppError: OCPPError, commandName: RequestCommand | IncomingRequestCommand @@ -80,17 +83,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.handleRequestError(chargingStation, commandName, error as Error); } } protected async sendMessage( + chargingStation: ChargingStation, messageId: string, messagePayload: JsonType, commandName: RequestCommand, @@ -101,6 +106,7 @@ export default abstract class OCPPRequestService { ): Promise { try { return await this.internalSendMessage( + chargingStation, messageId, messagePayload, MessageType.CALL_MESSAGE, @@ -108,11 +114,37 @@ export default abstract class OCPPRequestService { params ); } catch (error) { - this.handleRequestError(commandName, error as Error, { throwError: false }); + this.handleRequestError(chargingStation, commandName, error as Error, { throwError: false }); + } + } + + protected validateRequestPayload( + chargingStation: ChargingStation, + commandName: RequestCommand, + schema: JSONSchemaType, + payload: T + ): boolean { + if (!chargingStation.getPayloadSchemaValidation()) { + 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 + ); + 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,12 +155,10 @@ export default abstract class OCPPRequestService { } ): Promise { if ( - (this.chargingStation.isInUnknownState() && - commandName === RequestCommand.BOOT_NOTIFICATION) || - (!this.chargingStation.getOcppStrictCompliance() && - this.chargingStation.isInUnknownState()) || - this.chargingStation.isInAcceptedState() || - (this.chargingStation.isInPendingState() && + (chargingStation.isInUnknownState() && commandName === RequestCommand.BOOT_NOTIFICATION) || + (!chargingStation.getOcppStrictCompliance() && chargingStation.isInUnknownState()) || + chargingStation.isInAcceptedState() || + (chargingStation.isInPendingState() && (params.triggerMessage || messageType === MessageType.CALL_RESULT_MESSAGE)) ) { // eslint-disable-next-line @typescript-eslint/no-this-alias @@ -137,6 +167,7 @@ export default abstract class OCPPRequestService { return Utils.promiseWithTimeout( new Promise((resolve, reject) => { const messageToSend = this.buildMessageToSend( + chargingStation, messageId, messagePayload, messageType, @@ -144,32 +175,29 @@ export default abstract class OCPPRequestService { responseCallback, errorCallback ); - if (this.chargingStation.getEnableStatistics()) { - this.chargingStation.performanceStatistics.addRequestStatistic( - commandName, - messageType - ); + if (chargingStation.getEnableStatistics()) { + chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType); } // Check if wsConnection opened - if (this.chargingStation.isWebSocketConnectionOpened()) { + if (chargingStation.isWebSocketConnectionOpened()) { // Yes: Send Message const beginId = PerformanceStatistics.beginMeasure(commandName); // FIXME: Handle sending error - this.chargingStation.wsConnection.send(messageToSend); + chargingStation.wsConnection.send(messageToSend); PerformanceStatistics.endMeasure(commandName, 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) { // 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}'`, commandName, - (messagePayload?.details as JsonType) ?? {} + (messagePayload as JsonObject)?.details ?? {} ); if (messageType === MessageType.CALL_MESSAGE) { // Reject it but keep the request in the cache @@ -183,7 +211,7 @@ export default abstract class OCPPRequestService { ErrorType.GENERIC_ERROR, `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`, commandName, - (messagePayload?.details as JsonType) ?? {} + (messagePayload as JsonObject)?.details ?? {} ), false ); @@ -204,8 +232,8 @@ export default abstract class OCPPRequestService { payload: JsonType, requestPayload: JsonType ): Promise { - if (self.chargingStation.getEnableStatistics()) { - self.chargingStation.performanceStatistics.addRequestStatistic( + if (chargingStation.getEnableStatistics()) { + chargingStation.performanceStatistics.addRequestStatistic( commandName, MessageType.CALL_RESULT_MESSAGE ); @@ -213,6 +241,7 @@ export default abstract class OCPPRequestService { // Handle the request's response try { await self.ocppResponseService.responseHandler( + chargingStation, commandName as RequestCommand, payload, requestPayload @@ -221,7 +250,7 @@ export default abstract class OCPPRequestService { } catch (error) { reject(error); } finally { - self.chargingStation.requests.delete(messageId); + chargingStation.requests.delete(messageId); } } @@ -232,19 +261,19 @@ export default abstract class OCPPRequestService { * @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); } }), @@ -253,22 +282,22 @@ export default abstract class OCPPRequestService { ErrorType.GENERIC_ERROR, `Timeout for message id '${messageId}'`, commandName, - (messagePayload?.details as JsonType) ?? {} + (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, @@ -282,7 +311,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, @@ -327,24 +356,22 @@ export default abstract class OCPPRequestService { } private handleRequestError( + chargingStation: ChargingStation, commandName: RequestCommand | IncomingRequestCommand, error: Error, params: HandleErrorParams = { throwError: true } ): void { - logger.error( - this.chargingStation.logPrefix() + ' Request command %s error: %j', - commandName, - error - ); + logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error); if (params?.throwError) { 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; }