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
;
36 private readonly ocppResponseService
: OCPPResponseService
;
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);
55 public static getInstance
<T
extends OCPPRequestService
>(
56 this: new (ocppResponseService
: OCPPResponseService
) => T
,
57 ocppResponseService
: OCPPResponseService
59 if (OCPPRequestService
.instance
=== null) {
60 OCPPRequestService
.instance
= new this(ocppResponseService
);
62 return OCPPRequestService
.instance
as T
;
65 public async sendResponse(
66 chargingStation
: ChargingStation
,
68 messagePayload
: JsonType
,
69 commandName
: IncomingRequestCommand
70 ): Promise
<ResponseType
> {
72 // Send response message
73 return await this.internalSendMessage(
77 MessageType
.CALL_RESULT_MESSAGE
,
81 this.handleSendMessageError(chargingStation
, commandName
, error
as Error, {
87 public async sendError(
88 chargingStation
: ChargingStation
,
91 commandName
: RequestCommand
| IncomingRequestCommand
92 ): Promise
<ResponseType
> {
95 return await this.internalSendMessage(
99 MessageType
.CALL_ERROR_MESSAGE
,
103 this.handleSendMessageError(chargingStation
, commandName
, error
as Error);
107 protected async sendMessage(
108 chargingStation
: ChargingStation
,
110 messagePayload
: JsonType
,
111 commandName
: RequestCommand
,
112 params
: RequestParams
= {
113 skipBufferingOnError
: false,
114 triggerMessage
: false,
116 ): Promise
<ResponseType
> {
118 return await this.internalSendMessage(
122 MessageType
.CALL_MESSAGE
,
127 this.handleSendMessageError(chargingStation
, commandName
, error
as Error);
131 protected validateRequestPayload
<T
extends JsonType
>(
132 chargingStation
: ChargingStation
,
133 commandName
: RequestCommand
| IncomingRequestCommand
,
136 if (chargingStation
.getPayloadSchemaValidation() === false) {
139 const schema
= this.getRequestPayloadValidationSchema(chargingStation
, commandName
);
140 if (schema
=== false) {
143 const validate
= this.ajv
.compile(schema
);
144 OCPPServiceUtils
.convertDateToISOString
<T
>(payload
);
145 if (validate(payload
)) {
149 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Command '${commandName}' request PDU is invalid: %j`,
152 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
154 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
),
155 'Request PDU is invalid',
157 JSON
.stringify(validate
.errors
, null, 2)
161 private async internalSendMessage(
162 chargingStation
: ChargingStation
,
164 messagePayload
: JsonType
| OCPPError
,
165 messageType
: MessageType
,
166 commandName
?: RequestCommand
| IncomingRequestCommand
,
167 params
: RequestParams
= {
168 skipBufferingOnError
: false,
169 triggerMessage
: false,
171 ): Promise
<ResponseType
> {
173 (chargingStation
.isInUnknownState() === true &&
174 commandName
=== RequestCommand
.BOOT_NOTIFICATION
) ||
175 (chargingStation
.getOcppStrictCompliance() === false &&
176 chargingStation
.isInUnknownState() === true) ||
177 chargingStation
.isInAcceptedState() === true ||
178 (chargingStation
.isInPendingState() === true &&
179 (params
.triggerMessage
=== true || messageType
=== MessageType
.CALL_RESULT_MESSAGE
))
181 // eslint-disable-next-line @typescript-eslint/no-this-alias
183 // Send a message through wsConnection
184 return Utils
.promiseWithTimeout(
185 new Promise((resolve
, reject
) => {
186 const messageToSend
= this.buildMessageToSend(
195 if (chargingStation
.getEnableStatistics() === true) {
196 chargingStation
.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
198 // Check if wsConnection opened
199 if (chargingStation
.isWebSocketConnectionOpened() === true) {
201 const beginId
= PerformanceStatistics
.beginMeasure(commandName
as string);
202 // FIXME: Handle sending error
203 chargingStation
.wsConnection
.send(messageToSend
);
204 PerformanceStatistics
.endMeasure(commandName
as string, beginId
);
206 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
208 )} payload: ${messageToSend}`
210 } else if (params
.skipBufferingOnError
=== false) {
212 chargingStation
.bufferMessage(messageToSend
);
213 const ocppError
= new OCPPError(
214 ErrorType
.GENERIC_ERROR
,
215 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
217 (messagePayload
as JsonObject
)?.details
?? {}
219 if (messageType
=== MessageType
.CALL_MESSAGE
) {
220 // Reject it but keep the request in the cache
221 return reject(ocppError
);
223 return errorCallback(ocppError
, false);
226 return errorCallback(
228 ErrorType
.GENERIC_ERROR
,
229 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
231 (messagePayload
as JsonObject
)?.details
?? {}
237 if (messageType
!== MessageType
.CALL_MESSAGE
) {
239 return resolve(messagePayload
);
243 * Function that will receive the request's response
246 * @param requestPayload -
248 function responseCallback(payload
: JsonType
, requestPayload
: JsonType
): void {
249 if (chargingStation
.getEnableStatistics() === true) {
250 chargingStation
.performanceStatistics
.addRequestStatistic(
252 MessageType
.CALL_RESULT_MESSAGE
255 // Handle the request's response
256 self.ocppResponseService
259 commandName
as RequestCommand
,
270 chargingStation
.requests
.delete(messageId
);
275 * Function that will receive the request's error response
278 * @param requestStatistic -
280 function errorCallback(error
: OCPPError
, requestStatistic
= true): void {
281 if (requestStatistic
=== true && chargingStation
.getEnableStatistics() === true) {
282 chargingStation
.performanceStatistics
.addRequestStatistic(
284 MessageType
.CALL_ERROR_MESSAGE
288 `${chargingStation.logPrefix()} Error occurred when calling command ${commandName} with message data ${JSON.stringify(
293 chargingStation
.requests
.delete(messageId
);
297 Constants
.OCPP_WEBSOCKET_TIMEOUT
,
299 ErrorType
.GENERIC_ERROR
,
300 `Timeout for message id '${messageId}'`,
302 (messagePayload
as JsonObject
)?.details
?? {}
305 messageType
=== MessageType
.CALL_MESSAGE
&& chargingStation
.requests
.delete(messageId
);
310 ErrorType
.SECURITY_ERROR
,
311 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
316 private buildMessageToSend(
317 chargingStation
: ChargingStation
,
319 messagePayload
: JsonType
| OCPPError
,
320 messageType
: MessageType
,
321 commandName
?: RequestCommand
| IncomingRequestCommand
,
322 responseCallback
?: ResponseCallback
,
323 errorCallback
?: ErrorCallback
325 let messageToSend
: string;
327 switch (messageType
) {
329 case MessageType
.CALL_MESSAGE
:
331 chargingStation
.requests
.set(messageId
, [
335 messagePayload
as JsonType
,
337 this.validateRequestPayload(chargingStation
, commandName
, messagePayload
as JsonType
);
338 messageToSend
= JSON
.stringify([
343 ] as OutgoingRequest
);
346 case MessageType
.CALL_RESULT_MESSAGE
:
348 // FIXME: Validate response payload
349 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
] as Response
);
352 case MessageType
.CALL_ERROR_MESSAGE
:
353 // Build Error Message
354 messageToSend
= JSON
.stringify([
357 (messagePayload
as OCPPError
)?.code
?? ErrorType
.GENERIC_ERROR
,
358 (messagePayload
as OCPPError
)?.message
?? '',
359 (messagePayload
as OCPPError
)?.details
?? { commandName
},
363 return messageToSend
;
366 private getMessageTypeString(messageType
: MessageType
): string {
367 switch (messageType
) {
368 case MessageType
.CALL_MESSAGE
:
370 case MessageType
.CALL_RESULT_MESSAGE
:
372 case MessageType
.CALL_ERROR_MESSAGE
:
377 private handleSendMessageError(
378 chargingStation
: ChargingStation
,
379 commandName
: RequestCommand
| IncomingRequestCommand
,
381 params
: HandleErrorParams
<EmptyObject
> = { throwError
: false }
383 logger
.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error
);
384 if (params
?.throwError
=== true) {
389 // eslint-disable-next-line @typescript-eslint/no-unused-vars
390 public abstract requestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
391 chargingStation
: ChargingStation
,
392 commandName
: RequestCommand
,
393 commandParams
?: JsonType
,
394 params
?: RequestParams
397 protected abstract getRequestPayloadValidationSchema(
398 chargingStation
: ChargingStation
,
399 commandName
: RequestCommand
| IncomingRequestCommand
400 ): JSONSchemaType
<JsonObject
> | false;