2 IncomingRequestCommand
,
6 } from
'../../types/ocpp/Requests';
8 import type ChargingStation from
'../ChargingStation';
9 import Constants from
'../../utils/Constants';
10 import { EmptyObject
} from
'../../types/EmptyObject';
11 import { ErrorType
} from
'../../types/ocpp/ErrorType';
12 import { HandleErrorParams
} from
'../../types/Error';
13 import { JsonType
} from
'../../types/JsonType';
14 import { MessageType
} from
'../../types/ocpp/MessageType';
15 import OCPPError from
'../../exception/OCPPError';
16 import type OCPPResponseService from
'./OCPPResponseService';
17 import PerformanceStatistics from
'../../performance/PerformanceStatistics';
18 import Utils from
'../../utils/Utils';
19 import logger from
'../../utils/Logger';
21 export default abstract class OCPPRequestService
{
22 private static readonly instances
: Map
<string, OCPPRequestService
> = new Map
<
27 protected readonly chargingStation
: ChargingStation
;
28 private readonly ocppResponseService
: OCPPResponseService
;
30 protected constructor(
31 chargingStation
: ChargingStation
,
32 ocppResponseService
: OCPPResponseService
34 this.chargingStation
= chargingStation
;
35 this.ocppResponseService
= ocppResponseService
;
36 this.sendMessageHandler
.bind(this);
37 this.sendResult
.bind(this);
38 this.sendError
.bind(this);
41 public static getInstance
<T
extends OCPPRequestService
>(
42 this: new (chargingStation
: ChargingStation
, ocppResponseService
: OCPPResponseService
) => T
,
43 chargingStation
: ChargingStation
,
44 ocppResponseService
: OCPPResponseService
46 if (!OCPPRequestService
.instances
.has(chargingStation
.hashId
)) {
47 OCPPRequestService
.instances
.set(
48 chargingStation
.hashId
,
49 new this(chargingStation
, ocppResponseService
)
52 return OCPPRequestService
.instances
.get(chargingStation
.hashId
) as T
;
55 public async sendResult(
57 messagePayload
: JsonType
,
58 commandName
: IncomingRequestCommand
59 ): Promise
<ResponseType
> {
61 // Send result message
62 return await this.internalSendMessage(
65 MessageType
.CALL_RESULT_MESSAGE
,
69 this.handleRequestError(commandName
, error
as Error);
73 public async sendError(
76 commandName
: IncomingRequestCommand
77 ): Promise
<ResponseType
> {
80 return await this.internalSendMessage(
83 MessageType
.CALL_ERROR_MESSAGE
,
87 this.handleRequestError(commandName
, error
as Error);
91 protected async sendMessage(
93 messagePayload
: JsonType
,
94 commandName
: RequestCommand
,
95 params
: SendParams
= {
96 skipBufferingOnError
: false,
97 triggerMessage
: false,
99 ): Promise
<ResponseType
> {
101 return await this.internalSendMessage(
104 MessageType
.CALL_MESSAGE
,
109 this.handleRequestError(commandName
, error
as Error, { throwError
: false });
113 private async internalSendMessage(
115 messagePayload
: JsonType
| OCPPError
,
116 messageType
: MessageType
,
117 commandName
?: RequestCommand
| IncomingRequestCommand
,
118 params
: SendParams
= {
119 skipBufferingOnError
: false,
120 triggerMessage
: false,
122 ): Promise
<ResponseType
> {
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
)
131 // eslint-disable-next-line @typescript-eslint/no-this-alias
133 // Send a message through wsConnection
134 return Utils
.promiseWithTimeout(
135 new Promise((resolve
, reject
) => {
136 const messageToSend
= this.buildMessageToSend(
144 if (this.chargingStation
.getEnableStatistics()) {
145 this.chargingStation
.performanceStatistics
.addRequestStatistic(
150 // Check if wsConnection opened
151 if (this.chargingStation
.isWebSocketConnectionOpened()) {
153 const beginId
= PerformanceStatistics
.beginMeasure(commandName
);
154 // FIXME: Handle sending error
155 this.chargingStation
.wsConnection
.send(messageToSend
);
156 PerformanceStatistics
.endMeasure(commandName
, beginId
);
157 let msgTypeStr
: string;
158 switch (messageType
) {
159 case MessageType
.CALL_MESSAGE
:
160 msgTypeStr
= 'request';
162 case MessageType
.CALL_RESULT_MESSAGE
:
163 msgTypeStr
= 'response';
165 case MessageType
.CALL_ERROR_MESSAGE
:
166 msgTypeStr
= 'error';
170 `${this.chargingStation.logPrefix()} >> Command '${commandName}' sent ${msgTypeStr} payload: ${messageToSend}`
172 } else if (!params
.skipBufferingOnError
) {
174 this.chargingStation
.bufferMessage(messageToSend
);
175 const ocppError
= new OCPPError(
176 ErrorType
.GENERIC_ERROR
,
177 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
179 (messagePayload
?.details
as JsonType
) ?? {}
181 if (messageType
=== MessageType
.CALL_MESSAGE
) {
182 // Reject it but keep the request in the cache
183 return reject(ocppError
);
185 return rejectCallback(ocppError
, false);
188 return rejectCallback(
190 ErrorType
.GENERIC_ERROR
,
191 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
193 (messagePayload
?.details
as JsonType
) ?? {}
199 if (messageType
!== MessageType
.CALL_MESSAGE
) {
201 return resolve(messagePayload
);
205 * Function that will receive the request's response
208 * @param requestPayload
210 async function responseCallback(
211 payload
: JsonType
| string,
212 requestPayload
: JsonType
214 if (self.chargingStation
.getEnableStatistics()) {
215 self.chargingStation
.performanceStatistics
.addRequestStatistic(
217 MessageType
.CALL_RESULT_MESSAGE
220 // Handle the request's response
222 await self.ocppResponseService
.handleResponse(
223 commandName
as RequestCommand
,
231 self.chargingStation
.requests
.delete(messageId
);
236 * Function that will receive the request's error response
239 * @param requestStatistic
241 function rejectCallback(error
: OCPPError
, requestStatistic
= true): void {
242 if (requestStatistic
&& self.chargingStation
.getEnableStatistics()) {
243 self.chargingStation
.performanceStatistics
.addRequestStatistic(
245 MessageType
.CALL_ERROR_MESSAGE
249 `${self.chargingStation.logPrefix()} Error %j occurred when calling command %s with message data %j`,
254 self.chargingStation
.requests
.delete(messageId
);
258 Constants
.OCPP_WEBSOCKET_TIMEOUT
,
260 ErrorType
.GENERIC_ERROR
,
261 `Timeout for message id '${messageId}'`,
263 (messagePayload
?.details
as JsonType
) ?? {}
266 messageType
=== MessageType
.CALL_MESSAGE
&&
267 this.chargingStation
.requests
.delete(messageId
);
272 ErrorType
.SECURITY_ERROR
,
273 `Cannot send command ${commandName} payload when the charging station is in ${this.chargingStation.getRegistrationStatus()} state on the central server`,
278 private buildMessageToSend(
280 messagePayload
: JsonType
| OCPPError
,
281 messageType
: MessageType
,
282 commandName
?: RequestCommand
| IncomingRequestCommand
,
283 responseCallback
?: (payload
: JsonType
| string, requestPayload
: JsonType
) => Promise
<void>,
284 rejectCallback
?: (error
: OCPPError
, requestStatistic
?: boolean) => void
286 let messageToSend
: string;
288 switch (messageType
) {
290 case MessageType
.CALL_MESSAGE
:
292 this.chargingStation
.requests
.set(messageId
, [
298 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, messagePayload
]);
301 case MessageType
.CALL_RESULT_MESSAGE
:
303 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
]);
306 case MessageType
.CALL_ERROR_MESSAGE
:
307 // Build Error Message
308 messageToSend
= JSON
.stringify([
311 messagePayload
?.code
?? ErrorType
.GENERIC_ERROR
,
312 messagePayload
?.message
?? '',
313 messagePayload
?.details
?? { commandName
},
317 return messageToSend
;
320 private handleRequestError(
321 commandName
: RequestCommand
| IncomingRequestCommand
,
323 params
: HandleErrorParams
<EmptyObject
> = { throwError
: true }
326 this.chargingStation
.logPrefix() + ' Request command %s error: %j',
330 if (params
?.throwError
) {
335 // eslint-disable-next-line @typescript-eslint/no-unused-vars
336 public abstract sendMessageHandler
<Request
extends JsonType
, Response
extends JsonType
>(
337 commandName
: RequestCommand
,
338 commandParams
?: JsonType
,
340 ): Promise
<Response
>;