1 import { AuthorizeResponse
, StartTransactionResponse
, StopTransactionReason
, StopTransactionResponse
} from
'../../types/ocpp/Transaction';
2 import { DiagnosticsStatus
, IncomingRequestCommand
, RequestCommand
, SendParams
} from
'../../types/ocpp/Requests';
4 import { BootNotificationResponse
} from
'../../types/ocpp/Responses';
5 import { ChargePointErrorCode
} from
'../../types/ocpp/ChargePointErrorCode';
6 import { ChargePointStatus
} from
'../../types/ocpp/ChargePointStatus';
7 import type ChargingStation from
'../ChargingStation';
8 import Constants from
'../../utils/Constants';
9 import { ErrorType
} from
'../../types/ocpp/ErrorType';
10 import { JsonType
} from
'../../types/JsonType';
11 import { MessageType
} from
'../../types/ocpp/MessageType';
12 import { MeterValue
} from
'../../types/ocpp/MeterValues';
13 import OCPPError from
'../../exception/OCPPError';
14 import type OCPPResponseService from
'./OCPPResponseService';
15 import PerformanceStatistics from
'../../performance/PerformanceStatistics';
16 import Utils from
'../../utils/Utils';
17 import logger from
'../../utils/Logger';
19 export default abstract class OCPPRequestService
{
20 private static readonly instances
: Map
<string, OCPPRequestService
> = new Map
<string, OCPPRequestService
>();
21 protected readonly chargingStation
: ChargingStation
;
22 private readonly ocppResponseService
: OCPPResponseService
;
24 protected constructor(chargingStation
: ChargingStation
, ocppResponseService
: OCPPResponseService
) {
25 this.chargingStation
= chargingStation
;
26 this.ocppResponseService
= ocppResponseService
;
29 public static getInstance
<T
extends OCPPRequestService
>(this: new (chargingStation
: ChargingStation
, ocppResponseService
: OCPPResponseService
) => T
, chargingStation
: ChargingStation
, ocppResponseService
: OCPPResponseService
): T
{
30 if (!OCPPRequestService
.instances
.has(chargingStation
.id
)) {
31 OCPPRequestService
.instances
.set(chargingStation
.id
, new this(chargingStation
, ocppResponseService
));
33 return OCPPRequestService
.instances
.get(chargingStation
.id
) as T
;
36 public async sendResult(messageId
: string, messagePayload
: JsonType
, commandName
: IncomingRequestCommand
): Promise
<JsonType
| OCPPError
| string> {
38 // Send result message
39 return await this.internalSendMessage(messageId
, messagePayload
, MessageType
.CALL_RESULT_MESSAGE
, commandName
);
41 this.handleRequestError(commandName
, error
as Error);
45 public async sendError(messageId
: string, ocppError
: OCPPError
, commandName
: IncomingRequestCommand
): Promise
<JsonType
| OCPPError
| string> {
48 return await this.internalSendMessage(messageId
, ocppError
, MessageType
.CALL_ERROR_MESSAGE
, commandName
);
50 this.handleRequestError(commandName
, error
as Error);
54 protected async sendMessage(messageId
: string, messagePayload
: JsonType
, commandName
: RequestCommand
, params
: SendParams
= {
55 skipBufferingOnError
: false,
57 }): Promise
<JsonType
| OCPPError
| string> {
59 return await this.internalSendMessage(messageId
, messagePayload
, MessageType
.CALL_MESSAGE
, commandName
, params
);
61 this.handleRequestError(commandName
, error
as Error);
65 private async internalSendMessage(messageId
: string, messagePayload
: JsonType
| OCPPError
, messageType
: MessageType
, commandName
?: RequestCommand
| IncomingRequestCommand
,
66 params
: SendParams
= {
67 skipBufferingOnError
: false,
69 }): Promise
<JsonType
| OCPPError
| string> {
70 if ((this.chargingStation
.isInUnknownState() && commandName
=== RequestCommand
.BOOT_NOTIFICATION
)
71 || (!this.chargingStation
.getOcppStrictCompliance() && this.chargingStation
.isInUnknownState())
72 || this.chargingStation
.isInAcceptedState() || (this.chargingStation
.isInPendingState() && params
.triggerMessage
)) {
73 // eslint-disable-next-line @typescript-eslint/no-this-alias
75 // Send a message through wsConnection
76 return Utils
.promiseWithTimeout(new Promise((resolve
, reject
) => {
77 const messageToSend
= this.buildMessageToSend(messageId
, messagePayload
, messageType
, commandName
, responseCallback
, rejectCallback
);
78 if (this.chargingStation
.getEnableStatistics()) {
79 this.chargingStation
.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
81 // Check if wsConnection opened
82 if (this.chargingStation
.isWebSocketConnectionOpened()) {
84 const beginId
= PerformanceStatistics
.beginMeasure(commandName
);
85 // FIXME: Handle sending error
86 this.chargingStation
.wsConnection
.send(messageToSend
);
87 PerformanceStatistics
.endMeasure(commandName
, beginId
);
88 } else if (!params
.skipBufferingOnError
) {
90 this.chargingStation
.bufferMessage(messageToSend
);
91 const ocppError
= new OCPPError(ErrorType
.GENERIC_ERROR
, `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`, commandName
, messagePayload
?.details
as JsonType
?? {});
92 if (messageType
=== MessageType
.CALL_MESSAGE
) {
93 // Reject it but keep the request in the cache
94 return reject(ocppError
);
96 return rejectCallback(ocppError
, false);
99 return rejectCallback(new OCPPError(ErrorType
.GENERIC_ERROR
, `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`, commandName
, messagePayload
?.details
as JsonType
?? {}), false);
102 if (messageType
!== MessageType
.CALL_MESSAGE
) {
104 return resolve(messagePayload
);
108 * Function that will receive the request's response
111 * @param requestPayload
113 async function responseCallback(payload
: JsonType
| string, requestPayload
: JsonType
): Promise
<void> {
114 if (self.chargingStation
.getEnableStatistics()) {
115 self.chargingStation
.performanceStatistics
.addRequestStatistic(commandName
, MessageType
.CALL_RESULT_MESSAGE
);
117 // Handle the request's response
119 await self.ocppResponseService
.handleResponse(commandName
as RequestCommand
, payload
, requestPayload
);
125 self.chargingStation
.requests
.delete(messageId
);
130 * Function that will receive the request's error response
133 * @param requestStatistic
135 function rejectCallback(error
: OCPPError
, requestStatistic
= true): void {
136 if (requestStatistic
&& self.chargingStation
.getEnableStatistics()) {
137 self.chargingStation
.performanceStatistics
.addRequestStatistic(commandName
, MessageType
.CALL_ERROR_MESSAGE
);
139 logger
.error(`${self.chargingStation.logPrefix()} Error %j occurred when calling command %s with message data %j`, error
, commandName
, messagePayload
);
140 self.chargingStation
.requests
.delete(messageId
);
143 }), Constants
.OCPP_WEBSOCKET_TIMEOUT
, new OCPPError(ErrorType
.GENERIC_ERROR
, `Timeout for message id '${messageId}'`, commandName
, messagePayload
?.details
as JsonType
?? {}), () => {
144 messageType
=== MessageType
.CALL_MESSAGE
&& this.chargingStation
.requests
.delete(messageId
);
147 throw new OCPPError(ErrorType
.SECURITY_ERROR
, `Cannot send command ${commandName} payload when the charging station is in ${this.chargingStation.getRegistrationStatus()} state on the central server`, commandName
);
150 private buildMessageToSend(messageId
: string, messagePayload
: JsonType
| OCPPError
, messageType
: MessageType
, commandName
?: RequestCommand
| IncomingRequestCommand
,
151 responseCallback
?: (payload
: JsonType
| string, requestPayload
: JsonType
) => Promise
<void>,
152 rejectCallback
?: (error
: OCPPError
, requestStatistic
?: boolean) => void): string {
153 let messageToSend
: string;
155 switch (messageType
) {
157 case MessageType
.CALL_MESSAGE
:
159 this.chargingStation
.requests
.set(messageId
, [responseCallback
, rejectCallback
, commandName
, messagePayload
]);
160 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, messagePayload
]);
163 case MessageType
.CALL_RESULT_MESSAGE
:
165 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
]);
168 case MessageType
.CALL_ERROR_MESSAGE
:
169 // Build Error Message
170 messageToSend
= JSON
.stringify([messageType
, messageId
, messagePayload
?.code
?? ErrorType
.GENERIC_ERROR
, messagePayload
?.message
?? '', messagePayload
?.details
?? { commandName
}]);
173 return messageToSend
;
176 private handleRequestError(commandName
: RequestCommand
| IncomingRequestCommand
, error
: Error): void {
177 logger
.error(this.chargingStation
.logPrefix() + ' Request command %s error: %j', commandName
, error
);
181 public abstract sendHeartbeat(params
?: SendParams
): Promise
<void>;
182 public abstract sendBootNotification(chargePointModel
: string, chargePointVendor
: string, chargeBoxSerialNumber
?: string, firmwareVersion
?: string, chargePointSerialNumber
?: string, iccid
?: string, imsi
?: string, meterSerialNumber
?: string, meterType
?: string, params
?: SendParams
): Promise
<BootNotificationResponse
>;
183 public abstract sendStatusNotification(connectorId
: number, status: ChargePointStatus
, errorCode
?: ChargePointErrorCode
): Promise
<void>;
184 public abstract sendAuthorize(connectorId
: number, idTag
?: string): Promise
<AuthorizeResponse
>;
185 public abstract sendStartTransaction(connectorId
: number, idTag
?: string): Promise
<StartTransactionResponse
>;
186 public abstract sendStopTransaction(transactionId
: number, meterStop
: number, idTag
?: string, reason
?: StopTransactionReason
): Promise
<StopTransactionResponse
>;
187 public abstract sendMeterValues(connectorId
: number, transactionId
: number, interval
: number): Promise
<void>;
188 public abstract sendTransactionBeginMeterValues(connectorId
: number, transactionId
: number, beginMeterValue
: MeterValue
): Promise
<void>;
189 public abstract sendTransactionEndMeterValues(connectorId
: number, transactionId
: number, endMeterValue
: MeterValue
): Promise
<void>;
190 public abstract sendDiagnosticsStatusNotification(diagnosticsStatus
: DiagnosticsStatus
): Promise
<void>;