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