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