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
.stationInfo
?.ocppStrictCompliance
=== 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
.stationInfo
?.ocppStrictCompliance
=== 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
.stationInfo
?.ocppStrictCompliance
=== 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
.stationInfo
?.enableStatistics
=== 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 => {
361 requestStatistic
=== true &&
362 chargingStation
.stationInfo
?.enableStatistics
=== true
364 chargingStation
.performanceStatistics
?.addRequestStatistic(
366 MessageType
.CALL_ERROR_MESSAGE
,
370 `${chargingStation.logPrefix()} Error occurred at ${OCPPServiceUtils.getMessageTypeString(
372 )} command ${commandName} with PDU %j:`,
376 chargingStation
.requests
.delete(messageId
);
380 if (chargingStation
.stationInfo
?.enableStatistics
=== true) {
381 chargingStation
.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
383 const messageToSend
= this.buildMessageToSend(
392 let sendError
= false;
393 // Check if wsConnection opened
394 const wsOpened
= chargingStation
.isWebSocketConnectionOpened() === true;
396 const beginId
= PerformanceStatistics
.beginMeasure(commandName
);
398 chargingStation
.wsConnection
?.send(messageToSend
);
400 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${OCPPServiceUtils.getMessageTypeString(
402 )} payload: ${messageToSend}`,
406 `${chargingStation.logPrefix()} >> Command '${commandName}' failed to send ${OCPPServiceUtils.getMessageTypeString(
408 )} payload: ${messageToSend}:`,
413 PerformanceStatistics
.endMeasure(commandName
, beginId
);
415 const wsClosedOrErrored
= !wsOpened
|| sendError
=== true;
416 if (wsClosedOrErrored
&& params
?.skipBufferingOnError
=== false) {
418 chargingStation
.bufferMessage(messageToSend
);
419 // Reject and keep request in the cache
422 ErrorType
.GENERIC_ERROR
,
423 `WebSocket closed or errored for buffered message id '${messageId}' with content '${messageToSend}'`,
425 (messagePayload
as JsonObject
)?.details
?? Constants
.EMPTY_FROZEN_OBJECT
,
428 } else if (wsClosedOrErrored
) {
429 const ocppError
= new OCPPError(
430 ErrorType
.GENERIC_ERROR
,
431 `WebSocket closed or errored for non buffered message id '${messageId}' with content '${messageToSend}'`,
433 (messagePayload
as JsonObject
)?.details
?? Constants
.EMPTY_FROZEN_OBJECT
,
436 if (messageType
!== MessageType
.CALL_MESSAGE
) {
437 return reject(ocppError
);
439 // Reject and remove request from the cache
440 return errorCallback(ocppError
, false);
443 if (messageType
!== MessageType
.CALL_MESSAGE
) {
444 return resolve(messagePayload
);
447 OCPPConstants
.OCPP_WEBSOCKET_TIMEOUT
,
449 ErrorType
.GENERIC_ERROR
,
450 `Timeout for message id '${messageId}'`,
452 (messagePayload
as JsonObject
)?.details
?? Constants
.EMPTY_FROZEN_OBJECT
,
455 messageType
=== MessageType
.CALL_MESSAGE
&& chargingStation
.requests
.delete(messageId
);
460 ErrorType
.SECURITY_ERROR
,
461 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
466 private buildMessageToSend(
467 chargingStation
: ChargingStation
,
469 messagePayload
: JsonType
| OCPPError
,
470 messageType
: MessageType
,
471 commandName
: RequestCommand
| IncomingRequestCommand
,
472 responseCallback
: ResponseCallback
,
473 errorCallback
: ErrorCallback
,
475 let messageToSend
: string;
477 switch (messageType
) {
479 case MessageType
.CALL_MESSAGE
:
481 this.validateRequestPayload(chargingStation
, commandName
, messagePayload
as JsonType
);
482 chargingStation
.requests
.set(messageId
, [
486 messagePayload
as JsonType
,
488 messageToSend
= JSON
.stringify([
493 ] as OutgoingRequest
);
496 case MessageType
.CALL_RESULT_MESSAGE
:
498 this.validateIncomingRequestResponsePayload(
501 messagePayload
as JsonType
,
503 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
] as Response
);
506 case MessageType
.CALL_ERROR_MESSAGE
:
507 // Build Error Message
508 messageToSend
= JSON
.stringify([
511 (messagePayload
as OCPPError
)?.code
?? ErrorType
.GENERIC_ERROR
,
512 (messagePayload
as OCPPError
)?.message
?? '',
513 (messagePayload
as OCPPError
)?.details
?? { commandName
},
517 return messageToSend
;
520 // eslint-disable-next-line @typescript-eslint/no-unused-vars
521 public abstract requestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
522 chargingStation
: ChargingStation
,
523 commandName
: RequestCommand
,
524 // FIXME: should be ReqType
525 commandParams
?: JsonType
,
526 params
?: RequestParams
,