Spell fixlets
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPRequestService.ts
CommitLineData
c0560973 1import { AuthorizeResponse, StartTransactionResponse, StopTransactionReason, StopTransactionResponse } from '../../types/ocpp/Transaction';
47e22477 2import { DiagnosticsStatus, IncomingRequestCommand, RequestCommand } from '../../types/ocpp/Requests';
c0560973 3
efa43e52 4import { BootNotificationResponse } from '../../types/ocpp/Responses';
c0560973
JB
5import { ChargePointErrorCode } from '../../types/ocpp/ChargePointErrorCode';
6import { ChargePointStatus } from '../../types/ocpp/ChargePointStatus';
7import ChargingStation from '../ChargingStation';
8import Constants from '../../utils/Constants';
9import { ErrorType } from '../../types/ocpp/ErrorType';
10import { MessageType } from '../../types/ocpp/MessageType';
fd0c36fa 11import { MeterValue } from '../../types/ocpp/MeterValues';
14763b46 12import OCPPError from './OCPPError';
c0560973 13import OCPPResponseService from './OCPPResponseService';
a6b3c6c3 14import PerformanceStatistics from '../../performance/PerformanceStatistics';
c0560973
JB
15import logger from '../../utils/Logger';
16
17export default abstract class OCPPRequestService {
18 public chargingStation: ChargingStation;
19 protected ocppResponseService: OCPPResponseService;
20
21 constructor(chargingStation: ChargingStation, ocppResponseService: OCPPResponseService) {
22 this.chargingStation = chargingStation;
23 this.ocppResponseService = ocppResponseService;
24 }
25
a6b3c6c3 26 public async sendMessage(messageId: string, commandParams: any, messageType: MessageType, commandName: RequestCommand | IncomingRequestCommand,
9292e32a 27 skipBufferingOnError = false): Promise<unknown> {
c0560973
JB
28 // eslint-disable-next-line @typescript-eslint/no-this-alias
29 const self = this;
c0560973 30 // Send a message through wsConnection
e7accadb
JB
31 return new Promise((resolve, reject) => {
32 const messageToSend = this.buildMessageToSend(messageId, commandParams, messageType, commandName, responseCallback, rejectCallback);
a6b3c6c3
JB
33 if (this.chargingStation.getEnableStatistics()) {
34 this.chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
35 }
36 // Check if wsConnection opened
37 if (this.chargingStation.isWebSocketConnectionOpened()) {
c0560973 38 // Yes: Send Message
aef1b33a 39 const beginId = PerformanceStatistics.beginMeasure(commandName);
c0560973 40 this.chargingStation.wsConnection.send(messageToSend);
aef1b33a 41 PerformanceStatistics.endMeasure(commandName, beginId);
9292e32a 42 } else if (!skipBufferingOnError) {
3ba2381e 43 // Buffer it
77f00f84 44 this.chargingStation.addToMessageQueue(messageToSend);
c0560973 45 // Reject it
3582e6fe 46 return rejectCallback(new OCPPError(commandParams?.code ?? ErrorType.GENERIC_ERROR, commandParams?.message ?? `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams?.details ?? {}));
c0560973
JB
47 }
48 // Response?
49 if (messageType === MessageType.CALL_RESULT_MESSAGE) {
50 // Yes: send Ok
e7accadb 51 resolve(commandName);
c0560973
JB
52 } else if (messageType === MessageType.CALL_ERROR_MESSAGE) {
53 // Send timeout
5e5a3ab7 54 setTimeout(() => rejectCallback(new OCPPError(commandParams?.code ?? ErrorType.GENERIC_ERROR, commandParams?.message ?? `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams?.details ?? {})), Constants.OCPP_ERROR_TIMEOUT);
c0560973
JB
55 }
56
3340259a
JB
57 /**
58 * Function that will receive the request's response
59 *
81797102
JB
60 * @param payload
61 * @param requestPayload
3340259a 62 */
c0560973 63 async function responseCallback(payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>): Promise<void> {
52748e2c 64 if (self.chargingStation.getEnableStatistics()) {
aef1b33a 65 self.chargingStation.performanceStatistics.addRequestStatistic(commandName, MessageType.CALL_RESULT_MESSAGE);
c0560973
JB
66 }
67 // Send the response
68 await self.ocppResponseService.handleResponse(commandName as RequestCommand, payload, requestPayload);
69 resolve(payload);
70 }
71
3340259a
JB
72 /**
73 * Function that will receive the request's rejection
74 *
81797102 75 * @param error
3340259a 76 */
c0560973 77 function rejectCallback(error: OCPPError): void {
52748e2c 78 if (self.chargingStation.getEnableStatistics()) {
aef1b33a 79 self.chargingStation.performanceStatistics.addRequestStatistic(commandName, MessageType.CALL_ERROR_MESSAGE);
c0560973 80 }
52748e2c 81 logger.debug(`${self.chargingStation.logPrefix()} Error: %j occurred when calling command %s with parameters: %j`, error, commandName, commandParams);
c0560973 82 // Build Exception
9c613674 83 self.chargingStation.requests.set(messageId, [() => { /* This is intentional */ }, () => { /* This is intentional */ }, {}]);
c0560973
JB
84 // Send error
85 reject(error);
86 }
87 });
88 }
89
c7f95d16 90 protected handleRequestError(commandName: RequestCommand, error: Error): void {
47e22477 91 logger.error(this.chargingStation.logPrefix() + ' Request command ' + commandName + ' error: %j', error);
c0560973
JB
92 throw error;
93 }
94
e7accadb
JB
95 private buildMessageToSend(messageId: string, commandParams: any, messageType: MessageType, commandName: RequestCommand | IncomingRequestCommand,
96 responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => Promise<void>, rejectCallback: (error: OCPPError) => void): string {
97 let messageToSend: string;
98 // Type of message
99 switch (messageType) {
100 // Request
101 case MessageType.CALL_MESSAGE:
102 // Build request
103 this.chargingStation.requests.set(messageId, [responseCallback, rejectCallback, commandParams as Record<string, unknown>]);
104 messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]);
105 break;
106 // Response
107 case MessageType.CALL_RESULT_MESSAGE:
108 // Build response
109 messageToSend = JSON.stringify([messageType, messageId, commandParams]);
110 break;
111 // Error Message
112 case MessageType.CALL_ERROR_MESSAGE:
113 // Build Error Message
114 messageToSend = JSON.stringify([messageType, messageId, commandParams?.code ?? ErrorType.GENERIC_ERROR, commandParams?.message ?? '', commandParams?.details ?? {}]);
115 break;
116 }
117 return messageToSend;
118 }
119
c0560973
JB
120 public abstract sendHeartbeat(): Promise<void>;
121 public abstract sendBootNotification(chargePointModel: string, chargePointVendor: string, chargeBoxSerialNumber?: string, firmwareVersion?: string, chargePointSerialNumber?: string, iccid?: string, imsi?: string, meterSerialNumber?: string, meterType?: string): Promise<BootNotificationResponse>;
122 public abstract sendStatusNotification(connectorId: number, status: ChargePointStatus, errorCode?: ChargePointErrorCode): Promise<void>;
163547b1 123 public abstract sendAuthorize(connectorId: number, idTag?: string): Promise<AuthorizeResponse>;
c0560973
JB
124 public abstract sendStartTransaction(connectorId: number, idTag?: string): Promise<StartTransactionResponse>;
125 public abstract sendStopTransaction(transactionId: number, meterStop: number, idTag?: string, reason?: StopTransactionReason): Promise<StopTransactionResponse>;
aef1b33a 126 public abstract sendMeterValues(connectorId: number, transactionId: number, interval: number): Promise<void>;
fd0c36fa
JB
127 public abstract sendTransactionBeginMeterValues(connectorId: number, transactionId: number, beginMeterValue: MeterValue): Promise<void>;
128 public abstract sendTransactionEndMeterValues(connectorId: number, transactionId: number, endMeterValue: MeterValue): Promise<void>;
47e22477 129 public abstract sendDiagnosticsStatusNotification(diagnosticsStatus: DiagnosticsStatus): Promise<void>;
c0560973 130 public abstract sendError(messageId: string, error: OCPPError, commandName: RequestCommand | IncomingRequestCommand): Promise<unknown>;
c0560973 131}