3 IncomingRequestCommand
,
7 } from
'../../types/ocpp/Requests';
9 import type ChargingStation from
'../ChargingStation';
10 import Constants from
'../../utils/Constants';
11 import { EmptyObject
} from
'../../types/EmptyObject';
12 import { ErrorType
} from
'../../types/ocpp/ErrorType';
13 import { HandleErrorParams
} from
'../../types/Error';
14 import { JsonType
} from
'../../types/JsonType';
15 import { MessageType
} from
'../../types/ocpp/MessageType';
16 import { MeterValue
} from
'../../types/ocpp/MeterValues';
17 import OCPPError from
'../../exception/OCPPError';
18 import type OCPPResponseService from
'./OCPPResponseService';
19 import PerformanceStatistics from
'../../performance/PerformanceStatistics';
20 import Utils from
'../../utils/Utils';
21 import logger from
'../../utils/Logger';
23 export default abstract class OCPPRequestService
{
24 private static readonly instances
: Map
<string, OCPPRequestService
> = new Map
<
29 protected readonly chargingStation
: ChargingStation
;
30 private readonly ocppResponseService
: OCPPResponseService
;
32 protected constructor(
33 chargingStation
: ChargingStation
,
34 ocppResponseService
: OCPPResponseService
36 this.chargingStation
= chargingStation
;
37 this.ocppResponseService
= ocppResponseService
;
38 this.sendMessageHandler
.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
.id
)) {
47 OCPPRequestService
.instances
.set(
49 new this(chargingStation
, ocppResponseService
)
52 return OCPPRequestService
.instances
.get(chargingStation
.id
) 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 } else if (!params
.skipBufferingOnError
) {
159 this.chargingStation
.bufferMessage(messageToSend
);
160 const ocppError
= new OCPPError(
161 ErrorType
.GENERIC_ERROR
,
162 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
164 (messagePayload
?.details
as JsonType
) ?? {}
166 if (messageType
=== MessageType
.CALL_MESSAGE
) {
167 // Reject it but keep the request in the cache
168 return reject(ocppError
);
170 return rejectCallback(ocppError
, false);
173 return rejectCallback(
175 ErrorType
.GENERIC_ERROR
,
176 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
178 (messagePayload
?.details
as JsonType
) ?? {}
184 if (messageType
!== MessageType
.CALL_MESSAGE
) {
186 return resolve(messagePayload
);
190 * Function that will receive the request's response
193 * @param requestPayload
195 async function responseCallback(
196 payload
: JsonType
| string,
197 requestPayload
: JsonType
199 if (self.chargingStation
.getEnableStatistics()) {
200 self.chargingStation
.performanceStatistics
.addRequestStatistic(
202 MessageType
.CALL_RESULT_MESSAGE
205 // Handle the request's response
207 await self.ocppResponseService
.handleResponse(
208 commandName
as RequestCommand
,
217 self.chargingStation
.requests
.delete(messageId
);
222 * Function that will receive the request's error response
225 * @param requestStatistic
227 function rejectCallback(error
: OCPPError
, requestStatistic
= true): void {
228 if (requestStatistic
&& self.chargingStation
.getEnableStatistics()) {
229 self.chargingStation
.performanceStatistics
.addRequestStatistic(
231 MessageType
.CALL_ERROR_MESSAGE
235 `${self.chargingStation.logPrefix()} Error %j occurred when calling command %s with message data %j`,
240 self.chargingStation
.requests
.delete(messageId
);
244 Constants
.OCPP_WEBSOCKET_TIMEOUT
,
246 ErrorType
.GENERIC_ERROR
,
247 `Timeout for message id '${messageId}'`,
249 (messagePayload
?.details
as JsonType
) ?? {}
252 messageType
=== MessageType
.CALL_MESSAGE
&&
253 this.chargingStation
.requests
.delete(messageId
);
258 ErrorType
.SECURITY_ERROR
,
259 `Cannot send command ${commandName} payload when the charging station is in ${this.chargingStation.getRegistrationStatus()} state on the central server`,
264 private buildMessageToSend(
266 messagePayload
: JsonType
| OCPPError
,
267 messageType
: MessageType
,
268 commandName
?: RequestCommand
| IncomingRequestCommand
,
269 responseCallback
?: (payload
: JsonType
| string, requestPayload
: JsonType
) => Promise
<void>,
270 rejectCallback
?: (error
: OCPPError
, requestStatistic
?: boolean) => void
272 let messageToSend
: string;
274 switch (messageType
) {
276 case MessageType
.CALL_MESSAGE
:
278 this.chargingStation
.requests
.set(messageId
, [
284 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, messagePayload
]);
287 case MessageType
.CALL_RESULT_MESSAGE
:
289 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
]);
292 case MessageType
.CALL_ERROR_MESSAGE
:
293 // Build Error Message
294 messageToSend
= JSON
.stringify([
297 messagePayload
?.code
?? ErrorType
.GENERIC_ERROR
,
298 messagePayload
?.message
?? '',
299 messagePayload
?.details
?? { commandName
},
303 return messageToSend
;
306 private handleRequestError(
307 commandName
: RequestCommand
| IncomingRequestCommand
,
309 params
: HandleErrorParams
<EmptyObject
> = { throwError
: true }
312 this.chargingStation
.logPrefix() + ' Request command %s error: %j',
316 if (params
?.throwError
) {
321 public abstract sendMessageHandler(
322 commandName
: RequestCommand
,
323 commandParams
?: JsonType
,
325 ): Promise
<ResponseType
>;
327 public abstract sendTransactionBeginMeterValues(
329 transactionId
: number,
330 beginMeterValue
: MeterValue
333 public abstract sendTransactionEndMeterValues(
335 transactionId
: number,
336 endMeterValue
: MeterValue
339 public abstract sendDiagnosticsStatusNotification(
340 diagnosticsStatus
: DiagnosticsStatus