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