1 import Ajv
, { type JSONSchemaType
} from
'ajv';
2 import ajvFormats from
'ajv-formats';
4 import OCPPError from
'../../exception/OCPPError';
5 import PerformanceStatistics from
'../../performance/PerformanceStatistics';
6 import type { EmptyObject
} from
'../../types/EmptyObject';
7 import type { HandleErrorParams
} from
'../../types/Error';
8 import type { JsonObject
, JsonType
} from
'../../types/JsonType';
9 import { ErrorType
} from
'../../types/ocpp/ErrorType';
10 import { MessageType
} from
'../../types/ocpp/MessageType';
11 import type { OCPPVersion
} from
'../../types/ocpp/OCPPVersion';
14 type IncomingRequestCommand
,
18 type ResponseCallback
,
20 } from
'../../types/ocpp/Requests';
21 import type { ErrorResponse
, Response
} from
'../../types/ocpp/Responses';
22 import Constants from
'../../utils/Constants';
23 import logger from
'../../utils/Logger';
24 import Utils from
'../../utils/Utils';
25 import type ChargingStation from
'../ChargingStation';
26 import type OCPPResponseService from
'./OCPPResponseService';
27 import { OCPPServiceUtils
} from
'./OCPPServiceUtils';
29 const moduleName
= 'OCPPRequestService';
31 export default abstract class OCPPRequestService
{
32 private static instance
: OCPPRequestService
| null = null;
33 private readonly version
: OCPPVersion
;
34 private readonly ajv
: Ajv
;
35 private readonly ocppResponseService
: OCPPResponseService
;
36 protected abstract jsonSchemas
: Map
<RequestCommand
, JSONSchemaType
<JsonObject
>>;
38 protected constructor(version
: OCPPVersion
, ocppResponseService
: OCPPResponseService
) {
39 this.version
= version
;
41 keywords
: ['javaType'],
42 multipleOfPrecision
: 2,
45 this.ocppResponseService
= ocppResponseService
;
46 this.requestHandler
.bind(this);
47 this.sendMessage
.bind(this);
48 this.sendResponse
.bind(this);
49 this.sendError
.bind(this);
50 this.internalSendMessage
.bind(this);
51 this.buildMessageToSend
.bind(this);
52 this.validateRequestPayload
.bind(this);
53 this.validateIncomingRequestResponsePayload
.bind(this);
56 public static getInstance
<T
extends OCPPRequestService
>(
57 this: new (ocppResponseService
: OCPPResponseService
) => T
,
58 ocppResponseService
: OCPPResponseService
60 if (OCPPRequestService
.instance
=== null) {
61 OCPPRequestService
.instance
= new this(ocppResponseService
);
63 return OCPPRequestService
.instance
as T
;
66 public async sendResponse(
67 chargingStation
: ChargingStation
,
69 messagePayload
: JsonType
,
70 commandName
: IncomingRequestCommand
71 ): Promise
<ResponseType
> {
73 // Send response message
74 return await this.internalSendMessage(
78 MessageType
.CALL_RESULT_MESSAGE
,
82 this.handleSendMessageError(chargingStation
, commandName
, error
as Error, {
88 public async sendError(
89 chargingStation
: ChargingStation
,
92 commandName
: RequestCommand
| IncomingRequestCommand
93 ): Promise
<ResponseType
> {
96 return await this.internalSendMessage(
100 MessageType
.CALL_ERROR_MESSAGE
,
104 this.handleSendMessageError(chargingStation
, commandName
, error
as Error);
108 protected async sendMessage(
109 chargingStation
: ChargingStation
,
111 messagePayload
: JsonType
,
112 commandName
: RequestCommand
,
113 params
: RequestParams
= {
114 skipBufferingOnError
: false,
115 triggerMessage
: false,
117 ): Promise
<ResponseType
> {
119 return await this.internalSendMessage(
123 MessageType
.CALL_MESSAGE
,
128 this.handleSendMessageError(chargingStation
, commandName
, error
as Error);
132 private validateRequestPayload
<T
extends JsonObject
>(
133 chargingStation
: ChargingStation
,
134 commandName
: RequestCommand
| IncomingRequestCommand
,
137 if (chargingStation
.getPayloadSchemaValidation() === false) {
140 if (this.jsonSchemas
.has(commandName
as RequestCommand
) === false) {
142 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: No JSON schema found for command '${commandName}' PDU validation`
146 const validate
= this.ajv
.compile(this.jsonSchemas
.get(commandName
as RequestCommand
));
147 payload
= Utils
.cloneObject
<T
>(payload
);
148 OCPPServiceUtils
.convertDateToISOString
<T
>(payload
);
149 if (validate(payload
)) {
153 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Command '${commandName}' request PDU is invalid: %j`,
156 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
158 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
),
159 'Request PDU is invalid',
161 JSON
.stringify(validate
.errors
, null, 2)
165 private validateIncomingRequestResponsePayload
<T
extends JsonObject
>(
166 chargingStation
: ChargingStation
,
167 commandName
: RequestCommand
| IncomingRequestCommand
,
170 if (chargingStation
.getPayloadSchemaValidation() === false) {
174 this.ocppResponseService
.jsonIncomingRequestResponseSchemas
.has(
175 commandName
as IncomingRequestCommand
179 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: No JSON schema found for command '${commandName}' PDU validation`
183 const validate
= this.ajv
.compile(
184 this.ocppResponseService
.jsonIncomingRequestResponseSchemas
.get(
185 commandName
as IncomingRequestCommand
188 payload
= Utils
.cloneObject
<T
>(payload
);
189 OCPPServiceUtils
.convertDateToISOString
<T
>(payload
);
190 if (validate(payload
)) {
194 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: Command '${commandName}' reponse PDU is invalid: %j`,
197 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
199 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
),
200 'Response PDU is invalid',
202 JSON
.stringify(validate
.errors
, null, 2)
206 private async internalSendMessage(
207 chargingStation
: ChargingStation
,
209 messagePayload
: JsonType
| OCPPError
,
210 messageType
: MessageType
,
211 commandName
?: RequestCommand
| IncomingRequestCommand
,
212 params
: RequestParams
= {
213 skipBufferingOnError
: false,
214 triggerMessage
: false,
216 ): Promise
<ResponseType
> {
218 (chargingStation
.isInUnknownState() === true &&
219 commandName
=== RequestCommand
.BOOT_NOTIFICATION
) ||
220 (chargingStation
.getOcppStrictCompliance() === false &&
221 chargingStation
.isInUnknownState() === true) ||
222 chargingStation
.isInAcceptedState() === true ||
223 (chargingStation
.isInPendingState() === true &&
224 (params
.triggerMessage
=== true || messageType
=== MessageType
.CALL_RESULT_MESSAGE
))
226 // eslint-disable-next-line @typescript-eslint/no-this-alias
228 // Send a message through wsConnection
229 return Utils
.promiseWithTimeout(
230 new Promise((resolve
, reject
) => {
231 const messageToSend
= this.buildMessageToSend(
240 if (chargingStation
.getEnableStatistics() === true) {
241 chargingStation
.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
243 // Check if wsConnection opened
244 if (chargingStation
.isWebSocketConnectionOpened() === true) {
246 const beginId
= PerformanceStatistics
.beginMeasure(commandName
as string);
247 // FIXME: Handle sending error
248 chargingStation
.wsConnection
.send(messageToSend
);
249 PerformanceStatistics
.endMeasure(commandName
as string, beginId
);
251 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
253 )} payload: ${messageToSend}`
255 } else if (params
.skipBufferingOnError
=== false) {
257 chargingStation
.bufferMessage(messageToSend
);
258 const ocppError
= new OCPPError(
259 ErrorType
.GENERIC_ERROR
,
260 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
262 (messagePayload
as JsonObject
)?.details
?? {}
264 if (messageType
=== MessageType
.CALL_MESSAGE
) {
265 // Reject it but keep the request in the cache
266 return reject(ocppError
);
268 return errorCallback(ocppError
, false);
271 return errorCallback(
273 ErrorType
.GENERIC_ERROR
,
274 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
276 (messagePayload
as JsonObject
)?.details
?? {}
282 if (messageType
!== MessageType
.CALL_MESSAGE
) {
284 return resolve(messagePayload
);
288 * Function that will receive the request's response
291 * @param requestPayload -
293 function responseCallback(payload
: JsonType
, requestPayload
: JsonType
): void {
294 if (chargingStation
.getEnableStatistics() === true) {
295 chargingStation
.performanceStatistics
.addRequestStatistic(
297 MessageType
.CALL_RESULT_MESSAGE
300 // Handle the request's response
301 self.ocppResponseService
304 commandName
as RequestCommand
,
315 chargingStation
.requests
.delete(messageId
);
320 * Function that will receive the request's error response
323 * @param requestStatistic -
325 function errorCallback(error
: OCPPError
, requestStatistic
= true): void {
326 if (requestStatistic
=== true && chargingStation
.getEnableStatistics() === true) {
327 chargingStation
.performanceStatistics
.addRequestStatistic(
329 MessageType
.CALL_ERROR_MESSAGE
333 `${chargingStation.logPrefix()} Error occurred when calling command ${commandName} with message data ${JSON.stringify(
338 chargingStation
.requests
.delete(messageId
);
342 Constants
.OCPP_WEBSOCKET_TIMEOUT
,
344 ErrorType
.GENERIC_ERROR
,
345 `Timeout for message id '${messageId}'`,
347 (messagePayload
as JsonObject
)?.details
?? {}
350 messageType
=== MessageType
.CALL_MESSAGE
&& chargingStation
.requests
.delete(messageId
);
355 ErrorType
.SECURITY_ERROR
,
356 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
361 private buildMessageToSend(
362 chargingStation
: ChargingStation
,
364 messagePayload
: JsonType
| OCPPError
,
365 messageType
: MessageType
,
366 commandName
?: RequestCommand
| IncomingRequestCommand
,
367 responseCallback
?: ResponseCallback
,
368 errorCallback
?: ErrorCallback
370 let messageToSend
: string;
372 switch (messageType
) {
374 case MessageType
.CALL_MESSAGE
:
376 chargingStation
.requests
.set(messageId
, [
380 messagePayload
as JsonType
,
382 this.validateRequestPayload(chargingStation
, commandName
, messagePayload
as JsonObject
);
383 messageToSend
= JSON
.stringify([
388 ] as OutgoingRequest
);
391 case MessageType
.CALL_RESULT_MESSAGE
:
393 this.validateIncomingRequestResponsePayload(
396 messagePayload
as JsonObject
398 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
] as Response
);
401 case MessageType
.CALL_ERROR_MESSAGE
:
402 // Build Error Message
403 messageToSend
= JSON
.stringify([
406 (messagePayload
as OCPPError
)?.code
?? ErrorType
.GENERIC_ERROR
,
407 (messagePayload
as OCPPError
)?.message
?? '',
408 (messagePayload
as OCPPError
)?.details
?? { commandName
},
412 return messageToSend
;
415 private getMessageTypeString(messageType
: MessageType
): string {
416 switch (messageType
) {
417 case MessageType
.CALL_MESSAGE
:
419 case MessageType
.CALL_RESULT_MESSAGE
:
421 case MessageType
.CALL_ERROR_MESSAGE
:
426 private handleSendMessageError(
427 chargingStation
: ChargingStation
,
428 commandName
: RequestCommand
| IncomingRequestCommand
,
430 params
: HandleErrorParams
<EmptyObject
> = { throwError
: false }
432 logger
.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error
);
433 if (params
?.throwError
=== true) {
438 // eslint-disable-next-line @typescript-eslint/no-unused-vars
439 public abstract requestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
440 chargingStation
: ChargingStation
,
441 commandName
: RequestCommand
,
442 commandParams
?: JsonType
,
443 params
?: RequestParams