+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 { EmptyObject } from '../../types/EmptyObject';
-import { HandleErrorParams } from '../../types/Error';
-import { JsonObject, JsonType } from '../../types/JsonType';
+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 {
RequestParams,
ResponseType,
} from '../../types/ocpp/Requests';
-import { ErrorResponse, Response } from '../../types/ocpp/Responses';
+import type { ErrorResponse, Response } from '../../types/ocpp/Responses';
import Constants from '../../utils/Constants';
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 instance: OCPPRequestService | null = null;
+ private readonly ajv: Ajv;
private readonly ocppResponseService: OCPPResponseService;
protected constructor(ocppResponseService: OCPPResponseService) {
this.ocppResponseService = ocppResponseService;
+ this.ajv = new Ajv();
+ ajvFormats(this.ajv);
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<T extends OCPPRequestService>(
this: new (ocppResponseService: OCPPResponseService) => T,
ocppResponseService: OCPPResponseService
): T {
- if (!OCPPRequestService.instance) {
+ if (OCPPRequestService.instance === null) {
OCPPRequestService.instance = new this(ocppResponseService);
}
return OCPPRequestService.instance as T;
commandName
);
} catch (error) {
- this.handleRequestError(chargingStation, commandName, error as Error);
+ this.handleSendMessageError(chargingStation, commandName, error as Error, {
+ throwError: true,
+ });
}
}
commandName
);
} catch (error) {
- this.handleRequestError(chargingStation, commandName, error as Error);
+ this.handleSendMessageError(chargingStation, commandName, error as Error);
}
}
params
);
} catch (error) {
- this.handleRequestError(chargingStation, commandName, error as Error, { throwError: false });
+ this.handleSendMessageError(chargingStation, commandName, error as Error);
}
}
+ protected validateRequestPayload<T extends JsonType>(
+ chargingStation: ChargingStation,
+ commandName: RequestCommand,
+ schema: JSONSchemaType<T>,
+ 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,
}
): Promise<ResponseType> {
if (
- (chargingStation.isInUnknownState() && commandName === RequestCommand.BOOT_NOTIFICATION) ||
- (!chargingStation.getOcppStrictCompliance() && chargingStation.isInUnknownState()) ||
- chargingStation.isInAcceptedState() ||
- (chargingStation.isInPendingState() &&
- (params.triggerMessage || messageType === MessageType.CALL_RESULT_MESSAGE))
+ (chargingStation.isInUnknownState() === true &&
+ commandName === RequestCommand.BOOT_NOTIFICATION) ||
+ (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;
responseCallback,
errorCallback
);
- if (chargingStation.getEnableStatistics()) {
+ if (chargingStation.getEnableStatistics() === true) {
chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
}
// Check if wsConnection opened
- if (chargingStation.isWebSocketConnectionOpened()) {
+ if (chargingStation.isWebSocketConnectionOpened() === true) {
// Yes: Send Message
const beginId = PerformanceStatistics.beginMeasure(commandName);
// FIXME: Handle sending error
messageType
)} payload: ${messageToSend}`
);
- } else if (!params.skipBufferingOnError) {
+ } else if (params.skipBufferingOnError === false) {
// Buffer it
chargingStation.bufferMessage(messageToSend);
const ocppError = new OCPPError(
payload: JsonType,
requestPayload: JsonType
): Promise<void> {
- if (chargingStation.getEnableStatistics()) {
+ if (chargingStation.getEnableStatistics() === true) {
chargingStation.performanceStatistics.addRequestStatistic(
commandName,
MessageType.CALL_RESULT_MESSAGE
* @param requestStatistic
*/
function errorCallback(error: OCPPError, requestStatistic = true): void {
- if (requestStatistic && chargingStation.getEnableStatistics()) {
+ if (requestStatistic === true && chargingStation.getEnableStatistics() === true) {
chargingStation.performanceStatistics.addRequestStatistic(
commandName,
MessageType.CALL_ERROR_MESSAGE
);
}
logger.error(
- `${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
);
chargingStation.requests.delete(messageId);
reject(error);
}
}
- private handleRequestError(
+ private handleSendMessageError(
chargingStation: ChargingStation,
commandName: RequestCommand | IncomingRequestCommand,
error: Error,
- params: HandleErrorParams<EmptyObject> = { throwError: true }
+ params: HandleErrorParams<EmptyObject> = { throwError: false }
): void {
- logger.error(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<Request extends JsonType, Response extends JsonType>(
+ public abstract requestHandler<RequestType extends JsonType, ResponseType extends JsonType>(
chargingStation: ChargingStation,
commandName: RequestCommand,
commandParams?: JsonType,
params?: RequestParams
- ): Promise<Response>;
+ ): Promise<ResponseType>;
}