Cleanup some helpers defaults values
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPRequestService.ts
CommitLineData
d270cc87 1import Ajv, { type JSONSchemaType } from 'ajv';
b52c969d
JB
2import ajvFormats from 'ajv-formats';
3
78202038
JB
4import type OCPPResponseService from './OCPPResponseService';
5import { OCPPServiceUtils } from './OCPPServiceUtils';
8114d10e
JB
6import OCPPError from '../../exception/OCPPError';
7import PerformanceStatistics from '../../performance/PerformanceStatistics';
6c1761d4
JB
8import type { EmptyObject } from '../../types/EmptyObject';
9import type { HandleErrorParams } from '../../types/Error';
10import type { JsonObject, JsonType } from '../../types/JsonType';
8114d10e
JB
11import { ErrorType } from '../../types/ocpp/ErrorType';
12import { MessageType } from '../../types/ocpp/MessageType';
b0342994 13import type { OCPPVersion } from '../../types/ocpp/OCPPVersion';
e7aeea18 14import {
27782dbc
JB
15 type ErrorCallback,
16 type IncomingRequestCommand,
17 type OutgoingRequest,
e7aeea18 18 RequestCommand,
27782dbc
JB
19 type RequestParams,
20 type ResponseCallback,
e0b0ee21 21 type ResponseType,
e7aeea18 22} from '../../types/ocpp/Requests';
6c1761d4 23import type { ErrorResponse, Response } from '../../types/ocpp/Responses';
c0560973 24import Constants from '../../utils/Constants';
9f2e3130 25import logger from '../../utils/Logger';
8114d10e
JB
26import Utils from '../../utils/Utils';
27import type ChargingStation from '../ChargingStation';
c0560973 28
e3018bc4
JB
29const moduleName = 'OCPPRequestService';
30
c0560973 31export default abstract class OCPPRequestService {
08f130a0 32 private static instance: OCPPRequestService | null = null;
d270cc87 33 private readonly version: OCPPVersion;
012ae1a9 34 private readonly ajv: Ajv;
9f2e3130 35 private readonly ocppResponseService: OCPPResponseService;
b3fc3ff5 36 protected abstract jsonSchemas: Map<RequestCommand, JSONSchemaType<JsonObject>>;
c0560973 37
d270cc87
JB
38 protected constructor(version: OCPPVersion, ocppResponseService: OCPPResponseService) {
39 this.version = version;
45988780 40 this.ajv = new Ajv({
98fc1389 41 keywords: ['javaType'],
45988780
JB
42 multipleOfPrecision: 2,
43 });
9952c548 44 ajvFormats(this.ajv);
d270cc87 45 this.ocppResponseService = ocppResponseService;
f7f98c68 46 this.requestHandler.bind(this);
511c1897 47 this.sendMessage.bind(this);
c75a6675 48 this.sendResponse.bind(this);
54ce9b7d 49 this.sendError.bind(this);
9952c548
JB
50 this.internalSendMessage.bind(this);
51 this.buildMessageToSend.bind(this);
52 this.validateRequestPayload.bind(this);
02887891 53 this.validateIncomingRequestResponsePayload.bind(this);
c0560973
JB
54 }
55
e7aeea18 56 public static getInstance<T extends OCPPRequestService>(
08f130a0 57 this: new (ocppResponseService: OCPPResponseService) => T,
e7aeea18
JB
58 ocppResponseService: OCPPResponseService
59 ): T {
1ca780f9 60 if (OCPPRequestService.instance === null) {
08f130a0 61 OCPPRequestService.instance = new this(ocppResponseService);
9f2e3130 62 }
08f130a0 63 return OCPPRequestService.instance as T;
9f2e3130
JB
64 }
65
c75a6675 66 public async sendResponse(
08f130a0 67 chargingStation: ChargingStation,
e7aeea18 68 messageId: string,
5cc4b63b 69 messagePayload: JsonType,
e7aeea18
JB
70 commandName: IncomingRequestCommand
71 ): Promise<ResponseType> {
5e0c67e8 72 try {
c75a6675 73 // Send response message
e7aeea18 74 return await this.internalSendMessage(
08f130a0 75 chargingStation,
e7aeea18
JB
76 messageId,
77 messagePayload,
78 MessageType.CALL_RESULT_MESSAGE,
79 commandName
80 );
5e0c67e8 81 } catch (error) {
dc922667 82 this.handleSendMessageError(chargingStation, commandName, error as Error, {
07561812 83 throwError: true,
dc922667 84 });
5e0c67e8
JB
85 }
86 }
87
e7aeea18 88 public async sendError(
08f130a0 89 chargingStation: ChargingStation,
e7aeea18
JB
90 messageId: string,
91 ocppError: OCPPError,
b3ec7bc1 92 commandName: RequestCommand | IncomingRequestCommand
e7aeea18 93 ): Promise<ResponseType> {
5e0c67e8
JB
94 try {
95 // Send error message
e7aeea18 96 return await this.internalSendMessage(
08f130a0 97 chargingStation,
e7aeea18
JB
98 messageId,
99 ocppError,
100 MessageType.CALL_ERROR_MESSAGE,
101 commandName
102 );
5e0c67e8 103 } catch (error) {
dc922667 104 this.handleSendMessageError(chargingStation, commandName, error as Error);
5e0c67e8
JB
105 }
106 }
107
e7aeea18 108 protected async sendMessage(
08f130a0 109 chargingStation: ChargingStation,
e7aeea18 110 messageId: string,
5cc4b63b 111 messagePayload: JsonType,
e7aeea18 112 commandName: RequestCommand,
be9b0d50 113 params: RequestParams = {
e7aeea18
JB
114 skipBufferingOnError: false,
115 triggerMessage: false,
8ec8e3d0 116 throwError: false,
e7aeea18
JB
117 }
118 ): Promise<ResponseType> {
5e0c67e8 119 try {
e7aeea18 120 return await this.internalSendMessage(
08f130a0 121 chargingStation,
e7aeea18
JB
122 messageId,
123 messagePayload,
124 MessageType.CALL_MESSAGE,
125 commandName,
126 params
127 );
5e0c67e8 128 } catch (error) {
8ec8e3d0
JB
129 this.handleSendMessageError(chargingStation, commandName, error as Error, {
130 throwError: params.throwError,
131 });
5e0c67e8
JB
132 }
133 }
134
02887891 135 private validateRequestPayload<T extends JsonObject>(
b52c969d 136 chargingStation: ChargingStation,
45988780 137 commandName: RequestCommand | IncomingRequestCommand,
b52c969d
JB
138 payload: T
139 ): boolean {
0638ddd2 140 if (chargingStation.getPayloadSchemaValidation() === false) {
b52c969d
JB
141 return true;
142 }
b3fc3ff5
JB
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 );
45988780
JB
147 return true;
148 }
b3fc3ff5
JB
149 const validate = this.ajv.compile(this.jsonSchemas.get(commandName as RequestCommand));
150 payload = Utils.cloneObject<T>(payload);
1799761a 151 OCPPServiceUtils.convertDateToISOString<T>(payload);
b52c969d
JB
152 if (validate(payload)) {
153 return true;
154 }
155 logger.error(
45988780 156 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Command '${commandName}' request PDU is invalid: %j`,
b52c969d
JB
157 validate.errors
158 );
e909d2a7 159 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
b52c969d 160 throw new OCPPError(
01a4dcbb 161 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
b52c969d
JB
162 'Request PDU is invalid',
163 commandName,
164 JSON.stringify(validate.errors, null, 2)
165 );
166 }
167
02887891 168 private validateIncomingRequestResponsePayload<T extends JsonObject>(
b3fc3ff5
JB
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(
02887891 182 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: No JSON schema found for command '${commandName}' PDU validation`
b3fc3ff5
JB
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(
02887891 197 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: Command '${commandName}' reponse PDU is invalid: %j`,
b3fc3ff5
JB
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
e7aeea18 209 private async internalSendMessage(
08f130a0 210 chargingStation: ChargingStation,
e7aeea18 211 messageId: string,
5cc4b63b 212 messagePayload: JsonType | OCPPError,
e7aeea18
JB
213 messageType: MessageType,
214 commandName?: RequestCommand | IncomingRequestCommand,
be9b0d50 215 params: RequestParams = {
e7aeea18
JB
216 skipBufferingOnError: false,
217 triggerMessage: false,
218 }
219 ): Promise<ResponseType> {
220 if (
3a13fc92
JB
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))
e7aeea18 228 ) {
caad9d6b
JB
229 // eslint-disable-next-line @typescript-eslint/no-this-alias
230 const self = this;
231 // Send a message through wsConnection
e7aeea18
JB
232 return Utils.promiseWithTimeout(
233 new Promise((resolve, reject) => {
234 const messageToSend = this.buildMessageToSend(
08f130a0 235 chargingStation,
e7aeea18
JB
236 messageId,
237 messagePayload,
238 messageType,
239 commandName,
240 responseCallback,
a2d1c0f1 241 errorCallback
e7aeea18 242 );
0638ddd2 243 if (chargingStation.getEnableStatistics() === true) {
08f130a0 244 chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
caad9d6b 245 }
1b821a64 246 let sendError = false;
e7aeea18 247 // Check if wsConnection opened
0638ddd2 248 if (chargingStation.isWebSocketConnectionOpened() === true) {
edd13439 249 const beginId = PerformanceStatistics.beginMeasure(commandName as string);
1b821a64
JB
250 try {
251 chargingStation.wsConnection.send(messageToSend);
252 } catch (error) {
253 sendError = true;
254 }
edd13439 255 PerformanceStatistics.endMeasure(commandName as string, beginId);
6f35d2da 256 logger.debug(
08f130a0 257 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
9a3b8d9f
JB
258 messageType
259 )} payload: ${messageToSend}`
6f35d2da 260 );
1b821a64
JB
261 }
262 const wsClosedOrErrored =
263 chargingStation.isWebSocketConnectionOpened() === false || sendError === true;
264 if (wsClosedOrErrored && params.skipBufferingOnError === false) {
265 // Buffer
08f130a0 266 chargingStation.bufferMessage(messageToSend);
1b821a64
JB
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) {
e7aeea18
JB
277 const ocppError = new OCPPError(
278 ErrorType.GENERIC_ERROR,
1b821a64 279 `WebSocket closed or errored for non buffered message id '${messageId}' with content '${messageToSend}'`,
e7aeea18 280 commandName,
5cc4b63b 281 (messagePayload as JsonObject)?.details ?? {}
e7aeea18 282 );
1b821a64
JB
283 // Reject response
284 if (messageType !== MessageType.CALL_MESSAGE) {
e7aeea18
JB
285 return reject(ocppError);
286 }
1b821a64 287 // Reject and remove request from the cache
a2d1c0f1 288 return errorCallback(ocppError, false);
caad9d6b 289 }
1b821a64 290 // Resolve response
e7aeea18 291 if (messageType !== MessageType.CALL_MESSAGE) {
e7aeea18
JB
292 return resolve(messagePayload);
293 }
294
295 /**
296 * Function that will receive the request's response
297 *
0e4fa348
JB
298 * @param payload -
299 * @param requestPayload -
e7aeea18 300 */
3a148e48 301 function responseCallback(payload: JsonType, requestPayload: JsonType): void {
0638ddd2 302 if (chargingStation.getEnableStatistics() === true) {
08f130a0 303 chargingStation.performanceStatistics.addRequestStatistic(
e7aeea18
JB
304 commandName,
305 MessageType.CALL_RESULT_MESSAGE
306 );
307 }
308 // Handle the request's response
3a148e48
JB
309 self.ocppResponseService
310 .responseHandler(
08f130a0 311 chargingStation,
e7aeea18
JB
312 commandName as RequestCommand,
313 payload,
314 requestPayload
3a148e48
JB
315 )
316 .then(() => {
317 resolve(payload);
318 })
319 .catch((error) => {
320 reject(error);
321 })
322 .finally(() => {
323 chargingStation.requests.delete(messageId);
324 });
caad9d6b 325 }
caad9d6b 326
e7aeea18
JB
327 /**
328 * Function that will receive the request's error response
329 *
0e4fa348
JB
330 * @param error -
331 * @param requestStatistic -
e7aeea18 332 */
a2d1c0f1 333 function errorCallback(error: OCPPError, requestStatistic = true): void {
0afed85f 334 if (requestStatistic === true && chargingStation.getEnableStatistics() === true) {
08f130a0 335 chargingStation.performanceStatistics.addRequestStatistic(
e7aeea18
JB
336 commandName,
337 MessageType.CALL_ERROR_MESSAGE
338 );
339 }
340 logger.error(
1b821a64
JB
341 `${chargingStation.logPrefix()} Error occurred at ${self.getMessageTypeString(
342 messageType
343 )} command ${commandName} with PDU %j:`,
344 messagePayload,
fc040c43 345 error
e7aeea18 346 );
08f130a0 347 chargingStation.requests.delete(messageId);
e7aeea18 348 reject(error);
caad9d6b 349 }
e7aeea18
JB
350 }),
351 Constants.OCPP_WEBSOCKET_TIMEOUT,
352 new OCPPError(
353 ErrorType.GENERIC_ERROR,
354 `Timeout for message id '${messageId}'`,
355 commandName,
5cc4b63b 356 (messagePayload as JsonObject)?.details ?? {}
e7aeea18
JB
357 ),
358 () => {
08f130a0 359 messageType === MessageType.CALL_MESSAGE && chargingStation.requests.delete(messageId);
caad9d6b 360 }
e7aeea18 361 );
caad9d6b 362 }
e7aeea18
JB
363 throw new OCPPError(
364 ErrorType.SECURITY_ERROR,
e3018bc4 365 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
e7aeea18
JB
366 commandName
367 );
c0560973
JB
368 }
369
e7aeea18 370 private buildMessageToSend(
08f130a0 371 chargingStation: ChargingStation,
e7aeea18 372 messageId: string,
5cc4b63b 373 messagePayload: JsonType | OCPPError,
e7aeea18
JB
374 messageType: MessageType,
375 commandName?: RequestCommand | IncomingRequestCommand,
d900c8d7
JB
376 responseCallback?: ResponseCallback,
377 errorCallback?: ErrorCallback
e7aeea18 378 ): string {
e7accadb
JB
379 let messageToSend: string;
380 // Type of message
381 switch (messageType) {
382 // Request
383 case MessageType.CALL_MESSAGE:
384 // Build request
cda96260 385 this.validateRequestPayload(chargingStation, commandName, messagePayload as JsonObject);
08f130a0 386 chargingStation.requests.set(messageId, [
e7aeea18 387 responseCallback,
a2d1c0f1 388 errorCallback,
e7aeea18 389 commandName,
5cc4b63b 390 messagePayload as JsonType,
e7aeea18 391 ]);
b3ec7bc1
JB
392 messageToSend = JSON.stringify([
393 messageType,
394 messageId,
395 commandName,
396 messagePayload,
397 ] as OutgoingRequest);
e7accadb
JB
398 break;
399 // Response
400 case MessageType.CALL_RESULT_MESSAGE:
401 // Build response
02887891
JB
402 this.validateIncomingRequestResponsePayload(
403 chargingStation,
404 commandName,
405 messagePayload as JsonObject
406 );
b3ec7bc1 407 messageToSend = JSON.stringify([messageType, messageId, messagePayload] as Response);
e7accadb
JB
408 break;
409 // Error Message
410 case MessageType.CALL_ERROR_MESSAGE:
411 // Build Error Message
e7aeea18
JB
412 messageToSend = JSON.stringify([
413 messageType,
414 messageId,
b3ec7bc1
JB
415 (messagePayload as OCPPError)?.code ?? ErrorType.GENERIC_ERROR,
416 (messagePayload as OCPPError)?.message ?? '',
417 (messagePayload as OCPPError)?.details ?? { commandName },
418 ] as ErrorResponse);
e7accadb
JB
419 break;
420 }
421 return messageToSend;
422 }
423
9a3b8d9f
JB
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
dc922667 435 private handleSendMessageError(
08f130a0 436 chargingStation: ChargingStation,
e7aeea18
JB
437 commandName: RequestCommand | IncomingRequestCommand,
438 error: Error,
07561812 439 params: HandleErrorParams<EmptyObject> = { throwError: false }
e7aeea18 440 ): void {
60ddad53 441 logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error);
07561812 442 if (params?.throwError === true) {
e0a50bcd
JB
443 throw error;
444 }
5e0c67e8
JB
445 }
446
ef6fa3fb 447 // eslint-disable-next-line @typescript-eslint/no-unused-vars
e0b0ee21 448 public abstract requestHandler<ReqType extends JsonType, ResType extends JsonType>(
08f130a0 449 chargingStation: ChargingStation,
94a464f9 450 commandName: RequestCommand,
5cc4b63b 451 commandParams?: JsonType,
be9b0d50 452 params?: RequestParams
e0b0ee21 453 ): Promise<ResType>;
c0560973 454}