- public async sendMessage(messageId: string, commandParams: any, messageType: MessageType, commandName: RequestCommand | IncomingRequestCommand): Promise<any> {
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- const self = this;
- // Send a message through wsConnection
- return new Promise((resolve: (value?: any | PromiseLike<any>) => void, reject: (reason?: any) => void) => {
- let messageToSend: string;
- // Type of message
- switch (messageType) {
- // Request
- case MessageType.CALL_MESSAGE:
- // Build request
- this.chargingStation.requests[messageId] = [responseCallback, rejectCallback, commandParams as Record<string, unknown>];
- messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]);
- break;
- // Response
- case MessageType.CALL_RESULT_MESSAGE:
- // Build response
- messageToSend = JSON.stringify([messageType, messageId, commandParams]);
- break;
- // Error Message
- case MessageType.CALL_ERROR_MESSAGE:
- // Build Error Message
- messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]);
- break;
- }
- // Check if wsConnection opened and charging station registered
- if (this.chargingStation.isWebSocketConnectionOpened() && (this.chargingStation.isRegistered() || commandName === RequestCommand.BOOT_NOTIFICATION)) {
- if (this.chargingStation.getEnableStatistics()) {
- this.chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
+ public static getInstance<T extends OCPPRequestService>(
+ this: new (ocppResponseService: OCPPResponseService) => T,
+ ocppResponseService: OCPPResponseService
+ ): T {
+ if (OCPPRequestService.instance === null) {
+ OCPPRequestService.instance = new this(ocppResponseService)
+ }
+ return OCPPRequestService.instance as T
+ }
+
+ public async sendResponse (
+ chargingStation: ChargingStation,
+ messageId: string,
+ messagePayload: JsonType,
+ commandName: IncomingRequestCommand
+ ): Promise<ResponseType> {
+ try {
+ // Send response message
+ return await this.internalSendMessage(
+ chargingStation,
+ messageId,
+ messagePayload,
+ MessageType.CALL_RESULT_MESSAGE,
+ commandName
+ )
+ } catch (error) {
+ handleSendMessageError(chargingStation, commandName, error as Error, {
+ throwError: true
+ })
+ return null
+ }
+ }
+
+ public async sendError (
+ chargingStation: ChargingStation,
+ messageId: string,
+ ocppError: OCPPError,
+ commandName: RequestCommand | IncomingRequestCommand
+ ): Promise<ResponseType> {
+ try {
+ // Send error message
+ return await this.internalSendMessage(
+ chargingStation,
+ messageId,
+ ocppError,
+ MessageType.CALL_ERROR_MESSAGE,
+ commandName
+ )
+ } catch (error) {
+ handleSendMessageError(chargingStation, commandName, error as Error)
+ return null
+ }
+ }
+
+ protected async sendMessage (
+ chargingStation: ChargingStation,
+ messageId: string,
+ messagePayload: JsonType,
+ commandName: RequestCommand,
+ params?: RequestParams
+ ): Promise<ResponseType> {
+ params = {
+ ...defaultRequestParams,
+ ...params
+ }
+ try {
+ return await this.internalSendMessage(
+ chargingStation,
+ messageId,
+ messagePayload,
+ MessageType.CALL_MESSAGE,
+ commandName,
+ params
+ )
+ } catch (error) {
+ handleSendMessageError(chargingStation, commandName, error as Error, {
+ throwError: params.throwError
+ })
+ return null
+ }
+ }
+
+ private validateRequestPayload<T extends JsonType>(
+ chargingStation: ChargingStation,
+ commandName: RequestCommand | IncomingRequestCommand,
+ payload: T
+ ): boolean {
+ if (chargingStation.stationInfo?.ocppStrictCompliance === false) {
+ return true
+ }
+ if (!this.payloadValidateFunctions.has(commandName as RequestCommand)) {
+ logger.warn(
+ `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: No JSON schema found for command '${commandName}' PDU validation`
+ )
+ return true
+ }
+ const validate = this.payloadValidateFunctions.get(commandName as RequestCommand)
+ payload = clone<T>(payload)
+ OCPPServiceUtils.convertDateToISOString<T>(payload)
+ if (validate?.(payload) === true) {
+ return true
+ }
+ logger.error(
+ `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Command '${commandName}' 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, undefined, 2)
+ )
+ }
+
+ private validateIncomingRequestResponsePayload<T extends JsonType>(
+ chargingStation: ChargingStation,
+ commandName: RequestCommand | IncomingRequestCommand,
+ payload: T
+ ): boolean {
+ if (chargingStation.stationInfo?.ocppStrictCompliance === false) {
+ return true
+ }
+ if (
+ !this.ocppResponseService.incomingRequestResponsePayloadValidateFunctions.has(
+ commandName as IncomingRequestCommand
+ )
+ ) {
+ logger.warn(
+ `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
+ )
+ return true
+ }
+ const validate = this.ocppResponseService.incomingRequestResponsePayloadValidateFunctions.get(
+ commandName as IncomingRequestCommand
+ )
+ payload = clone<T>(payload)
+ OCPPServiceUtils.convertDateToISOString<T>(payload)
+ if (validate?.(payload) === true) {
+ return true
+ }
+ logger.error(
+ `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: Command '${commandName}' response 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),
+ 'Response PDU is invalid',
+ commandName,
+ JSON.stringify(validate?.errors, undefined, 2)
+ )
+ }
+
+ private async internalSendMessage (
+ chargingStation: ChargingStation,
+ messageId: string,
+ messagePayload: JsonType | OCPPError,
+ messageType: MessageType,
+ commandName: RequestCommand | IncomingRequestCommand,
+ params?: RequestParams
+ ): Promise<ResponseType> {
+ params = {
+ ...defaultRequestParams,
+ ...params
+ }
+ if (
+ (chargingStation.inUnknownState() && commandName === RequestCommand.BOOT_NOTIFICATION) ||
+ (chargingStation.stationInfo?.ocppStrictCompliance === false &&
+ chargingStation.inUnknownState()) ||
+ chargingStation.inAcceptedState() ||
+ (chargingStation.inPendingState() &&
+ (params.triggerMessage === true || messageType === MessageType.CALL_RESULT_MESSAGE))
+ ) {
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
+ const self = this
+ // Send a message through wsConnection
+ 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
+ )
+ }
+ // Handle the request's response
+ self.ocppResponseService
+ .responseHandler(
+ chargingStation,
+ commandName as RequestCommand,
+ payload,
+ requestPayload
+ )
+ .then(() => {
+ resolve(payload)
+ })
+ .catch(reject)
+ .finally(() => {
+ chargingStation.requests.delete(messageId)
+ chargingStation.emit(ChargingStationEvents.updated)
+ })
+ }
+
+ /**
+ * Function that will receive the request's error response
+ *
+ * @param ocppError -
+ * @param requestStatistic -
+ */
+ const errorCallback = (ocppError: OCPPError, requestStatistic = true): void => {
+ if (requestStatistic && 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,
+ ocppError
+ )
+ chargingStation.requests.delete(messageId)
+ chargingStation.emit(ChargingStationEvents.updated)
+ 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
+ )
+ }
+ } else if (
+ params?.skipBufferingOnError === true &&
+ messageType === MessageType.CALL_MESSAGE
+ ) {
+ // Remove request from the cache
+ chargingStation.requests.delete(messageId)
+ }
+ reject(ocppError)