1 import type { JSONSchemaType
} from
'ajv';
2 import Ajv from
'ajv-draft-04';
3 import ajvFormats from
'ajv-formats';
5 import OCPPError from
'../../exception/OCPPError';
6 import PerformanceStatistics from
'../../performance/PerformanceStatistics';
7 import type { EmptyObject
} from
'../../types/EmptyObject';
8 import type { HandleErrorParams
} from
'../../types/Error';
9 import type { JsonObject
, JsonType
} from
'../../types/JsonType';
10 import { ErrorType
} from
'../../types/ocpp/ErrorType';
11 import { MessageType
} from
'../../types/ocpp/MessageType';
13 IncomingRequestCommand
,
18 } from
'../../types/ocpp/Requests';
19 import type { ErrorResponse
, Response
} from
'../../types/ocpp/Responses';
20 import Constants from
'../../utils/Constants';
21 import logger from
'../../utils/Logger';
22 import Utils from
'../../utils/Utils';
23 import type ChargingStation from
'../ChargingStation';
24 import type OCPPResponseService from
'./OCPPResponseService';
25 import { OCPPServiceUtils
} from
'./OCPPServiceUtils';
27 const moduleName
= 'OCPPRequestService';
29 export default abstract class OCPPRequestService
{
30 private static instance
: OCPPRequestService
| null = null;
33 private readonly ocppResponseService
: OCPPResponseService
;
35 protected constructor(ocppResponseService
: OCPPResponseService
) {
36 this.ocppResponseService
= ocppResponseService
;
39 this.requestHandler
.bind(this);
40 this.sendResponse
.bind(this);
41 this.sendError
.bind(this);
42 this.internalSendMessage
.bind(this);
43 this.buildMessageToSend
.bind(this);
44 this.validateRequestPayload
.bind(this);
47 public static getInstance
<T
extends OCPPRequestService
>(
48 this: new (ocppResponseService
: OCPPResponseService
) => T
,
49 ocppResponseService
: OCPPResponseService
51 if (OCPPRequestService
.instance
=== null) {
52 OCPPRequestService
.instance
= new this(ocppResponseService
);
54 return OCPPRequestService
.instance
as T
;
57 public async sendResponse(
58 chargingStation
: ChargingStation
,
60 messagePayload
: JsonType
,
61 commandName
: IncomingRequestCommand
62 ): Promise
<ResponseType
> {
64 // Send response message
65 return await this.internalSendMessage(
69 MessageType
.CALL_RESULT_MESSAGE
,
73 this.handleRequestError(chargingStation
, commandName
, error
as Error);
77 public async sendError(
78 chargingStation
: ChargingStation
,
81 commandName
: RequestCommand
| IncomingRequestCommand
82 ): Promise
<ResponseType
> {
85 return await this.internalSendMessage(
89 MessageType
.CALL_ERROR_MESSAGE
,
93 this.handleRequestError(chargingStation
, commandName
, error
as Error);
97 protected async sendMessage(
98 chargingStation
: ChargingStation
,
100 messagePayload
: JsonType
,
101 commandName
: RequestCommand
,
102 params
: RequestParams
= {
103 skipBufferingOnError
: false,
104 triggerMessage
: false,
106 ): Promise
<ResponseType
> {
108 return await this.internalSendMessage(
112 MessageType
.CALL_MESSAGE
,
117 this.handleRequestError(chargingStation
, commandName
, error
as Error, { throwError
: false });
121 protected validateRequestPayload
<T
extends JsonType
>(
122 chargingStation
: ChargingStation
,
123 commandName
: RequestCommand
,
124 schema
: JSONSchemaType
<T
>,
127 if (chargingStation
.getPayloadSchemaValidation() === false) {
130 const validate
= this.ajv
.compile(schema
);
131 if (validate(payload
)) {
135 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Request PDU is invalid: %j`,
138 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
140 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
),
141 'Request PDU is invalid',
143 JSON
.stringify(validate
.errors
, null, 2)
147 private async internalSendMessage(
148 chargingStation
: ChargingStation
,
150 messagePayload
: JsonType
| OCPPError
,
151 messageType
: MessageType
,
152 commandName
?: RequestCommand
| IncomingRequestCommand
,
153 params
: RequestParams
= {
154 skipBufferingOnError
: false,
155 triggerMessage
: false,
157 ): Promise
<ResponseType
> {
159 (chargingStation
.isInUnknownState() && commandName
=== RequestCommand
.BOOT_NOTIFICATION
) ||
160 (!chargingStation
.getOcppStrictCompliance() && chargingStation
.isInUnknownState()) ||
161 chargingStation
.isInAcceptedState() ||
162 (chargingStation
.isInPendingState() &&
163 (params
.triggerMessage
|| messageType
=== MessageType
.CALL_RESULT_MESSAGE
))
165 // eslint-disable-next-line @typescript-eslint/no-this-alias
167 // Send a message through wsConnection
168 return Utils
.promiseWithTimeout(
169 new Promise((resolve
, reject
) => {
170 const messageToSend
= this.buildMessageToSend(
179 if (chargingStation
.getEnableStatistics() === true) {
180 chargingStation
.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
182 // Check if wsConnection opened
183 if (chargingStation
.isWebSocketConnectionOpened() === true) {
185 const beginId
= PerformanceStatistics
.beginMeasure(commandName
);
186 // FIXME: Handle sending error
187 chargingStation
.wsConnection
.send(messageToSend
);
188 PerformanceStatistics
.endMeasure(commandName
, beginId
);
190 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
192 )} payload: ${messageToSend}`
194 } else if (params
.skipBufferingOnError
=== false) {
196 chargingStation
.bufferMessage(messageToSend
);
197 const ocppError
= new OCPPError(
198 ErrorType
.GENERIC_ERROR
,
199 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
201 (messagePayload
as JsonObject
)?.details
?? {}
203 if (messageType
=== MessageType
.CALL_MESSAGE
) {
204 // Reject it but keep the request in the cache
205 return reject(ocppError
);
207 return errorCallback(ocppError
, false);
210 return errorCallback(
212 ErrorType
.GENERIC_ERROR
,
213 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
215 (messagePayload
as JsonObject
)?.details
?? {}
221 if (messageType
!== MessageType
.CALL_MESSAGE
) {
223 return resolve(messagePayload
);
227 * Function that will receive the request's response
230 * @param requestPayload
232 async function responseCallback(
234 requestPayload
: JsonType
236 if (chargingStation
.getEnableStatistics() === true) {
237 chargingStation
.performanceStatistics
.addRequestStatistic(
239 MessageType
.CALL_RESULT_MESSAGE
242 // Handle the request's response
244 await self.ocppResponseService
.responseHandler(
246 commandName
as RequestCommand
,
254 chargingStation
.requests
.delete(messageId
);
259 * Function that will receive the request's error response
262 * @param requestStatistic
264 function errorCallback(error
: OCPPError
, requestStatistic
= true): void {
265 if (requestStatistic
=== true && chargingStation
.getEnableStatistics() === true) {
266 chargingStation
.performanceStatistics
.addRequestStatistic(
268 MessageType
.CALL_ERROR_MESSAGE
272 `${chargingStation.logPrefix()} Error occurred when calling command ${commandName} with message data ${JSON.stringify(
277 chargingStation
.requests
.delete(messageId
);
281 Constants
.OCPP_WEBSOCKET_TIMEOUT
,
283 ErrorType
.GENERIC_ERROR
,
284 `Timeout for message id '${messageId}'`,
286 (messagePayload
as JsonObject
)?.details
?? {}
289 messageType
=== MessageType
.CALL_MESSAGE
&& chargingStation
.requests
.delete(messageId
);
294 ErrorType
.SECURITY_ERROR
,
295 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
300 private buildMessageToSend(
301 chargingStation
: ChargingStation
,
303 messagePayload
: JsonType
| OCPPError
,
304 messageType
: MessageType
,
305 commandName
?: RequestCommand
| IncomingRequestCommand
,
306 responseCallback
?: (payload
: JsonType
, requestPayload
: JsonType
) => Promise
<void>,
307 errorCallback
?: (error
: OCPPError
, requestStatistic
?: boolean) => void
309 let messageToSend
: string;
311 switch (messageType
) {
313 case MessageType
.CALL_MESSAGE
:
315 chargingStation
.requests
.set(messageId
, [
319 messagePayload
as JsonType
,
321 messageToSend
= JSON
.stringify([
326 ] as OutgoingRequest
);
329 case MessageType
.CALL_RESULT_MESSAGE
:
331 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
] as Response
);
334 case MessageType
.CALL_ERROR_MESSAGE
:
335 // Build Error Message
336 messageToSend
= JSON
.stringify([
339 (messagePayload
as OCPPError
)?.code
?? ErrorType
.GENERIC_ERROR
,
340 (messagePayload
as OCPPError
)?.message
?? '',
341 (messagePayload
as OCPPError
)?.details
?? { commandName
},
345 return messageToSend
;
348 private getMessageTypeString(messageType
: MessageType
): string {
349 switch (messageType
) {
350 case MessageType
.CALL_MESSAGE
:
352 case MessageType
.CALL_RESULT_MESSAGE
:
354 case MessageType
.CALL_ERROR_MESSAGE
:
359 private handleRequestError(
360 chargingStation
: ChargingStation
,
361 commandName
: RequestCommand
| IncomingRequestCommand
,
363 params
: HandleErrorParams
<EmptyObject
> = { throwError
: true }
365 logger
.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error
);
366 if (params
?.throwError
) {
371 // eslint-disable-next-line @typescript-eslint/no-unused-vars
372 public abstract requestHandler
<RequestType
extends JsonType
, ResponseType
extends JsonType
>(
373 chargingStation
: ChargingStation
,
374 commandName
: RequestCommand
,
375 commandParams
?: JsonType
,
376 params
?: RequestParams
377 ): Promise
<ResponseType
>;