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()) {
130 const validate
= this.ajv
.compile(schema
);
131 if (validate(payload
)) {
135 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Request PDU is invalid: %j`,
139 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
),
140 'Request PDU is invalid',
142 JSON
.stringify(validate
.errors
, null, 2)
146 private async internalSendMessage(
147 chargingStation
: ChargingStation
,
149 messagePayload
: JsonType
| OCPPError
,
150 messageType
: MessageType
,
151 commandName
?: RequestCommand
| IncomingRequestCommand
,
152 params
: RequestParams
= {
153 skipBufferingOnError
: false,
154 triggerMessage
: false,
156 ): Promise
<ResponseType
> {
158 (chargingStation
.isInUnknownState() && commandName
=== RequestCommand
.BOOT_NOTIFICATION
) ||
159 (!chargingStation
.getOcppStrictCompliance() && chargingStation
.isInUnknownState()) ||
160 chargingStation
.isInAcceptedState() ||
161 (chargingStation
.isInPendingState() &&
162 (params
.triggerMessage
|| messageType
=== MessageType
.CALL_RESULT_MESSAGE
))
164 // eslint-disable-next-line @typescript-eslint/no-this-alias
166 // Send a message through wsConnection
167 return Utils
.promiseWithTimeout(
168 new Promise((resolve
, reject
) => {
169 const messageToSend
= this.buildMessageToSend(
178 if (chargingStation
.getEnableStatistics()) {
179 chargingStation
.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
181 // Check if wsConnection opened
182 if (chargingStation
.isWebSocketConnectionOpened()) {
184 const beginId
= PerformanceStatistics
.beginMeasure(commandName
);
185 // FIXME: Handle sending error
186 chargingStation
.wsConnection
.send(messageToSend
);
187 PerformanceStatistics
.endMeasure(commandName
, beginId
);
189 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
191 )} payload: ${messageToSend}`
193 } else if (!params
.skipBufferingOnError
) {
195 chargingStation
.bufferMessage(messageToSend
);
196 const ocppError
= new OCPPError(
197 ErrorType
.GENERIC_ERROR
,
198 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
200 (messagePayload
as JsonObject
)?.details
?? {}
202 if (messageType
=== MessageType
.CALL_MESSAGE
) {
203 // Reject it but keep the request in the cache
204 return reject(ocppError
);
206 return errorCallback(ocppError
, false);
209 return errorCallback(
211 ErrorType
.GENERIC_ERROR
,
212 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
214 (messagePayload
as JsonObject
)?.details
?? {}
220 if (messageType
!== MessageType
.CALL_MESSAGE
) {
222 return resolve(messagePayload
);
226 * Function that will receive the request's response
229 * @param requestPayload
231 async function responseCallback(
233 requestPayload
: JsonType
235 if (chargingStation
.getEnableStatistics()) {
236 chargingStation
.performanceStatistics
.addRequestStatistic(
238 MessageType
.CALL_RESULT_MESSAGE
241 // Handle the request's response
243 await self.ocppResponseService
.responseHandler(
245 commandName
as RequestCommand
,
253 chargingStation
.requests
.delete(messageId
);
258 * Function that will receive the request's error response
261 * @param requestStatistic
263 function errorCallback(error
: OCPPError
, requestStatistic
= true): void {
264 if (requestStatistic
&& chargingStation
.getEnableStatistics()) {
265 chargingStation
.performanceStatistics
.addRequestStatistic(
267 MessageType
.CALL_ERROR_MESSAGE
271 `${chargingStation.logPrefix()} Error occurred when calling command ${commandName} with message data ${JSON.stringify(
276 chargingStation
.requests
.delete(messageId
);
280 Constants
.OCPP_WEBSOCKET_TIMEOUT
,
282 ErrorType
.GENERIC_ERROR
,
283 `Timeout for message id '${messageId}'`,
285 (messagePayload
as JsonObject
)?.details
?? {}
288 messageType
=== MessageType
.CALL_MESSAGE
&& chargingStation
.requests
.delete(messageId
);
293 ErrorType
.SECURITY_ERROR
,
294 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
299 private buildMessageToSend(
300 chargingStation
: ChargingStation
,
302 messagePayload
: JsonType
| OCPPError
,
303 messageType
: MessageType
,
304 commandName
?: RequestCommand
| IncomingRequestCommand
,
305 responseCallback
?: (payload
: JsonType
, requestPayload
: JsonType
) => Promise
<void>,
306 errorCallback
?: (error
: OCPPError
, requestStatistic
?: boolean) => void
308 let messageToSend
: string;
310 switch (messageType
) {
312 case MessageType
.CALL_MESSAGE
:
314 chargingStation
.requests
.set(messageId
, [
318 messagePayload
as JsonType
,
320 messageToSend
= JSON
.stringify([
325 ] as OutgoingRequest
);
328 case MessageType
.CALL_RESULT_MESSAGE
:
330 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
] as Response
);
333 case MessageType
.CALL_ERROR_MESSAGE
:
334 // Build Error Message
335 messageToSend
= JSON
.stringify([
338 (messagePayload
as OCPPError
)?.code
?? ErrorType
.GENERIC_ERROR
,
339 (messagePayload
as OCPPError
)?.message
?? '',
340 (messagePayload
as OCPPError
)?.details
?? { commandName
},
344 return messageToSend
;
347 private getMessageTypeString(messageType
: MessageType
): string {
348 switch (messageType
) {
349 case MessageType
.CALL_MESSAGE
:
351 case MessageType
.CALL_RESULT_MESSAGE
:
353 case MessageType
.CALL_ERROR_MESSAGE
:
358 private handleRequestError(
359 chargingStation
: ChargingStation
,
360 commandName
: RequestCommand
| IncomingRequestCommand
,
362 params
: HandleErrorParams
<EmptyObject
> = { throwError
: true }
364 logger
.error(`${chargingStation.logPrefix()} Request command ${commandName} error:`, error
);
365 if (params
?.throwError
) {
370 // eslint-disable-next-line @typescript-eslint/no-unused-vars
371 public abstract requestHandler
<RequestType
extends JsonType
, ResponseType
extends JsonType
>(
372 chargingStation
: ChargingStation
,
373 commandName
: RequestCommand
,
374 commandParams
?: JsonType
,
375 params
?: RequestParams
376 ): Promise
<ResponseType
>;