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