- public async sendMessage(messageId: string, commandParams: any, messageType: MessageType, commandName: RequestCommand | IncomingRequestCommand,
- skipBufferingOnError = false): Promise<unknown> {
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- const self = this;
- // Send a message through wsConnection
- return new Promise((resolve, reject) => {
- const messageToSend = this.buildMessageToSend(messageId, commandParams, messageType, commandName, responseCallback, rejectCallback);
- if (this.chargingStation.getEnableStatistics()) {
- this.chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
- }
- // Check if wsConnection opened
- if (this.chargingStation.isWebSocketConnectionOpened()) {
- // Yes: Send Message
- const beginId = PerformanceStatistics.beginMeasure(commandName);
- this.chargingStation.wsConnection.send(messageToSend);
- PerformanceStatistics.endMeasure(commandName, beginId);
- } else if (!skipBufferingOnError) {
- // Buffer it
- this.chargingStation.addToMessageQueue(messageToSend);
- // Reject it but keep the request in the cache
- reject(new OCPPError(commandParams?.code ?? ErrorType.GENERIC_ERROR, commandParams?.message ?? `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams?.details ?? {}));
- }
- // Response?
- if (messageType !== MessageType.CALL_MESSAGE) {
- // Yes: send Ok
- resolve(commandName);
- } else {
- // Send timeout
- setTimeout(() => rejectCallback(new OCPPError(commandParams?.code ?? ErrorType.GENERIC_ERROR, commandParams?.message ?? `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams?.details ?? {})), Constants.OCPP_SOCKET_TIMEOUT);
- }
-
- /**
- * Function that will receive the request's response
- *
- * @param payload
- * @param requestPayload
- */
- async function responseCallback(payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>): Promise<void> {
- if (self.chargingStation.getEnableStatistics()) {
- self.chargingStation.performanceStatistics.addRequestStatistic(commandName, MessageType.CALL_RESULT_MESSAGE);
+ 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: (reason?: unknown) => void) => {
+ /**
+ * 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)
+ })