Factor out OCPP message type to string method
[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);
6f35d2da 157 logger.debug(
9a3b8d9f
JB
158 `${this.chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
159 messageType
160 )} payload: ${messageToSend}`
6f35d2da 161 );
e7aeea18
JB
162 } else if (!params.skipBufferingOnError) {
163 // Buffer it
164 this.chargingStation.bufferMessage(messageToSend);
165 const ocppError = new OCPPError(
166 ErrorType.GENERIC_ERROR,
167 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
168 commandName,
169 (messagePayload?.details as JsonType) ?? {}
170 );
171 if (messageType === MessageType.CALL_MESSAGE) {
172 // Reject it but keep the request in the cache
173 return reject(ocppError);
174 }
175 return rejectCallback(ocppError, false);
176 } else {
177 // Reject it
178 return rejectCallback(
179 new OCPPError(
180 ErrorType.GENERIC_ERROR,
181 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
182 commandName,
183 (messagePayload?.details as JsonType) ?? {}
184 ),
185 false
186 );
caad9d6b 187 }
e7aeea18
JB
188 // Response?
189 if (messageType !== MessageType.CALL_MESSAGE) {
190 // Yes: send Ok
191 return resolve(messagePayload);
192 }
193
194 /**
195 * Function that will receive the request's response
196 *
197 * @param payload
198 * @param requestPayload
199 */
200 async function responseCallback(
201 payload: JsonType | string,
202 requestPayload: JsonType
203 ): Promise<void> {
204 if (self.chargingStation.getEnableStatistics()) {
205 self.chargingStation.performanceStatistics.addRequestStatistic(
206 commandName,
207 MessageType.CALL_RESULT_MESSAGE
208 );
209 }
210 // Handle the request's response
211 try {
212 await self.ocppResponseService.handleResponse(
213 commandName as RequestCommand,
214 payload,
215 requestPayload
216 );
217 resolve(payload);
218 } catch (error) {
219 reject(error);
e7aeea18
JB
220 } finally {
221 self.chargingStation.requests.delete(messageId);
222 }
caad9d6b 223 }
caad9d6b 224
e7aeea18
JB
225 /**
226 * Function that will receive the request's error response
227 *
228 * @param error
229 * @param requestStatistic
230 */
231 function rejectCallback(error: OCPPError, requestStatistic = true): void {
232 if (requestStatistic && self.chargingStation.getEnableStatistics()) {
233 self.chargingStation.performanceStatistics.addRequestStatistic(
234 commandName,
235 MessageType.CALL_ERROR_MESSAGE
236 );
237 }
238 logger.error(
239 `${self.chargingStation.logPrefix()} Error %j occurred when calling command %s with message data %j`,
240 error,
241 commandName,
242 messagePayload
243 );
244 self.chargingStation.requests.delete(messageId);
245 reject(error);
caad9d6b 246 }
e7aeea18
JB
247 }),
248 Constants.OCPP_WEBSOCKET_TIMEOUT,
249 new OCPPError(
250 ErrorType.GENERIC_ERROR,
251 `Timeout for message id '${messageId}'`,
252 commandName,
253 (messagePayload?.details as JsonType) ?? {}
254 ),
255 () => {
256 messageType === MessageType.CALL_MESSAGE &&
257 this.chargingStation.requests.delete(messageId);
caad9d6b 258 }
e7aeea18 259 );
caad9d6b 260 }
e7aeea18
JB
261 throw new OCPPError(
262 ErrorType.SECURITY_ERROR,
263 `Cannot send command ${commandName} payload when the charging station is in ${this.chargingStation.getRegistrationStatus()} state on the central server`,
264 commandName
265 );
c0560973
JB
266 }
267
e7aeea18
JB
268 private buildMessageToSend(
269 messageId: string,
270 messagePayload: JsonType | OCPPError,
271 messageType: MessageType,
272 commandName?: RequestCommand | IncomingRequestCommand,
273 responseCallback?: (payload: JsonType | string, requestPayload: JsonType) => Promise<void>,
274 rejectCallback?: (error: OCPPError, requestStatistic?: boolean) => void
275 ): string {
e7accadb
JB
276 let messageToSend: string;
277 // Type of message
278 switch (messageType) {
279 // Request
280 case MessageType.CALL_MESSAGE:
281 // Build request
e7aeea18
JB
282 this.chargingStation.requests.set(messageId, [
283 responseCallback,
284 rejectCallback,
285 commandName,
286 messagePayload,
287 ]);
5e0c67e8 288 messageToSend = JSON.stringify([messageType, messageId, commandName, messagePayload]);
e7accadb
JB
289 break;
290 // Response
291 case MessageType.CALL_RESULT_MESSAGE:
292 // Build response
5e0c67e8 293 messageToSend = JSON.stringify([messageType, messageId, messagePayload]);
e7accadb
JB
294 break;
295 // Error Message
296 case MessageType.CALL_ERROR_MESSAGE:
297 // Build Error Message
e7aeea18
JB
298 messageToSend = JSON.stringify([
299 messageType,
300 messageId,
301 messagePayload?.code ?? ErrorType.GENERIC_ERROR,
302 messagePayload?.message ?? '',
303 messagePayload?.details ?? { commandName },
304 ]);
e7accadb
JB
305 break;
306 }
307 return messageToSend;
308 }
309
9a3b8d9f
JB
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
e7aeea18
JB
321 private handleRequestError(
322 commandName: RequestCommand | IncomingRequestCommand,
323 error: Error,
324 params: HandleErrorParams<EmptyObject> = { throwError: true }
325 ): void {
326 logger.error(
327 this.chargingStation.logPrefix() + ' Request command %s error: %j',
328 commandName,
329 error
330 );
e0a50bcd
JB
331 if (params?.throwError) {
332 throw error;
333 }
5e0c67e8
JB
334 }
335
ef6fa3fb
JB
336 // eslint-disable-next-line @typescript-eslint/no-unused-vars
337 public abstract sendMessageHandler<Request extends JsonType, Response extends JsonType>(
94a464f9
JB
338 commandName: RequestCommand,
339 commandParams?: JsonType,
340 params?: SendParams
f22266fd 341 ): Promise<Response>;
c0560973 342}