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