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
;
42 this.ocppResponseService
= ocppResponseService
;
43 this.requestHandler
.bind(this);
44 this.sendMessage
.bind(this);
45 this.sendResponse
.bind(this);
46 this.sendError
.bind(this);
47 this.internalSendMessage
.bind(this);
48 this.buildMessageToSend
.bind(this);
49 this.validateRequestPayload
.bind(this);
52 public static getInstance
<T
extends OCPPRequestService
>(
53 this: new (ocppResponseService
: OCPPResponseService
) => T
,
54 ocppResponseService
: OCPPResponseService
56 if (OCPPRequestService
.instance
=== null) {
57 OCPPRequestService
.instance
= new this(ocppResponseService
);
59 return OCPPRequestService
.instance
as T
;
62 public async sendResponse(
63 chargingStation
: ChargingStation
,
65 messagePayload
: JsonType
,
66 commandName
: IncomingRequestCommand
67 ): Promise
<ResponseType
> {
69 // Send response message
70 return await this.internalSendMessage(
74 MessageType
.CALL_RESULT_MESSAGE
,
78 this.handleSendMessageError(chargingStation
, commandName
, error
as Error, {
84 public async sendError(
85 chargingStation
: ChargingStation
,
88 commandName
: RequestCommand
| IncomingRequestCommand
89 ): Promise
<ResponseType
> {
92 return await this.internalSendMessage(
96 MessageType
.CALL_ERROR_MESSAGE
,
100 this.handleSendMessageError(chargingStation
, commandName
, error
as Error);
104 protected async sendMessage(
105 chargingStation
: ChargingStation
,
107 messagePayload
: JsonType
,
108 commandName
: RequestCommand
,
109 params
: RequestParams
= {
110 skipBufferingOnError
: false,
111 triggerMessage
: false,
113 ): Promise
<ResponseType
> {
115 return await this.internalSendMessage(
119 MessageType
.CALL_MESSAGE
,
124 this.handleSendMessageError(chargingStation
, commandName
, error
as Error);
128 protected validateRequestPayload
<T
extends JsonType
>(
129 chargingStation
: ChargingStation
,
130 commandName
: RequestCommand
,
131 schema
: JSONSchemaType
<T
>,
134 if (chargingStation
.getPayloadSchemaValidation() === false) {
137 const validate
= this.ajv
.compile(schema
);
138 if (validate(payload
)) {
142 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Request PDU is invalid: %j`,
145 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
147 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
),
148 'Request PDU is invalid',
150 JSON
.stringify(validate
.errors
, null, 2)
154 private async internalSendMessage(
155 chargingStation
: ChargingStation
,
157 messagePayload
: JsonType
| OCPPError
,
158 messageType
: MessageType
,
159 commandName
?: RequestCommand
| IncomingRequestCommand
,
160 params
: RequestParams
= {
161 skipBufferingOnError
: false,
162 triggerMessage
: false,
164 ): Promise
<ResponseType
> {
166 (chargingStation
.isInUnknownState() === true &&
167 commandName
=== RequestCommand
.BOOT_NOTIFICATION
) ||
168 (chargingStation
.getOcppStrictCompliance() === false &&
169 chargingStation
.isInUnknownState() === true) ||
170 chargingStation
.isInAcceptedState() === true ||
171 (chargingStation
.isInPendingState() === true &&
172 (params
.triggerMessage
=== true || messageType
=== MessageType
.CALL_RESULT_MESSAGE
))
174 // eslint-disable-next-line @typescript-eslint/no-this-alias
176 // Send a message through wsConnection
177 return Utils
.promiseWithTimeout(
178 new Promise((resolve
, reject
) => {
179 const messageToSend
= this.buildMessageToSend(
188 if (chargingStation
.getEnableStatistics() === true) {
189 chargingStation
.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
191 // Check if wsConnection opened
192 if (chargingStation
.isWebSocketConnectionOpened() === true) {
194 const beginId
= PerformanceStatistics
.beginMeasure(commandName
as string);
195 // FIXME: Handle sending error
196 chargingStation
.wsConnection
.send(messageToSend
);
197 PerformanceStatistics
.endMeasure(commandName
as string, beginId
);
199 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
201 )} payload: ${messageToSend}`
203 } else if (params
.skipBufferingOnError
=== false) {
205 chargingStation
.bufferMessage(messageToSend
);
206 const ocppError
= new OCPPError(
207 ErrorType
.GENERIC_ERROR
,
208 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
210 (messagePayload
as JsonObject
)?.details
?? {}
212 if (messageType
=== MessageType
.CALL_MESSAGE
) {
213 // Reject it but keep the request in the cache
214 return reject(ocppError
);
216 return errorCallback(ocppError
, false);
219 return errorCallback(
221 ErrorType
.GENERIC_ERROR
,
222 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
224 (messagePayload
as JsonObject
)?.details
?? {}
230 if (messageType
!== MessageType
.CALL_MESSAGE
) {
232 return resolve(messagePayload
);
236 * Function that will receive the request's response
239 * @param requestPayload -
241 function responseCallback(payload
: JsonType
, requestPayload
: JsonType
): void {
242 if (chargingStation
.getEnableStatistics() === true) {
243 chargingStation
.performanceStatistics
.addRequestStatistic(
245 MessageType
.CALL_RESULT_MESSAGE
248 // Handle the request's response
249 self.ocppResponseService
252 commandName
as RequestCommand
,
263 chargingStation
.requests
.delete(messageId
);
268 * Function that will receive the request's error response
271 * @param requestStatistic -
273 function errorCallback(error
: OCPPError
, requestStatistic
= true): void {
274 if (requestStatistic
=== true && chargingStation
.getEnableStatistics() === true) {
275 chargingStation
.performanceStatistics
.addRequestStatistic(
277 MessageType
.CALL_ERROR_MESSAGE
281 `${chargingStation.logPrefix()} Error occurred when calling command ${commandName} with message data ${JSON.stringify(
286 chargingStation
.requests
.delete(messageId
);
290 Constants
.OCPP_WEBSOCKET_TIMEOUT
,
292 ErrorType
.GENERIC_ERROR
,
293 `Timeout for message id '${messageId}'`,
295 (messagePayload
as JsonObject
)?.details
?? {}
298 messageType
=== MessageType
.CALL_MESSAGE
&& chargingStation
.requests
.delete(messageId
);
303 ErrorType
.SECURITY_ERROR
,
304 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
309 private buildMessageToSend(
310 chargingStation
: ChargingStation
,
312 messagePayload
: JsonType
| OCPPError
,
313 messageType
: MessageType
,
314 commandName
?: RequestCommand
| IncomingRequestCommand
,
315 responseCallback
?: ResponseCallback
,
316 errorCallback
?: ErrorCallback
318 let messageToSend
: string;
320 switch (messageType
) {
322 case MessageType
.CALL_MESSAGE
:
324 chargingStation
.requests
.set(messageId
, [
328 messagePayload
as JsonType
,
330 messageToSend
= JSON
.stringify([
335 ] as OutgoingRequest
);
338 case MessageType
.CALL_RESULT_MESSAGE
:
340 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
] as Response
);
343 case MessageType
.CALL_ERROR_MESSAGE
:
344 // Build Error Message
345 messageToSend
= JSON
.stringify([
348 (messagePayload
as OCPPError
)?.code
?? ErrorType
.GENERIC_ERROR
,
349 (messagePayload
as OCPPError
)?.message
?? '',
350 (messagePayload
as OCPPError
)?.details
?? { commandName
},
354 return messageToSend
;
357 private getMessageTypeString(messageType
: MessageType
): string {
358 switch (messageType
) {
359 case MessageType
.CALL_MESSAGE
:
361 case MessageType
.CALL_RESULT_MESSAGE
:
363 case MessageType
.CALL_ERROR_MESSAGE
:
368 private handleSendMessageError(
369 chargingStation
: ChargingStation
,
370 commandName
: RequestCommand
| IncomingRequestCommand
,
372 params
: HandleErrorParams
<EmptyObject
> = { throwError
: false }
374 logger
.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error
);
375 if (params
?.throwError
=== true) {
380 // eslint-disable-next-line @typescript-eslint/no-unused-vars
381 public abstract requestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
382 chargingStation
: ChargingStation
,
383 commandName
: RequestCommand
,
384 commandParams
?: JsonType
,
385 params
?: RequestParams