d14fb5703a09deea352195560ae0e98c55dc56af
[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 private readonly ocppResponseService: OCPPResponseService;
36 protected abstract jsonSchemas: Map<RequestCommand, JSONSchemaType<JsonObject>>;
37
38 protected constructor(version: OCPPVersion, ocppResponseService: OCPPResponseService) {
39 this.version = version;
40 this.ajv = new Ajv({
41 keywords: ['javaType'],
42 multipleOfPrecision: 2,
43 });
44 ajvFormats(this.ajv);
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);
53 this.validateIncomingRequestResponsePayload.bind(this);
54 }
55
56 public static getInstance<T extends OCPPRequestService>(
57 this: new (ocppResponseService: OCPPResponseService) => T,
58 ocppResponseService: OCPPResponseService
59 ): T {
60 if (OCPPRequestService.instance === null) {
61 OCPPRequestService.instance = new this(ocppResponseService);
62 }
63 return OCPPRequestService.instance as T;
64 }
65
66 public async sendResponse(
67 chargingStation: ChargingStation,
68 messageId: string,
69 messagePayload: JsonType,
70 commandName: IncomingRequestCommand
71 ): Promise<ResponseType> {
72 try {
73 // Send response message
74 return await this.internalSendMessage(
75 chargingStation,
76 messageId,
77 messagePayload,
78 MessageType.CALL_RESULT_MESSAGE,
79 commandName
80 );
81 } catch (error) {
82 this.handleSendMessageError(chargingStation, commandName, error as Error, {
83 throwError: true,
84 });
85 }
86 }
87
88 public async sendError(
89 chargingStation: ChargingStation,
90 messageId: string,
91 ocppError: OCPPError,
92 commandName: RequestCommand | IncomingRequestCommand
93 ): Promise<ResponseType> {
94 try {
95 // Send error message
96 return await this.internalSendMessage(
97 chargingStation,
98 messageId,
99 ocppError,
100 MessageType.CALL_ERROR_MESSAGE,
101 commandName
102 );
103 } catch (error) {
104 this.handleSendMessageError(chargingStation, commandName, error as Error);
105 }
106 }
107
108 protected async sendMessage(
109 chargingStation: ChargingStation,
110 messageId: string,
111 messagePayload: JsonType,
112 commandName: RequestCommand,
113 params: RequestParams = {
114 skipBufferingOnError: false,
115 triggerMessage: false,
116 }
117 ): Promise<ResponseType> {
118 try {
119 return await this.internalSendMessage(
120 chargingStation,
121 messageId,
122 messagePayload,
123 MessageType.CALL_MESSAGE,
124 commandName,
125 params
126 );
127 } catch (error) {
128 this.handleSendMessageError(chargingStation, commandName, error as Error);
129 }
130 }
131
132 private validateRequestPayload<T extends JsonObject>(
133 chargingStation: ChargingStation,
134 commandName: RequestCommand | IncomingRequestCommand,
135 payload: T
136 ): boolean {
137 if (chargingStation.getPayloadSchemaValidation() === false) {
138 return true;
139 }
140 if (this.jsonSchemas.has(commandName as RequestCommand) === false) {
141 logger.warn(
142 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: No JSON schema found for command '${commandName}' PDU validation`
143 );
144 return true;
145 }
146 const validate = this.ajv.compile(this.jsonSchemas.get(commandName as RequestCommand));
147 payload = Utils.cloneObject<T>(payload);
148 OCPPServiceUtils.convertDateToISOString<T>(payload);
149 if (validate(payload)) {
150 return true;
151 }
152 logger.error(
153 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Command '${commandName}' request PDU is invalid: %j`,
154 validate.errors
155 );
156 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
157 throw new OCPPError(
158 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
159 'Request PDU is invalid',
160 commandName,
161 JSON.stringify(validate.errors, null, 2)
162 );
163 }
164
165 private validateIncomingRequestResponsePayload<T extends JsonObject>(
166 chargingStation: ChargingStation,
167 commandName: RequestCommand | IncomingRequestCommand,
168 payload: T
169 ): boolean {
170 if (chargingStation.getPayloadSchemaValidation() === false) {
171 return true;
172 }
173 if (
174 this.ocppResponseService.jsonIncomingRequestResponseSchemas.has(
175 commandName as IncomingRequestCommand
176 ) === false
177 ) {
178 logger.warn(
179 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: No JSON schema found for command '${commandName}' PDU validation`
180 );
181 return true;
182 }
183 const validate = this.ajv.compile(
184 this.ocppResponseService.jsonIncomingRequestResponseSchemas.get(
185 commandName as IncomingRequestCommand
186 )
187 );
188 payload = Utils.cloneObject<T>(payload);
189 OCPPServiceUtils.convertDateToISOString<T>(payload);
190 if (validate(payload)) {
191 return true;
192 }
193 logger.error(
194 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: Command '${commandName}' reponse PDU is invalid: %j`,
195 validate.errors
196 );
197 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
198 throw new OCPPError(
199 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
200 'Response PDU is invalid',
201 commandName,
202 JSON.stringify(validate.errors, null, 2)
203 );
204 }
205
206 private async internalSendMessage(
207 chargingStation: ChargingStation,
208 messageId: string,
209 messagePayload: JsonType | OCPPError,
210 messageType: MessageType,
211 commandName?: RequestCommand | IncomingRequestCommand,
212 params: RequestParams = {
213 skipBufferingOnError: false,
214 triggerMessage: false,
215 }
216 ): Promise<ResponseType> {
217 if (
218 (chargingStation.isInUnknownState() === true &&
219 commandName === RequestCommand.BOOT_NOTIFICATION) ||
220 (chargingStation.getOcppStrictCompliance() === false &&
221 chargingStation.isInUnknownState() === true) ||
222 chargingStation.isInAcceptedState() === true ||
223 (chargingStation.isInPendingState() === true &&
224 (params.triggerMessage === true || messageType === MessageType.CALL_RESULT_MESSAGE))
225 ) {
226 // eslint-disable-next-line @typescript-eslint/no-this-alias
227 const self = this;
228 // Send a message through wsConnection
229 return Utils.promiseWithTimeout(
230 new Promise((resolve, reject) => {
231 const messageToSend = this.buildMessageToSend(
232 chargingStation,
233 messageId,
234 messagePayload,
235 messageType,
236 commandName,
237 responseCallback,
238 errorCallback
239 );
240 if (chargingStation.getEnableStatistics() === true) {
241 chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
242 }
243 // Check if wsConnection opened
244 if (chargingStation.isWebSocketConnectionOpened() === true) {
245 // Yes: Send Message
246 const beginId = PerformanceStatistics.beginMeasure(commandName as string);
247 // FIXME: Handle sending error
248 chargingStation.wsConnection.send(messageToSend);
249 PerformanceStatistics.endMeasure(commandName as string, beginId);
250 logger.debug(
251 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
252 messageType
253 )} payload: ${messageToSend}`
254 );
255 } else if (params.skipBufferingOnError === false) {
256 // Buffer it
257 chargingStation.bufferMessage(messageToSend);
258 const ocppError = new OCPPError(
259 ErrorType.GENERIC_ERROR,
260 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
261 commandName,
262 (messagePayload as JsonObject)?.details ?? {}
263 );
264 if (messageType === MessageType.CALL_MESSAGE) {
265 // Reject it but keep the request in the cache
266 return reject(ocppError);
267 }
268 return errorCallback(ocppError, false);
269 } else {
270 // Reject it
271 return errorCallback(
272 new OCPPError(
273 ErrorType.GENERIC_ERROR,
274 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
275 commandName,
276 (messagePayload as JsonObject)?.details ?? {}
277 ),
278 false
279 );
280 }
281 // Response?
282 if (messageType !== MessageType.CALL_MESSAGE) {
283 // Yes: send Ok
284 return resolve(messagePayload);
285 }
286
287 /**
288 * Function that will receive the request's response
289 *
290 * @param payload -
291 * @param requestPayload -
292 */
293 function responseCallback(payload: JsonType, requestPayload: JsonType): void {
294 if (chargingStation.getEnableStatistics() === true) {
295 chargingStation.performanceStatistics.addRequestStatistic(
296 commandName,
297 MessageType.CALL_RESULT_MESSAGE
298 );
299 }
300 // Handle the request's response
301 self.ocppResponseService
302 .responseHandler(
303 chargingStation,
304 commandName as RequestCommand,
305 payload,
306 requestPayload
307 )
308 .then(() => {
309 resolve(payload);
310 })
311 .catch((error) => {
312 reject(error);
313 })
314 .finally(() => {
315 chargingStation.requests.delete(messageId);
316 });
317 }
318
319 /**
320 * Function that will receive the request's error response
321 *
322 * @param error -
323 * @param requestStatistic -
324 */
325 function errorCallback(error: OCPPError, requestStatistic = true): void {
326 if (requestStatistic === true && chargingStation.getEnableStatistics() === true) {
327 chargingStation.performanceStatistics.addRequestStatistic(
328 commandName,
329 MessageType.CALL_ERROR_MESSAGE
330 );
331 }
332 logger.error(
333 `${chargingStation.logPrefix()} Error occurred when calling command ${commandName} with message data ${JSON.stringify(
334 messagePayload
335 )}:`,
336 error
337 );
338 chargingStation.requests.delete(messageId);
339 reject(error);
340 }
341 }),
342 Constants.OCPP_WEBSOCKET_TIMEOUT,
343 new OCPPError(
344 ErrorType.GENERIC_ERROR,
345 `Timeout for message id '${messageId}'`,
346 commandName,
347 (messagePayload as JsonObject)?.details ?? {}
348 ),
349 () => {
350 messageType === MessageType.CALL_MESSAGE && chargingStation.requests.delete(messageId);
351 }
352 );
353 }
354 throw new OCPPError(
355 ErrorType.SECURITY_ERROR,
356 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
357 commandName
358 );
359 }
360
361 private buildMessageToSend(
362 chargingStation: ChargingStation,
363 messageId: string,
364 messagePayload: JsonType | OCPPError,
365 messageType: MessageType,
366 commandName?: RequestCommand | IncomingRequestCommand,
367 responseCallback?: ResponseCallback,
368 errorCallback?: ErrorCallback
369 ): string {
370 let messageToSend: string;
371 // Type of message
372 switch (messageType) {
373 // Request
374 case MessageType.CALL_MESSAGE:
375 // Build request
376 chargingStation.requests.set(messageId, [
377 responseCallback,
378 errorCallback,
379 commandName,
380 messagePayload as JsonType,
381 ]);
382 this.validateRequestPayload(chargingStation, commandName, messagePayload as JsonObject);
383 messageToSend = JSON.stringify([
384 messageType,
385 messageId,
386 commandName,
387 messagePayload,
388 ] as OutgoingRequest);
389 break;
390 // Response
391 case MessageType.CALL_RESULT_MESSAGE:
392 // Build response
393 this.validateIncomingRequestResponsePayload(
394 chargingStation,
395 commandName,
396 messagePayload as JsonObject
397 );
398 messageToSend = JSON.stringify([messageType, messageId, messagePayload] as Response);
399 break;
400 // Error Message
401 case MessageType.CALL_ERROR_MESSAGE:
402 // Build Error Message
403 messageToSend = JSON.stringify([
404 messageType,
405 messageId,
406 (messagePayload as OCPPError)?.code ?? ErrorType.GENERIC_ERROR,
407 (messagePayload as OCPPError)?.message ?? '',
408 (messagePayload as OCPPError)?.details ?? { commandName },
409 ] as ErrorResponse);
410 break;
411 }
412 return messageToSend;
413 }
414
415 private getMessageTypeString(messageType: MessageType): string {
416 switch (messageType) {
417 case MessageType.CALL_MESSAGE:
418 return 'request';
419 case MessageType.CALL_RESULT_MESSAGE:
420 return 'response';
421 case MessageType.CALL_ERROR_MESSAGE:
422 return 'error';
423 }
424 }
425
426 private handleSendMessageError(
427 chargingStation: ChargingStation,
428 commandName: RequestCommand | IncomingRequestCommand,
429 error: Error,
430 params: HandleErrorParams<EmptyObject> = { throwError: false }
431 ): void {
432 logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error);
433 if (params?.throwError === true) {
434 throw error;
435 }
436 }
437
438 // eslint-disable-next-line @typescript-eslint/no-unused-vars
439 public abstract requestHandler<ReqType extends JsonType, ResType extends JsonType>(
440 chargingStation: ChargingStation,
441 commandName: RequestCommand,
442 commandParams?: JsonType,
443 params?: RequestParams
444 ): Promise<ResType>;
445 }