Add GetDiagnostics command support
[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';
c0560973
JB
12import OCPPError from '../OcppError';
13import OCPPResponseService from './OCPPResponseService';
14import logger from '../../utils/Logger';
15
16export default abstract class OCPPRequestService {
17 public chargingStation: ChargingStation;
18 protected ocppResponseService: OCPPResponseService;
19
20 constructor(chargingStation: ChargingStation, ocppResponseService: OCPPResponseService) {
21 this.chargingStation = chargingStation;
22 this.ocppResponseService = ocppResponseService;
23 }
24
193d2c0a 25 public async sendMessage(messageId: string, commandParams: any, messageType: MessageType, commandName: RequestCommand | IncomingRequestCommand): Promise<any> {
c0560973
JB
26 // eslint-disable-next-line @typescript-eslint/no-this-alias
27 const self = this;
c0560973
JB
28 // Send a message through wsConnection
29 return new Promise((resolve: (value?: any | PromiseLike<any>) => void, reject: (reason?: any) => void) => {
30 let messageToSend: string;
31 // Type of message
32 switch (messageType) {
33 // Request
34 case MessageType.CALL_MESSAGE:
35 // Build request
6e0964c8 36 this.chargingStation.requests[messageId] = [responseCallback, rejectCallback, commandParams as Record<string, unknown>];
c0560973
JB
37 messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]);
38 break;
39 // Response
40 case MessageType.CALL_RESULT_MESSAGE:
41 // Build response
42 messageToSend = JSON.stringify([messageType, messageId, commandParams]);
43 break;
44 // Error Message
45 case MessageType.CALL_ERROR_MESSAGE:
46 // Build Error Message
47 messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]);
48 break;
49 }
50 // Check if wsConnection opened and charging station registered
51 if (this.chargingStation.isWebSocketOpen() && (this.chargingStation.isRegistered() || commandName === RequestCommand.BOOT_NOTIFICATION)) {
52 if (this.chargingStation.getEnableStatistics()) {
54b1efe0 53 this.chargingStation.performanceStatistics.addMessage(commandName, messageType);
c0560973
JB
54 }
55 // Yes: Send Message
56 this.chargingStation.wsConnection.send(messageToSend);
57 } else if (commandName !== RequestCommand.BOOT_NOTIFICATION) {
3ba2381e 58 // Buffer it
77f00f84 59 this.chargingStation.addToMessageQueue(messageToSend);
c0560973
JB
60 // Reject it
61 return rejectCallback(new OCPPError(commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams.details ? commandParams.details : {}));
62 }
63 // Response?
64 if (messageType === MessageType.CALL_RESULT_MESSAGE) {
65 // Yes: send Ok
66 resolve();
67 } else if (messageType === MessageType.CALL_ERROR_MESSAGE) {
68 // Send timeout
69 setTimeout(() => rejectCallback(new OCPPError(commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams.details ? commandParams.details : {})), Constants.OCPP_ERROR_TIMEOUT);
70 }
71
3340259a
JB
72 /**
73 * Function that will receive the request's response
74 *
e71cccf3
JB
75 * @param {Record<string, unknown> | string} payload
76 * @param {Record<string, unknown>} requestPayload
3340259a 77 */
c0560973 78 async function responseCallback(payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>): Promise<void> {
52748e2c 79 if (self.chargingStation.getEnableStatistics()) {
54b1efe0 80 self.chargingStation.performanceStatistics.addMessage(commandName, MessageType.CALL_RESULT_MESSAGE);
c0560973
JB
81 }
82 // Send the response
83 await self.ocppResponseService.handleResponse(commandName as RequestCommand, payload, requestPayload);
84 resolve(payload);
85 }
86
3340259a
JB
87 /**
88 * Function that will receive the request's rejection
89 *
e71cccf3 90 * @param {OCPPError} error
3340259a 91 */
c0560973 92 function rejectCallback(error: OCPPError): void {
52748e2c 93 if (self.chargingStation.getEnableStatistics()) {
54b1efe0 94 self.chargingStation.performanceStatistics.addMessage(commandName, MessageType.CALL_ERROR_MESSAGE);
c0560973 95 }
52748e2c 96 logger.debug(`${self.chargingStation.logPrefix()} Error: %j occurred when calling command %s with parameters: %j`, error, commandName, commandParams);
c0560973
JB
97 // Build Exception
98 // eslint-disable-next-line no-empty-function
52748e2c 99 self.chargingStation.requests[messageId] = [() => { }, () => { }, {}];
c0560973
JB
100 // Send error
101 reject(error);
102 }
103 });
104 }
105
106 public handleRequestError(commandName: RequestCommand, error: Error): void {
47e22477 107 logger.error(this.chargingStation.logPrefix() + ' Request command ' + commandName + ' error: %j', error);
c0560973
JB
108 throw error;
109 }
110
111 public abstract sendHeartbeat(): Promise<void>;
112 public abstract sendBootNotification(chargePointModel: string, chargePointVendor: string, chargeBoxSerialNumber?: string, firmwareVersion?: string, chargePointSerialNumber?: string, iccid?: string, imsi?: string, meterSerialNumber?: string, meterType?: string): Promise<BootNotificationResponse>;
113 public abstract sendStatusNotification(connectorId: number, status: ChargePointStatus, errorCode?: ChargePointErrorCode): Promise<void>;
163547b1 114 public abstract sendAuthorize(connectorId: number, idTag?: string): Promise<AuthorizeResponse>;
c0560973
JB
115 public abstract sendStartTransaction(connectorId: number, idTag?: string): Promise<StartTransactionResponse>;
116 public abstract sendStopTransaction(transactionId: number, meterStop: number, idTag?: string, reason?: StopTransactionReason): Promise<StopTransactionResponse>;
117 public abstract sendMeterValues(connectorId: number, transactionId: number, interval: number, self: OCPPRequestService): Promise<void>;
fd0c36fa
JB
118 public abstract sendTransactionBeginMeterValues(connectorId: number, transactionId: number, beginMeterValue: MeterValue): Promise<void>;
119 public abstract sendTransactionEndMeterValues(connectorId: number, transactionId: number, endMeterValue: MeterValue): Promise<void>;
47e22477 120 public abstract sendDiagnosticsStatusNotification(diagnosticsStatus: DiagnosticsStatus): Promise<void>;
c0560973 121 public abstract sendError(messageId: string, error: OCPPError, commandName: RequestCommand | IncomingRequestCommand): Promise<unknown>;
c0560973 122}