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 chalk from
'chalk';
20 import logger from
'../../utils/Logger';
22 export default abstract class OCPPRequestService
{
23 private static readonly instances
: Map
<string, OCPPRequestService
> = new Map
<
28 protected readonly chargingStation
: ChargingStation
;
29 private readonly ocppResponseService
: OCPPResponseService
;
31 protected constructor(
32 chargingStation
: ChargingStation
,
33 ocppResponseService
: OCPPResponseService
35 this.chargingStation
= chargingStation
;
36 this.ocppResponseService
= ocppResponseService
;
37 this.sendMessageHandler
.bind(this);
38 this.sendResult
.bind(this);
39 this.sendError
.bind(this);
42 public static getInstance
<T
extends OCPPRequestService
>(
43 this: new (chargingStation
: ChargingStation
, ocppResponseService
: OCPPResponseService
) => T
,
44 chargingStation
: ChargingStation
,
45 ocppResponseService
: OCPPResponseService
47 if (!OCPPRequestService
.instances
.has(chargingStation
.hashId
)) {
48 OCPPRequestService
.instances
.set(
49 chargingStation
.hashId
,
50 new this(chargingStation
, ocppResponseService
)
53 return OCPPRequestService
.instances
.get(chargingStation
.hashId
) as T
;
56 public async sendResult(
58 messagePayload
: JsonType
,
59 commandName
: IncomingRequestCommand
60 ): Promise
<ResponseType
> {
62 // Send result message
63 return await this.internalSendMessage(
66 MessageType
.CALL_RESULT_MESSAGE
,
70 this.handleRequestError(commandName
, error
as Error);
74 public async sendError(
77 commandName
: IncomingRequestCommand
78 ): Promise
<ResponseType
> {
81 return await this.internalSendMessage(
84 MessageType
.CALL_ERROR_MESSAGE
,
88 this.handleRequestError(commandName
, error
as Error);
92 protected async sendMessage(
94 messagePayload
: JsonType
,
95 commandName
: RequestCommand
,
96 params
: SendParams
= {
97 skipBufferingOnError
: false,
98 triggerMessage
: false,
100 ): Promise
<ResponseType
> {
102 return await this.internalSendMessage(
105 MessageType
.CALL_MESSAGE
,
110 this.handleRequestError(commandName
, error
as Error, { throwError
: false });
114 private async internalSendMessage(
116 messagePayload
: JsonType
| OCPPError
,
117 messageType
: MessageType
,
118 commandName
?: RequestCommand
| IncomingRequestCommand
,
119 params
: SendParams
= {
120 skipBufferingOnError
: false,
121 triggerMessage
: false,
123 ): Promise
<ResponseType
> {
125 (this.chargingStation
.isInUnknownState() &&
126 commandName
=== RequestCommand
.BOOT_NOTIFICATION
) ||
127 (!this.chargingStation
.getOcppStrictCompliance() &&
128 this.chargingStation
.isInUnknownState()) ||
129 this.chargingStation
.isInAcceptedState() ||
130 (this.chargingStation
.isInPendingState() && params
.triggerMessage
)
132 // eslint-disable-next-line @typescript-eslint/no-this-alias
134 // Send a message through wsConnection
135 return Utils
.promiseWithTimeout(
136 new Promise((resolve
, reject
) => {
137 const messageToSend
= this.buildMessageToSend(
145 if (this.chargingStation
.getEnableStatistics()) {
146 this.chargingStation
.performanceStatistics
.addRequestStatistic(
151 // Check if wsConnection opened
152 if (this.chargingStation
.isWebSocketConnectionOpened()) {
154 const beginId
= PerformanceStatistics
.beginMeasure(commandName
);
155 console
.log(chalk
`{blue >> Sending message = ${messageToSend}}`);
156 // FIXME: Handle sending error
157 this.chargingStation
.wsConnection
.send(messageToSend
);
158 PerformanceStatistics
.endMeasure(commandName
, beginId
);
159 } else if (!params
.skipBufferingOnError
) {
161 this.chargingStation
.bufferMessage(messageToSend
);
162 const ocppError
= new OCPPError(
163 ErrorType
.GENERIC_ERROR
,
164 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
166 (messagePayload
?.details
as JsonType
) ?? {}
168 if (messageType
=== MessageType
.CALL_MESSAGE
) {
169 // Reject it but keep the request in the cache
170 return reject(ocppError
);
172 return rejectCallback(ocppError
, false);
175 return rejectCallback(
177 ErrorType
.GENERIC_ERROR
,
178 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
180 (messagePayload
?.details
as JsonType
) ?? {}
186 if (messageType
!== MessageType
.CALL_MESSAGE
) {
188 return resolve(messagePayload
);
192 * Function that will receive the request's response
195 * @param requestPayload
197 async function responseCallback(
198 payload
: JsonType
| string,
199 requestPayload
: JsonType
201 if (self.chargingStation
.getEnableStatistics()) {
202 self.chargingStation
.performanceStatistics
.addRequestStatistic(
204 MessageType
.CALL_RESULT_MESSAGE
207 // Handle the request's response
209 await self.ocppResponseService
.handleResponse(
210 commandName
as RequestCommand
,
218 self.chargingStation
.requests
.delete(messageId
);
223 * Function that will receive the request's error response
226 * @param requestStatistic
228 function rejectCallback(error
: OCPPError
, requestStatistic
= true): void {
229 if (requestStatistic
&& self.chargingStation
.getEnableStatistics()) {
230 self.chargingStation
.performanceStatistics
.addRequestStatistic(
232 MessageType
.CALL_ERROR_MESSAGE
236 `${self.chargingStation.logPrefix()} Error %j occurred when calling command %s with message data %j`,
241 self.chargingStation
.requests
.delete(messageId
);
245 Constants
.OCPP_WEBSOCKET_TIMEOUT
,
247 ErrorType
.GENERIC_ERROR
,
248 `Timeout for message id '${messageId}'`,
250 (messagePayload
?.details
as JsonType
) ?? {}
253 messageType
=== MessageType
.CALL_MESSAGE
&&
254 this.chargingStation
.requests
.delete(messageId
);
259 ErrorType
.SECURITY_ERROR
,
260 `Cannot send command ${commandName} payload when the charging station is in ${this.chargingStation.getRegistrationStatus()} state on the central server`,
265 private buildMessageToSend(
267 messagePayload
: JsonType
| OCPPError
,
268 messageType
: MessageType
,
269 commandName
?: RequestCommand
| IncomingRequestCommand
,
270 responseCallback
?: (payload
: JsonType
| string, requestPayload
: JsonType
) => Promise
<void>,
271 rejectCallback
?: (error
: OCPPError
, requestStatistic
?: boolean) => void
273 let messageToSend
: string;
275 switch (messageType
) {
277 case MessageType
.CALL_MESSAGE
:
279 this.chargingStation
.requests
.set(messageId
, [
285 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, messagePayload
]);
288 case MessageType
.CALL_RESULT_MESSAGE
:
290 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
]);
293 case MessageType
.CALL_ERROR_MESSAGE
:
294 // Build Error Message
295 messageToSend
= JSON
.stringify([
298 messagePayload
?.code
?? ErrorType
.GENERIC_ERROR
,
299 messagePayload
?.message
?? '',
300 messagePayload
?.details
?? { commandName
},
304 return messageToSend
;
307 private handleRequestError(
308 commandName
: RequestCommand
| IncomingRequestCommand
,
310 params
: HandleErrorParams
<EmptyObject
> = { throwError
: true }
313 this.chargingStation
.logPrefix() + ' Request command %s error: %j',
317 if (params
?.throwError
) {
322 // eslint-disable-next-line @typescript-eslint/no-unused-vars
323 public abstract sendMessageHandler
<Request
extends JsonType
, Response
extends JsonType
>(
324 commandName
: RequestCommand
,
325 commandParams
?: JsonType
,
327 ): Promise
<Response
>;