Migrate all JSON schemas to draft-06 or higher
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPRequestService.ts
1 import Ajv, { type JSONSchemaType } from 'ajv';
2 import ajvFormats from 'ajv-formats';
3
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';
12 import {
13 type ErrorCallback,
14 type IncomingRequestCommand,
15 type OutgoingRequest,
16 RequestCommand,
17 type RequestParams,
18 type ResponseCallback,
19 type ResponseType,
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';
28
29 const moduleName = 'OCPPRequestService';
30
31 export default abstract class OCPPRequestService {
32 private static instance: OCPPRequestService | null = null;
33 private readonly version: OCPPVersion;
34 private readonly ajv: Ajv;
35
36 private readonly ocppResponseService: OCPPResponseService;
37
38 protected constructor(version: OCPPVersion, ocppResponseService: OCPPResponseService) {
39 this.version = version;
40 this.ajv = new Ajv();
41 ajvFormats(this.ajv);
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);
50 }
51
52 public static getInstance<T extends OCPPRequestService>(
53 this: new (ocppResponseService: OCPPResponseService) => T,
54 ocppResponseService: OCPPResponseService
55 ): T {
56 if (OCPPRequestService.instance === null) {
57 OCPPRequestService.instance = new this(ocppResponseService);
58 }
59 return OCPPRequestService.instance as T;
60 }
61
62 public async sendResponse(
63 chargingStation: ChargingStation,
64 messageId: string,
65 messagePayload: JsonType,
66 commandName: IncomingRequestCommand
67 ): Promise<ResponseType> {
68 try {
69 // Send response message
70 return await this.internalSendMessage(
71 chargingStation,
72 messageId,
73 messagePayload,
74 MessageType.CALL_RESULT_MESSAGE,
75 commandName
76 );
77 } catch (error) {
78 this.handleSendMessageError(chargingStation, commandName, error as Error, {
79 throwError: true,
80 });
81 }
82 }
83
84 public async sendError(
85 chargingStation: ChargingStation,
86 messageId: string,
87 ocppError: OCPPError,
88 commandName: RequestCommand | IncomingRequestCommand
89 ): Promise<ResponseType> {
90 try {
91 // Send error message
92 return await this.internalSendMessage(
93 chargingStation,
94 messageId,
95 ocppError,
96 MessageType.CALL_ERROR_MESSAGE,
97 commandName
98 );
99 } catch (error) {
100 this.handleSendMessageError(chargingStation, commandName, error as Error);
101 }
102 }
103
104 protected async sendMessage(
105 chargingStation: ChargingStation,
106 messageId: string,
107 messagePayload: JsonType,
108 commandName: RequestCommand,
109 params: RequestParams = {
110 skipBufferingOnError: false,
111 triggerMessage: false,
112 }
113 ): Promise<ResponseType> {
114 try {
115 return await this.internalSendMessage(
116 chargingStation,
117 messageId,
118 messagePayload,
119 MessageType.CALL_MESSAGE,
120 commandName,
121 params
122 );
123 } catch (error) {
124 this.handleSendMessageError(chargingStation, commandName, error as Error);
125 }
126 }
127
128 protected validateRequestPayload<T extends JsonType>(
129 chargingStation: ChargingStation,
130 commandName: RequestCommand,
131 schema: JSONSchemaType<T>,
132 payload: T
133 ): boolean {
134 if (chargingStation.getPayloadSchemaValidation() === false) {
135 return true;
136 }
137 const validate = this.ajv.compile(schema);
138 if (validate(payload)) {
139 return true;
140 }
141 logger.error(
142 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Request PDU is invalid: %j`,
143 validate.errors
144 );
145 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
146 throw new OCPPError(
147 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
148 'Request PDU is invalid',
149 commandName,
150 JSON.stringify(validate.errors, null, 2)
151 );
152 }
153
154 private async internalSendMessage(
155 chargingStation: ChargingStation,
156 messageId: string,
157 messagePayload: JsonType | OCPPError,
158 messageType: MessageType,
159 commandName?: RequestCommand | IncomingRequestCommand,
160 params: RequestParams = {
161 skipBufferingOnError: false,
162 triggerMessage: false,
163 }
164 ): Promise<ResponseType> {
165 if (
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))
173 ) {
174 // eslint-disable-next-line @typescript-eslint/no-this-alias
175 const self = this;
176 // Send a message through wsConnection
177 return Utils.promiseWithTimeout(
178 new Promise((resolve, reject) => {
179 const messageToSend = this.buildMessageToSend(
180 chargingStation,
181 messageId,
182 messagePayload,
183 messageType,
184 commandName,
185 responseCallback,
186 errorCallback
187 );
188 if (chargingStation.getEnableStatistics() === true) {
189 chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
190 }
191 // Check if wsConnection opened
192 if (chargingStation.isWebSocketConnectionOpened() === true) {
193 // Yes: Send Message
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);
198 logger.debug(
199 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
200 messageType
201 )} payload: ${messageToSend}`
202 );
203 } else if (params.skipBufferingOnError === false) {
204 // Buffer it
205 chargingStation.bufferMessage(messageToSend);
206 const ocppError = new OCPPError(
207 ErrorType.GENERIC_ERROR,
208 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
209 commandName,
210 (messagePayload as JsonObject)?.details ?? {}
211 );
212 if (messageType === MessageType.CALL_MESSAGE) {
213 // Reject it but keep the request in the cache
214 return reject(ocppError);
215 }
216 return errorCallback(ocppError, false);
217 } else {
218 // Reject it
219 return errorCallback(
220 new OCPPError(
221 ErrorType.GENERIC_ERROR,
222 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
223 commandName,
224 (messagePayload as JsonObject)?.details ?? {}
225 ),
226 false
227 );
228 }
229 // Response?
230 if (messageType !== MessageType.CALL_MESSAGE) {
231 // Yes: send Ok
232 return resolve(messagePayload);
233 }
234
235 /**
236 * Function that will receive the request's response
237 *
238 * @param payload -
239 * @param requestPayload -
240 */
241 function responseCallback(payload: JsonType, requestPayload: JsonType): void {
242 if (chargingStation.getEnableStatistics() === true) {
243 chargingStation.performanceStatistics.addRequestStatistic(
244 commandName,
245 MessageType.CALL_RESULT_MESSAGE
246 );
247 }
248 // Handle the request's response
249 self.ocppResponseService
250 .responseHandler(
251 chargingStation,
252 commandName as RequestCommand,
253 payload,
254 requestPayload
255 )
256 .then(() => {
257 resolve(payload);
258 })
259 .catch((error) => {
260 reject(error);
261 })
262 .finally(() => {
263 chargingStation.requests.delete(messageId);
264 });
265 }
266
267 /**
268 * Function that will receive the request's error response
269 *
270 * @param error -
271 * @param requestStatistic -
272 */
273 function errorCallback(error: OCPPError, requestStatistic = true): void {
274 if (requestStatistic === true && chargingStation.getEnableStatistics() === true) {
275 chargingStation.performanceStatistics.addRequestStatistic(
276 commandName,
277 MessageType.CALL_ERROR_MESSAGE
278 );
279 }
280 logger.error(
281 `${chargingStation.logPrefix()} Error occurred when calling command ${commandName} with message data ${JSON.stringify(
282 messagePayload
283 )}:`,
284 error
285 );
286 chargingStation.requests.delete(messageId);
287 reject(error);
288 }
289 }),
290 Constants.OCPP_WEBSOCKET_TIMEOUT,
291 new OCPPError(
292 ErrorType.GENERIC_ERROR,
293 `Timeout for message id '${messageId}'`,
294 commandName,
295 (messagePayload as JsonObject)?.details ?? {}
296 ),
297 () => {
298 messageType === MessageType.CALL_MESSAGE && chargingStation.requests.delete(messageId);
299 }
300 );
301 }
302 throw new OCPPError(
303 ErrorType.SECURITY_ERROR,
304 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
305 commandName
306 );
307 }
308
309 private buildMessageToSend(
310 chargingStation: ChargingStation,
311 messageId: string,
312 messagePayload: JsonType | OCPPError,
313 messageType: MessageType,
314 commandName?: RequestCommand | IncomingRequestCommand,
315 responseCallback?: ResponseCallback,
316 errorCallback?: ErrorCallback
317 ): string {
318 let messageToSend: string;
319 // Type of message
320 switch (messageType) {
321 // Request
322 case MessageType.CALL_MESSAGE:
323 // Build request
324 chargingStation.requests.set(messageId, [
325 responseCallback,
326 errorCallback,
327 commandName,
328 messagePayload as JsonType,
329 ]);
330 messageToSend = JSON.stringify([
331 messageType,
332 messageId,
333 commandName,
334 messagePayload,
335 ] as OutgoingRequest);
336 break;
337 // Response
338 case MessageType.CALL_RESULT_MESSAGE:
339 // Build response
340 messageToSend = JSON.stringify([messageType, messageId, messagePayload] as Response);
341 break;
342 // Error Message
343 case MessageType.CALL_ERROR_MESSAGE:
344 // Build Error Message
345 messageToSend = JSON.stringify([
346 messageType,
347 messageId,
348 (messagePayload as OCPPError)?.code ?? ErrorType.GENERIC_ERROR,
349 (messagePayload as OCPPError)?.message ?? '',
350 (messagePayload as OCPPError)?.details ?? { commandName },
351 ] as ErrorResponse);
352 break;
353 }
354 return messageToSend;
355 }
356
357 private getMessageTypeString(messageType: MessageType): string {
358 switch (messageType) {
359 case MessageType.CALL_MESSAGE:
360 return 'request';
361 case MessageType.CALL_RESULT_MESSAGE:
362 return 'response';
363 case MessageType.CALL_ERROR_MESSAGE:
364 return 'error';
365 }
366 }
367
368 private handleSendMessageError(
369 chargingStation: ChargingStation,
370 commandName: RequestCommand | IncomingRequestCommand,
371 error: Error,
372 params: HandleErrorParams<EmptyObject> = { throwError: false }
373 ): void {
374 logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error);
375 if (params?.throwError === true) {
376 throw error;
377 }
378 }
379
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
386 ): Promise<ResType>;
387 }