b72c2a8c2da99460627fee6cb9d9fc7de8b87e3a
[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 type OCPPResponseService from './OCPPResponseService';
5 import { OCPPServiceUtils } from './OCPPServiceUtils';
6 import OCPPError from '../../exception/OCPPError';
7 import PerformanceStatistics from '../../performance/PerformanceStatistics';
8 import type { EmptyObject } from '../../types/EmptyObject';
9 import type { HandleErrorParams } from '../../types/Error';
10 import type { JsonObject, JsonType } from '../../types/JsonType';
11 import { ErrorType } from '../../types/ocpp/ErrorType';
12 import { MessageType } from '../../types/ocpp/MessageType';
13 import type { OCPPVersion } from '../../types/ocpp/OCPPVersion';
14 import {
15 type ErrorCallback,
16 type IncomingRequestCommand,
17 type OutgoingRequest,
18 RequestCommand,
19 type RequestParams,
20 type ResponseCallback,
21 type ResponseType,
22 } from '../../types/ocpp/Requests';
23 import type { ErrorResponse, Response } from '../../types/ocpp/Responses';
24 import Constants from '../../utils/Constants';
25 import logger from '../../utils/Logger';
26 import Utils from '../../utils/Utils';
27 import type ChargingStation from '../ChargingStation';
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 throwError: false,
117 }
118 ): Promise<ResponseType> {
119 try {
120 return await this.internalSendMessage(
121 chargingStation,
122 messageId,
123 messagePayload,
124 MessageType.CALL_MESSAGE,
125 commandName,
126 params
127 );
128 } catch (error) {
129 this.handleSendMessageError(chargingStation, commandName, error as Error, {
130 throwError: params.throwError,
131 });
132 }
133 }
134
135 private validateRequestPayload<T extends JsonObject>(
136 chargingStation: ChargingStation,
137 commandName: RequestCommand | IncomingRequestCommand,
138 payload: T
139 ): boolean {
140 if (chargingStation.getPayloadSchemaValidation() === false) {
141 return true;
142 }
143 if (this.jsonSchemas.has(commandName as RequestCommand) === false) {
144 logger.warn(
145 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: No JSON schema found for command '${commandName}' PDU validation`
146 );
147 return true;
148 }
149 const validate = this.ajv.compile(this.jsonSchemas.get(commandName as RequestCommand));
150 payload = Utils.cloneObject<T>(payload);
151 OCPPServiceUtils.convertDateToISOString<T>(payload);
152 if (validate(payload)) {
153 return true;
154 }
155 logger.error(
156 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Command '${commandName}' request PDU is invalid: %j`,
157 validate.errors
158 );
159 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
160 throw new OCPPError(
161 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
162 'Request PDU is invalid',
163 commandName,
164 JSON.stringify(validate.errors, null, 2)
165 );
166 }
167
168 private validateIncomingRequestResponsePayload<T extends JsonObject>(
169 chargingStation: ChargingStation,
170 commandName: RequestCommand | IncomingRequestCommand,
171 payload: T
172 ): boolean {
173 if (chargingStation.getPayloadSchemaValidation() === false) {
174 return true;
175 }
176 if (
177 this.ocppResponseService.jsonIncomingRequestResponseSchemas.has(
178 commandName as IncomingRequestCommand
179 ) === false
180 ) {
181 logger.warn(
182 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: No JSON schema found for command '${commandName}' PDU validation`
183 );
184 return true;
185 }
186 const validate = this.ajv.compile(
187 this.ocppResponseService.jsonIncomingRequestResponseSchemas.get(
188 commandName as IncomingRequestCommand
189 )
190 );
191 payload = Utils.cloneObject<T>(payload);
192 OCPPServiceUtils.convertDateToISOString<T>(payload);
193 if (validate(payload)) {
194 return true;
195 }
196 logger.error(
197 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: Command '${commandName}' reponse PDU is invalid: %j`,
198 validate.errors
199 );
200 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
201 throw new OCPPError(
202 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
203 'Response PDU is invalid',
204 commandName,
205 JSON.stringify(validate.errors, null, 2)
206 );
207 }
208
209 private async internalSendMessage(
210 chargingStation: ChargingStation,
211 messageId: string,
212 messagePayload: JsonType | OCPPError,
213 messageType: MessageType,
214 commandName?: RequestCommand | IncomingRequestCommand,
215 params: RequestParams = {
216 skipBufferingOnError: false,
217 triggerMessage: false,
218 }
219 ): Promise<ResponseType> {
220 if (
221 (chargingStation.isInUnknownState() === true &&
222 commandName === RequestCommand.BOOT_NOTIFICATION) ||
223 (chargingStation.getOcppStrictCompliance() === false &&
224 chargingStation.isInUnknownState() === true) ||
225 chargingStation.isInAcceptedState() === true ||
226 (chargingStation.isInPendingState() === true &&
227 (params.triggerMessage === true || messageType === MessageType.CALL_RESULT_MESSAGE))
228 ) {
229 // eslint-disable-next-line @typescript-eslint/no-this-alias
230 const self = this;
231 // Send a message through wsConnection
232 return Utils.promiseWithTimeout(
233 new Promise((resolve, reject) => {
234 const messageToSend = this.buildMessageToSend(
235 chargingStation,
236 messageId,
237 messagePayload,
238 messageType,
239 commandName,
240 responseCallback,
241 errorCallback
242 );
243 if (chargingStation.getEnableStatistics() === true) {
244 chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
245 }
246 let sendError = false;
247 // Check if wsConnection opened
248 if (chargingStation.isWebSocketConnectionOpened() === true) {
249 const beginId = PerformanceStatistics.beginMeasure(commandName as string);
250 try {
251 chargingStation.wsConnection.send(messageToSend);
252 } catch (error) {
253 sendError = true;
254 }
255 PerformanceStatistics.endMeasure(commandName as string, beginId);
256 logger.debug(
257 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
258 messageType
259 )} payload: ${messageToSend}`
260 );
261 }
262 const wsClosedOrErrored =
263 chargingStation.isWebSocketConnectionOpened() === false || sendError === true;
264 if (wsClosedOrErrored && params.skipBufferingOnError === false) {
265 // Buffer
266 chargingStation.bufferMessage(messageToSend);
267 // Reject and keep request in the cache
268 return reject(
269 new OCPPError(
270 ErrorType.GENERIC_ERROR,
271 `WebSocket closed or errored for buffered message id '${messageId}' with content '${messageToSend}'`,
272 commandName,
273 (messagePayload as JsonObject)?.details ?? {}
274 )
275 );
276 } else if (wsClosedOrErrored) {
277 const ocppError = new OCPPError(
278 ErrorType.GENERIC_ERROR,
279 `WebSocket closed or errored for non buffered message id '${messageId}' with content '${messageToSend}'`,
280 commandName,
281 (messagePayload as JsonObject)?.details ?? {}
282 );
283 // Reject response
284 if (messageType !== MessageType.CALL_MESSAGE) {
285 return reject(ocppError);
286 }
287 // Reject and remove request from the cache
288 return errorCallback(ocppError, false);
289 }
290 // Resolve response
291 if (messageType !== MessageType.CALL_MESSAGE) {
292 return resolve(messagePayload);
293 }
294
295 /**
296 * Function that will receive the request's response
297 *
298 * @param payload -
299 * @param requestPayload -
300 */
301 function responseCallback(payload: JsonType, requestPayload: JsonType): void {
302 if (chargingStation.getEnableStatistics() === true) {
303 chargingStation.performanceStatistics.addRequestStatistic(
304 commandName,
305 MessageType.CALL_RESULT_MESSAGE
306 );
307 }
308 // Handle the request's response
309 self.ocppResponseService
310 .responseHandler(
311 chargingStation,
312 commandName as RequestCommand,
313 payload,
314 requestPayload
315 )
316 .then(() => {
317 resolve(payload);
318 })
319 .catch((error) => {
320 reject(error);
321 })
322 .finally(() => {
323 chargingStation.requests.delete(messageId);
324 });
325 }
326
327 /**
328 * Function that will receive the request's error response
329 *
330 * @param error -
331 * @param requestStatistic -
332 */
333 function errorCallback(error: OCPPError, requestStatistic = true): void {
334 if (requestStatistic === true && chargingStation.getEnableStatistics() === true) {
335 chargingStation.performanceStatistics.addRequestStatistic(
336 commandName,
337 MessageType.CALL_ERROR_MESSAGE
338 );
339 }
340 logger.error(
341 `${chargingStation.logPrefix()} Error occurred at ${self.getMessageTypeString(
342 messageType
343 )} command ${commandName} with PDU %j:`,
344 messagePayload,
345 error
346 );
347 chargingStation.requests.delete(messageId);
348 reject(error);
349 }
350 }),
351 Constants.OCPP_WEBSOCKET_TIMEOUT,
352 new OCPPError(
353 ErrorType.GENERIC_ERROR,
354 `Timeout for message id '${messageId}'`,
355 commandName,
356 (messagePayload as JsonObject)?.details ?? {}
357 ),
358 () => {
359 messageType === MessageType.CALL_MESSAGE && chargingStation.requests.delete(messageId);
360 }
361 );
362 }
363 throw new OCPPError(
364 ErrorType.SECURITY_ERROR,
365 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
366 commandName
367 );
368 }
369
370 private buildMessageToSend(
371 chargingStation: ChargingStation,
372 messageId: string,
373 messagePayload: JsonType | OCPPError,
374 messageType: MessageType,
375 commandName?: RequestCommand | IncomingRequestCommand,
376 responseCallback?: ResponseCallback,
377 errorCallback?: ErrorCallback
378 ): string {
379 let messageToSend: string;
380 // Type of message
381 switch (messageType) {
382 // Request
383 case MessageType.CALL_MESSAGE:
384 // Build request
385 this.validateRequestPayload(chargingStation, commandName, messagePayload as JsonObject);
386 chargingStation.requests.set(messageId, [
387 responseCallback,
388 errorCallback,
389 commandName,
390 messagePayload as JsonType,
391 ]);
392 messageToSend = JSON.stringify([
393 messageType,
394 messageId,
395 commandName,
396 messagePayload,
397 ] as OutgoingRequest);
398 break;
399 // Response
400 case MessageType.CALL_RESULT_MESSAGE:
401 // Build response
402 this.validateIncomingRequestResponsePayload(
403 chargingStation,
404 commandName,
405 messagePayload as JsonObject
406 );
407 messageToSend = JSON.stringify([messageType, messageId, messagePayload] as Response);
408 break;
409 // Error Message
410 case MessageType.CALL_ERROR_MESSAGE:
411 // Build Error Message
412 messageToSend = JSON.stringify([
413 messageType,
414 messageId,
415 (messagePayload as OCPPError)?.code ?? ErrorType.GENERIC_ERROR,
416 (messagePayload as OCPPError)?.message ?? '',
417 (messagePayload as OCPPError)?.details ?? { commandName },
418 ] as ErrorResponse);
419 break;
420 }
421 return messageToSend;
422 }
423
424 private getMessageTypeString(messageType: MessageType): string {
425 switch (messageType) {
426 case MessageType.CALL_MESSAGE:
427 return 'request';
428 case MessageType.CALL_RESULT_MESSAGE:
429 return 'response';
430 case MessageType.CALL_ERROR_MESSAGE:
431 return 'error';
432 }
433 }
434
435 private handleSendMessageError(
436 chargingStation: ChargingStation,
437 commandName: RequestCommand | IncomingRequestCommand,
438 error: Error,
439 params: HandleErrorParams<EmptyObject> = { throwError: false }
440 ): void {
441 logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error);
442 if (params?.throwError === true) {
443 throw error;
444 }
445 }
446
447 // eslint-disable-next-line @typescript-eslint/no-unused-vars
448 public abstract requestHandler<ReqType extends JsonType, ResType extends JsonType>(
449 chargingStation: ChargingStation,
450 commandName: RequestCommand,
451 commandParams?: JsonType,
452 params?: RequestParams
453 ): Promise<ResType>;
454 }