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