Add OCPP DataTransfer request support
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / AbstractUIService.ts
CommitLineData
8114d10e 1import BaseError from '../../../exception/BaseError';
9d73266c 2import type OCPPError from '../../../exception/OCPPError';
5a010bf0 3import { Bootstrap } from '../../../internal';
675fa8e3 4import {
32de5a57 5 ProcedureName,
976d11ec
JB
6 type ProtocolRequest,
7 type ProtocolRequestHandler,
8 type ProtocolVersion,
9 type RequestPayload,
10 type ResponsePayload,
32de5a57 11 ResponseStatus,
675fa8e3 12} from '../../../types/UIProtocol';
976d11ec 13import {
0d2cec76 14 BroadcastChannelProcedureName,
976d11ec 15 type BroadcastChannelRequestPayload,
0d2cec76 16} from '../../../types/WorkerBroadcastChannel';
675fa8e3 17import logger from '../../../utils/Logger';
0d2cec76 18import Utils from '../../../utils/Utils';
6c8f5d90 19import UIServiceWorkerBroadcastChannel from '../../UIServiceWorkerBroadcastChannel';
db2336d9 20import type { AbstractUIServer } from '../AbstractUIServer';
4198ad5c 21
32de5a57
LM
22const moduleName = 'AbstractUIService';
23
4198ad5c 24export default abstract class AbstractUIService {
d56ea27c 25 protected static readonly ProcedureNameToBroadCastChannelProcedureNameMap: Omit<
976d11ec 26 Record<ProcedureName, BroadcastChannelProcedureName>,
17e9e8ce
JB
27 | ProcedureName.START_SIMULATOR
28 | ProcedureName.STOP_SIMULATOR
29 | ProcedureName.LIST_CHARGING_STATIONS
976d11ec
JB
30 > = {
31 [ProcedureName.START_CHARGING_STATION]: BroadcastChannelProcedureName.START_CHARGING_STATION,
32 [ProcedureName.STOP_CHARGING_STATION]: BroadcastChannelProcedureName.STOP_CHARGING_STATION,
33 [ProcedureName.CLOSE_CONNECTION]: BroadcastChannelProcedureName.CLOSE_CONNECTION,
34 [ProcedureName.OPEN_CONNECTION]: BroadcastChannelProcedureName.OPEN_CONNECTION,
35 [ProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR]:
36 BroadcastChannelProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR,
37 [ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR]:
38 BroadcastChannelProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR,
39 [ProcedureName.START_TRANSACTION]: BroadcastChannelProcedureName.START_TRANSACTION,
40 [ProcedureName.STOP_TRANSACTION]: BroadcastChannelProcedureName.STOP_TRANSACTION,
41 [ProcedureName.AUTHORIZE]: BroadcastChannelProcedureName.AUTHORIZE,
8bfbc743 42 [ProcedureName.BOOT_NOTIFICATION]: BroadcastChannelProcedureName.BOOT_NOTIFICATION,
976d11ec
JB
43 [ProcedureName.STATUS_NOTIFICATION]: BroadcastChannelProcedureName.STATUS_NOTIFICATION,
44 [ProcedureName.HEARTBEAT]: BroadcastChannelProcedureName.HEARTBEAT,
45 [ProcedureName.METER_VALUES]: BroadcastChannelProcedureName.METER_VALUES,
91a7d3ea 46 [ProcedureName.DATA_TRANSFER]: BroadcastChannelProcedureName.DATA_TRANSFER,
976d11ec
JB
47 };
48
02a6943a 49 protected readonly requestHandlers: Map<ProcedureName, ProtocolRequestHandler>;
53870cff
JB
50 private readonly version: ProtocolVersion;
51 private readonly uiServer: AbstractUIServer;
52 private readonly uiServiceWorkerBroadcastChannel: UIServiceWorkerBroadcastChannel;
0d2cec76 53 private readonly broadcastChannelRequests: Map<string, number>;
4198ad5c 54
33cea517 55 constructor(uiServer: AbstractUIServer, version: ProtocolVersion) {
675fa8e3 56 this.uiServer = uiServer;
976d11ec 57 this.version = version;
02a6943a 58 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
32de5a57
LM
59 [ProcedureName.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
60 [ProcedureName.START_SIMULATOR, this.handleStartSimulator.bind(this)],
61 [ProcedureName.STOP_SIMULATOR, this.handleStopSimulator.bind(this)],
4198ad5c 62 ]);
6812b4e1 63 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this);
0d2cec76 64 this.broadcastChannelRequests = new Map<string, number>();
4198ad5c
JB
65 }
66
5e3cb728 67 public async requestHandler(request: ProtocolRequest): Promise<void> {
98a5256a 68 let messageId: string;
32de5a57 69 let command: ProcedureName;
6c8f5d90 70 let requestPayload: RequestPayload | undefined;
32de5a57
LM
71 let responsePayload: ResponsePayload;
72 try {
5e3cb728 73 [messageId, command, requestPayload] = request;
32de5a57 74
02a6943a 75 if (this.requestHandlers.has(command) === false) {
32de5a57
LM
76 throw new BaseError(
77 `${command} is not implemented to handle message payload ${JSON.stringify(
78 requestPayload,
79 null,
80 2
81 )}`
82 );
4198ad5c 83 }
89b7a234 84
6c8f5d90 85 // Call the request handler to build the response payload
5e8e29f4 86 responsePayload = await this.requestHandlers.get(command)(messageId, command, requestPayload);
32de5a57
LM
87 } catch (error) {
88 // Log
1f7fa4de 89 logger.error(`${this.logPrefix(moduleName, 'messageHandler')} Handle request error:`, error);
6c8f5d90 90 responsePayload = {
9d73266c 91 hashIds: requestPayload.hashIds,
6c8f5d90
JB
92 status: ResponseStatus.FAILURE,
93 command,
94 requestPayload,
95 responsePayload,
96 errorMessage: (error as Error).message,
97 errorStack: (error as Error).stack,
9d73266c 98 errorDetails: (error as OCPPError).details,
6c8f5d90 99 };
623b39b5
JB
100 } finally {
101 // Send response for payload not forwarded to broadcast channel
102 if (responsePayload !== undefined) {
d3195f0a 103 this.sendResponse(messageId, responsePayload);
623b39b5 104 }
4198ad5c 105 }
6c8f5d90
JB
106 }
107
108 public sendRequest(
109 messageId: string,
110 procedureName: ProcedureName,
111 requestPayload: RequestPayload
112 ): void {
852a4c5f
JB
113 this.uiServer.sendRequest(
114 this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload)
115 );
6c8f5d90 116 }
32de5a57 117
6c8f5d90 118 public sendResponse(messageId: string, responsePayload: ResponsePayload): void {
852a4c5f 119 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload));
4198ad5c
JB
120 }
121
6c8f5d90 122 public logPrefix(modName: string, methodName: string): string {
0d2cec76
JB
123 return this.uiServer.logPrefix(modName, methodName, this.version);
124 }
125
126 public deleteBroadcastChannelRequest(uuid: string): void {
127 this.broadcastChannelRequests.delete(uuid);
128 }
129
130 public getBroadcastChannelExpectedResponses(uuid: string): number {
131 return this.broadcastChannelRequests.get(uuid) ?? 0;
132 }
133
2a3cf7fc
JB
134 protected handleProtocolRequest(
135 uuid: string,
136 procedureName: ProcedureName,
137 payload: RequestPayload
138 ): void {
139 this.sendBroadcastChannelRequest(
140 uuid,
141 AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMap[
142 procedureName
143 ] as BroadcastChannelProcedureName,
144 payload
145 );
146 }
147
148 private sendBroadcastChannelRequest(
0d2cec76
JB
149 uuid: string,
150 procedureName: BroadcastChannelProcedureName,
151 payload: BroadcastChannelRequestPayload
152 ): void {
153 if (!Utils.isEmptyArray(payload.hashIds)) {
154 payload.hashIds = payload.hashIds
155 .map((hashId) => {
156 if (this.uiServer.chargingStations.has(hashId) === true) {
157 return hashId;
158 }
159 logger.warn(
160 `${this.logPrefix(
161 moduleName,
162 'sendBroadcastChannelRequest'
163 )} Charging station with hashId '${hashId}' not found`
164 );
165 })
166 .filter((hashId) => hashId !== undefined);
167 }
168 const expectedNumberOfResponses = !Utils.isEmptyArray(payload.hashIds)
169 ? payload.hashIds.length
170 : this.uiServer.chargingStations.size;
0d2cec76 171 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload]);
853ed24a 172 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses);
6c8f5d90
JB
173 }
174
89b7a234 175 private handleListChargingStations(): ResponsePayload {
32de5a57
LM
176 return {
177 status: ResponseStatus.SUCCESS,
5e3cb728
JB
178 chargingStations: [...this.uiServer.chargingStations.values()],
179 } as ResponsePayload;
32de5a57
LM
180 }
181
182 private async handleStartSimulator(): Promise<ResponsePayload> {
183 await Bootstrap.getInstance().start();
184 return { status: ResponseStatus.SUCCESS };
185 }
186
187 private async handleStopSimulator(): Promise<ResponsePayload> {
188 await Bootstrap.getInstance().stop();
189 return { status: ResponseStatus.SUCCESS };
4198ad5c
JB
190 }
191}