Cleanups
[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 logger.debug(
253 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
254 messageType
255 )} payload: ${messageToSend}`
256 );
257 } catch (error) {
258 logger.error(
259 `${chargingStation.logPrefix()} >> Command '${commandName}' failed to send ${this.getMessageTypeString(
260 messageType
261 )} payload: ${messageToSend}:`,
262 error
263 );
264 sendError = true;
265 }
266 PerformanceStatistics.endMeasure(commandName as string, beginId);
267 }
268 const wsClosedOrErrored =
269 chargingStation.isWebSocketConnectionOpened() === false || sendError === true;
270 if (wsClosedOrErrored && params.skipBufferingOnError === false) {
271 // Buffer
272 chargingStation.bufferMessage(messageToSend);
273 // Reject and keep request in the cache
274 return reject(
275 new OCPPError(
276 ErrorType.GENERIC_ERROR,
277 `WebSocket closed or errored for buffered message id '${messageId}' with content '${messageToSend}'`,
278 commandName,
279 (messagePayload as JsonObject)?.details ?? {}
280 )
281 );
282 } else if (wsClosedOrErrored) {
283 const ocppError = new OCPPError(
284 ErrorType.GENERIC_ERROR,
285 `WebSocket closed or errored for non buffered message id '${messageId}' with content '${messageToSend}'`,
286 commandName,
287 (messagePayload as JsonObject)?.details ?? {}
288 );
289 // Reject response
290 if (messageType !== MessageType.CALL_MESSAGE) {
291 return reject(ocppError);
292 }
293 // Reject and remove request from the cache
294 return errorCallback(ocppError, false);
295 }
296 // Resolve response
297 if (messageType !== MessageType.CALL_MESSAGE) {
298 return resolve(messagePayload);
299 }
300
301 /**
302 * Function that will receive the request's response
303 *
304 * @param payload -
305 * @param requestPayload -
306 */
307 function responseCallback(payload: JsonType, requestPayload: JsonType): void {
308 if (chargingStation.getEnableStatistics() === true) {
309 chargingStation.performanceStatistics.addRequestStatistic(
310 commandName,
311 MessageType.CALL_RESULT_MESSAGE
312 );
313 }
314 // Handle the request's response
315 self.ocppResponseService
316 .responseHandler(
317 chargingStation,
318 commandName as RequestCommand,
319 payload,
320 requestPayload
321 )
322 .then(() => {
323 resolve(payload);
324 })
325 .catch((error) => {
326 reject(error);
327 })
328 .finally(() => {
329 chargingStation.requests.delete(messageId);
330 });
331 }
332
333 /**
334 * Function that will receive the request's error response
335 *
336 * @param error -
337 * @param requestStatistic -
338 */
339 function errorCallback(error: OCPPError, requestStatistic = true): void {
340 if (requestStatistic === true && chargingStation.getEnableStatistics() === true) {
341 chargingStation.performanceStatistics.addRequestStatistic(
342 commandName,
343 MessageType.CALL_ERROR_MESSAGE
344 );
345 }
346 logger.error(
347 `${chargingStation.logPrefix()} Error occurred at ${self.getMessageTypeString(
348 messageType
349 )} command ${commandName} with PDU %j:`,
350 messagePayload,
351 error
352 );
353 chargingStation.requests.delete(messageId);
354 reject(error);
355 }
356 }),
357 Constants.OCPP_WEBSOCKET_TIMEOUT,
358 new OCPPError(
359 ErrorType.GENERIC_ERROR,
360 `Timeout for message id '${messageId}'`,
361 commandName,
362 (messagePayload as JsonObject)?.details ?? {}
363 ),
364 () => {
365 messageType === MessageType.CALL_MESSAGE && chargingStation.requests.delete(messageId);
366 }
367 );
368 }
369 throw new OCPPError(
370 ErrorType.SECURITY_ERROR,
371 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
372 commandName
373 );
374 }
375
376 private buildMessageToSend(
377 chargingStation: ChargingStation,
378 messageId: string,
379 messagePayload: JsonType | OCPPError,
380 messageType: MessageType,
381 commandName?: RequestCommand | IncomingRequestCommand,
382 responseCallback?: ResponseCallback,
383 errorCallback?: ErrorCallback
384 ): string {
385 let messageToSend: string;
386 // Type of message
387 switch (messageType) {
388 // Request
389 case MessageType.CALL_MESSAGE:
390 // Build request
391 this.validateRequestPayload(chargingStation, commandName, messagePayload as JsonObject);
392 chargingStation.requests.set(messageId, [
393 responseCallback,
394 errorCallback,
395 commandName,
396 messagePayload as JsonType,
397 ]);
398 messageToSend = JSON.stringify([
399 messageType,
400 messageId,
401 commandName,
402 messagePayload,
403 ] as OutgoingRequest);
404 break;
405 // Response
406 case MessageType.CALL_RESULT_MESSAGE:
407 // Build response
408 this.validateIncomingRequestResponsePayload(
409 chargingStation,
410 commandName,
411 messagePayload as JsonObject
412 );
413 messageToSend = JSON.stringify([messageType, messageId, messagePayload] as Response);
414 break;
415 // Error Message
416 case MessageType.CALL_ERROR_MESSAGE:
417 // Build Error Message
418 messageToSend = JSON.stringify([
419 messageType,
420 messageId,
421 (messagePayload as OCPPError)?.code ?? ErrorType.GENERIC_ERROR,
422 (messagePayload as OCPPError)?.message ?? '',
423 (messagePayload as OCPPError)?.details ?? { commandName },
424 ] as ErrorResponse);
425 break;
426 }
427 return messageToSend;
428 }
429
430 private getMessageTypeString(messageType: MessageType): string {
431 switch (messageType) {
432 case MessageType.CALL_MESSAGE:
433 return 'request';
434 case MessageType.CALL_RESULT_MESSAGE:
435 return 'response';
436 case MessageType.CALL_ERROR_MESSAGE:
437 return 'error';
438 }
439 }
440
441 private handleSendMessageError(
442 chargingStation: ChargingStation,
443 commandName: RequestCommand | IncomingRequestCommand,
444 error: Error,
445 params: HandleErrorParams<EmptyObject> = { throwError: false }
446 ): void {
447 logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error);
448 if (params?.throwError === true) {
449 throw error;
450 }
451 }
452
453 // eslint-disable-next-line @typescript-eslint/no-unused-vars
454 public abstract requestHandler<ReqType extends JsonType, ResType extends JsonType>(
455 chargingStation: ChargingStation,
456 commandName: RequestCommand,
457 commandParams?: JsonType,
458 params?: RequestParams
459 ): Promise<ResType>;
460 }