1 import Ajv
, { type JSONSchemaType
, type ValidateFunction
} from
'ajv';
2 import ajvFormats from
'ajv-formats';
4 import { OCPPConstants
} from
'./OCPPConstants';
5 import type { OCPPResponseService
} from
'./OCPPResponseService';
6 import { OCPPServiceUtils
} from
'./OCPPServiceUtils';
7 import type { ChargingStation
} from
'../../charging-station';
8 import { OCPPError
} from
'../../exception';
9 import { PerformanceStatistics
} from
'../../performance';
14 type IncomingRequestCommand
,
23 type ResponseCallback
,
29 handleSendMessageError
,
34 const moduleName
= 'OCPPRequestService';
36 const defaultRequestParams
: RequestParams
= {
37 skipBufferingOnError
: false,
38 triggerMessage
: false,
42 export abstract class OCPPRequestService
{
43 private static instance
: OCPPRequestService
| null = null;
44 private readonly version
: OCPPVersion
;
45 private readonly ajv
: Ajv
;
46 private readonly ocppResponseService
: OCPPResponseService
;
47 private readonly jsonValidateFunctions
: Map
<RequestCommand
, ValidateFunction
<JsonType
>>;
48 protected abstract jsonSchemas
: Map
<RequestCommand
, JSONSchemaType
<JsonType
>>;
50 protected constructor(version
: OCPPVersion
, ocppResponseService
: OCPPResponseService
) {
51 this.version
= version
;
53 keywords
: ['javaType'],
54 multipleOfPrecision
: 2,
57 this.jsonValidateFunctions
= new Map
<RequestCommand
, ValidateFunction
<JsonType
>>();
58 this.ocppResponseService
= ocppResponseService
;
59 this.requestHandler
= this.requestHandler
.bind(this) as <
60 // eslint-disable-next-line @typescript-eslint/no-unused-vars
61 ReqType
extends JsonType
,
62 ResType
extends JsonType
,
64 chargingStation
: ChargingStation
,
65 commandName
: RequestCommand
,
66 commandParams
?: JsonType
,
67 params
?: RequestParams
,
68 ) => Promise
<ResType
>;
69 this.sendMessage
= this.sendMessage
.bind(this) as (
70 chargingStation
: ChargingStation
,
72 messagePayload
: JsonType
,
73 commandName
: RequestCommand
,
74 params
?: RequestParams
,
75 ) => Promise
<ResponseType
>;
76 this.sendResponse
= this.sendResponse
.bind(this) as (
77 chargingStation
: ChargingStation
,
79 messagePayload
: JsonType
,
80 commandName
: IncomingRequestCommand
,
81 ) => Promise
<ResponseType
>;
82 this.sendError
= this.sendError
.bind(this) as (
83 chargingStation
: ChargingStation
,
86 commandName
: RequestCommand
| IncomingRequestCommand
,
87 ) => Promise
<ResponseType
>;
88 this.internalSendMessage
= this.internalSendMessage
.bind(this) as (
89 chargingStation
: ChargingStation
,
91 messagePayload
: JsonType
| OCPPError
,
92 messageType
: MessageType
,
93 commandName
: RequestCommand
| IncomingRequestCommand
,
94 params
?: RequestParams
,
95 ) => Promise
<ResponseType
>;
96 this.buildMessageToSend
= this.buildMessageToSend
.bind(this) as (
97 chargingStation
: ChargingStation
,
99 messagePayload
: JsonType
| OCPPError
,
100 messageType
: MessageType
,
101 commandName
: RequestCommand
| IncomingRequestCommand
,
102 responseCallback
: ResponseCallback
,
103 errorCallback
: ErrorCallback
,
105 this.validateRequestPayload
= this.validateRequestPayload
.bind(this) as <T
extends JsonType
>(
106 chargingStation
: ChargingStation
,
107 commandName
: RequestCommand
| IncomingRequestCommand
,
110 this.validateIncomingRequestResponsePayload
= this.validateIncomingRequestResponsePayload
.bind(
112 ) as <T
extends JsonType
>(
113 chargingStation
: ChargingStation
,
114 commandName
: RequestCommand
| IncomingRequestCommand
,
119 public static getInstance
<T
extends OCPPRequestService
>(
120 this: new (ocppResponseService
: OCPPResponseService
) => T
,
121 ocppResponseService
: OCPPResponseService
,
123 if (OCPPRequestService
.instance
=== null) {
124 OCPPRequestService
.instance
= new this(ocppResponseService
);
126 return OCPPRequestService
.instance
as T
;
129 public async sendResponse(
130 chargingStation
: ChargingStation
,
132 messagePayload
: JsonType
,
133 commandName
: IncomingRequestCommand
,
134 ): Promise
<ResponseType
> {
136 // Send response message
137 return await this.internalSendMessage(
141 MessageType
.CALL_RESULT_MESSAGE
,
145 handleSendMessageError(chargingStation
, commandName
, error
as Error, {
152 public async sendError(
153 chargingStation
: ChargingStation
,
155 ocppError
: OCPPError
,
156 commandName
: RequestCommand
| IncomingRequestCommand
,
157 ): Promise
<ResponseType
> {
159 // Send error message
160 return await this.internalSendMessage(
164 MessageType
.CALL_ERROR_MESSAGE
,
168 handleSendMessageError(chargingStation
, commandName
, error
as Error);
173 protected async sendMessage(
174 chargingStation
: ChargingStation
,
176 messagePayload
: JsonType
,
177 commandName
: RequestCommand
,
178 params
?: RequestParams
,
179 ): Promise
<ResponseType
> {
181 ...defaultRequestParams
,
185 return await this.internalSendMessage(
189 MessageType
.CALL_MESSAGE
,
194 handleSendMessageError(chargingStation
, commandName
, error
as Error, {
195 throwError
: params
.throwError
,
201 private validateRequestPayload
<T
extends JsonType
>(
202 chargingStation
: ChargingStation
,
203 commandName
: RequestCommand
| IncomingRequestCommand
,
206 if (chargingStation
.getOcppStrictCompliance() === false) {
209 if (this.jsonSchemas
.has(commandName
as RequestCommand
) === false) {
211 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: No JSON schema found for command '${commandName}' PDU validation`,
215 if (this.jsonValidateFunctions
.has(commandName
as RequestCommand
) === false) {
216 this.jsonValidateFunctions
.set(
217 commandName
as RequestCommand
,
218 this.ajv
.compile
<T
>(this.jsonSchemas
.get(commandName
as RequestCommand
)!).bind(this),
221 const validate
= this.jsonValidateFunctions
.get(commandName
as RequestCommand
)!;
222 payload
= cloneObject
<T
>(payload
);
223 OCPPServiceUtils
.convertDateToISOString
<T
>(payload
);
224 if (validate(payload
)) {
228 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Command '${commandName}' request PDU is invalid: %j`,
231 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
233 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
!),
234 'Request PDU is invalid',
236 JSON
.stringify(validate
.errors
, undefined, 2),
240 private validateIncomingRequestResponsePayload
<T
extends JsonType
>(
241 chargingStation
: ChargingStation
,
242 commandName
: RequestCommand
| IncomingRequestCommand
,
245 if (chargingStation
.getOcppStrictCompliance() === false) {
249 this.ocppResponseService
.jsonIncomingRequestResponseSchemas
.has(
250 commandName
as IncomingRequestCommand
,
254 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: No JSON schema found for command '${commandName}' PDU validation`,
259 this.ocppResponseService
.jsonIncomingRequestResponseValidateFunctions
.has(
260 commandName
as IncomingRequestCommand
,
263 this.ocppResponseService
.jsonIncomingRequestResponseValidateFunctions
.set(
264 commandName
as IncomingRequestCommand
,
267 this.ocppResponseService
.jsonIncomingRequestResponseSchemas
.get(
268 commandName
as IncomingRequestCommand
,
274 const validate
= this.ocppResponseService
.jsonIncomingRequestResponseValidateFunctions
.get(
275 commandName
as IncomingRequestCommand
,
277 payload
= cloneObject
<T
>(payload
);
278 OCPPServiceUtils
.convertDateToISOString
<T
>(payload
);
279 if (validate(payload
)) {
283 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: Command '${commandName}' reponse PDU is invalid: %j`,
286 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
288 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
!),
289 'Response PDU is invalid',
291 JSON
.stringify(validate
.errors
, undefined, 2),
295 private async internalSendMessage(
296 chargingStation
: ChargingStation
,
298 messagePayload
: JsonType
| OCPPError
,
299 messageType
: MessageType
,
300 commandName
: RequestCommand
| IncomingRequestCommand
,
301 params
?: RequestParams
,
302 ): Promise
<ResponseType
> {
304 ...defaultRequestParams
,
308 (chargingStation
.inUnknownState() === true &&
309 commandName
=== RequestCommand
.BOOT_NOTIFICATION
) ||
310 (chargingStation
.getOcppStrictCompliance() === false &&
311 chargingStation
.inUnknownState() === true) ||
312 chargingStation
.inAcceptedState() === true ||
313 (chargingStation
.inPendingState() === true &&
314 (params
.triggerMessage
=== true || messageType
=== MessageType
.CALL_RESULT_MESSAGE
))
316 // eslint-disable-next-line @typescript-eslint/no-this-alias
318 // Send a message through wsConnection
319 return promiseWithTimeout(
320 new Promise
<ResponseType
>((resolve
, reject
) => {
322 * Function that will receive the request's response
325 * @param requestPayload -
327 const responseCallback
= (payload
: JsonType
, requestPayload
: JsonType
): void => {
328 if (chargingStation
.getEnableStatistics() === true) {
329 chargingStation
.performanceStatistics
?.addRequestStatistic(
331 MessageType
.CALL_RESULT_MESSAGE
,
334 // Handle the request's response
335 self.ocppResponseService
338 commandName
as RequestCommand
,
349 chargingStation
.requests
.delete(messageId
);
354 * Function that will receive the request's error response
357 * @param requestStatistic -
359 const errorCallback
= (error
: OCPPError
, requestStatistic
= true): void => {
360 if (requestStatistic
=== true && chargingStation
.getEnableStatistics() === true) {
361 chargingStation
.performanceStatistics
?.addRequestStatistic(
363 MessageType
.CALL_ERROR_MESSAGE
,
367 `${chargingStation.logPrefix()} Error occurred at ${OCPPServiceUtils.getMessageTypeString(
369 )} command ${commandName} with PDU %j:`,
373 chargingStation
.requests
.delete(messageId
);
377 if (chargingStation
.getEnableStatistics() === true) {
378 chargingStation
.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
380 const messageToSend
= this.buildMessageToSend(
389 let sendError
= false;
390 // Check if wsConnection opened
391 const wsOpened
= chargingStation
.isWebSocketConnectionOpened() === true;
393 const beginId
= PerformanceStatistics
.beginMeasure(commandName
);
395 chargingStation
.wsConnection
?.send(messageToSend
);
397 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${OCPPServiceUtils.getMessageTypeString(
399 )} payload: ${messageToSend}`,
403 `${chargingStation.logPrefix()} >> Command '${commandName}' failed to send ${OCPPServiceUtils.getMessageTypeString(
405 )} payload: ${messageToSend}:`,
410 PerformanceStatistics
.endMeasure(commandName
, beginId
);
412 const wsClosedOrErrored
= !wsOpened
|| sendError
=== true;
413 if (wsClosedOrErrored
&& params
?.skipBufferingOnError
=== false) {
415 chargingStation
.bufferMessage(messageToSend
);
416 // Reject and keep request in the cache
419 ErrorType
.GENERIC_ERROR
,
420 `WebSocket closed or errored for buffered message id '${messageId}' with content '${messageToSend}'`,
422 (messagePayload
as JsonObject
)?.details
?? Constants
.EMPTY_FROZEN_OBJECT
,
425 } else if (wsClosedOrErrored
) {
426 const ocppError
= new OCPPError(
427 ErrorType
.GENERIC_ERROR
,
428 `WebSocket closed or errored for non buffered message id '${messageId}' with content '${messageToSend}'`,
430 (messagePayload
as JsonObject
)?.details
?? Constants
.EMPTY_FROZEN_OBJECT
,
433 if (messageType
!== MessageType
.CALL_MESSAGE
) {
434 return reject(ocppError
);
436 // Reject and remove request from the cache
437 return errorCallback(ocppError
, false);
440 if (messageType
!== MessageType
.CALL_MESSAGE
) {
441 return resolve(messagePayload
);
444 OCPPConstants
.OCPP_WEBSOCKET_TIMEOUT
,
446 ErrorType
.GENERIC_ERROR
,
447 `Timeout for message id '${messageId}'`,
449 (messagePayload
as JsonObject
)?.details
?? Constants
.EMPTY_FROZEN_OBJECT
,
452 messageType
=== MessageType
.CALL_MESSAGE
&& chargingStation
.requests
.delete(messageId
);
457 ErrorType
.SECURITY_ERROR
,
458 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
463 private buildMessageToSend(
464 chargingStation
: ChargingStation
,
466 messagePayload
: JsonType
| OCPPError
,
467 messageType
: MessageType
,
468 commandName
: RequestCommand
| IncomingRequestCommand
,
469 responseCallback
: ResponseCallback
,
470 errorCallback
: ErrorCallback
,
472 let messageToSend
: string;
474 switch (messageType
) {
476 case MessageType
.CALL_MESSAGE
:
478 this.validateRequestPayload(chargingStation
, commandName
, messagePayload
as JsonType
);
479 chargingStation
.requests
.set(messageId
, [
483 messagePayload
as JsonType
,
485 messageToSend
= JSON
.stringify([
490 ] as OutgoingRequest
);
493 case MessageType
.CALL_RESULT_MESSAGE
:
495 this.validateIncomingRequestResponsePayload(
498 messagePayload
as JsonType
,
500 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
] as Response
);
503 case MessageType
.CALL_ERROR_MESSAGE
:
504 // Build Error Message
505 messageToSend
= JSON
.stringify([
508 (messagePayload
as OCPPError
)?.code
?? ErrorType
.GENERIC_ERROR
,
509 (messagePayload
as OCPPError
)?.message
?? '',
510 (messagePayload
as OCPPError
)?.details
?? { commandName
},
514 return messageToSend
;
517 // eslint-disable-next-line @typescript-eslint/no-unused-vars
518 public abstract requestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
519 chargingStation
: ChargingStation
,
520 commandName
: RequestCommand
,
521 // FIXME: should be ReqType
522 commandParams
?: JsonType
,
523 params
?: RequestParams
,