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