Convert interface to type
[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 {
5083d31a 25 private 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,
46 };
47
02a6943a 48 protected readonly requestHandlers: Map<ProcedureName, ProtocolRequestHandler>;
53870cff
JB
49 private readonly version: ProtocolVersion;
50 private readonly uiServer: AbstractUIServer;
51 private readonly uiServiceWorkerBroadcastChannel: UIServiceWorkerBroadcastChannel;
0d2cec76 52 private readonly broadcastChannelRequests: Map<string, number>;
4198ad5c 53
33cea517 54 constructor(uiServer: AbstractUIServer, version: ProtocolVersion) {
675fa8e3 55 this.uiServer = uiServer;
976d11ec 56 this.version = version;
02a6943a 57 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
32de5a57
LM
58 [ProcedureName.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
59 [ProcedureName.START_SIMULATOR, this.handleStartSimulator.bind(this)],
60 [ProcedureName.STOP_SIMULATOR, this.handleStopSimulator.bind(this)],
4198ad5c 61 ]);
6812b4e1 62 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this);
0d2cec76 63 this.broadcastChannelRequests = new Map<string, number>();
4198ad5c
JB
64 }
65
5e3cb728 66 public async requestHandler(request: ProtocolRequest): Promise<void> {
98a5256a 67 let messageId: string;
32de5a57 68 let command: ProcedureName;
6c8f5d90 69 let requestPayload: RequestPayload | undefined;
32de5a57
LM
70 let responsePayload: ResponsePayload;
71 try {
5e3cb728 72 [messageId, command, requestPayload] = request;
32de5a57 73
02a6943a 74 if (this.requestHandlers.has(command) === false) {
32de5a57
LM
75 throw new BaseError(
76 `${command} is not implemented to handle message payload ${JSON.stringify(
77 requestPayload,
78 null,
79 2
80 )}`
81 );
4198ad5c 82 }
89b7a234 83
6c8f5d90 84 // Call the request handler to build the response payload
5e8e29f4 85 responsePayload = await this.requestHandlers.get(command)(messageId, command, requestPayload);
32de5a57
LM
86 } catch (error) {
87 // Log
1f7fa4de 88 logger.error(`${this.logPrefix(moduleName, 'messageHandler')} Handle request error:`, error);
6c8f5d90 89 responsePayload = {
9d73266c 90 hashIds: requestPayload.hashIds,
6c8f5d90
JB
91 status: ResponseStatus.FAILURE,
92 command,
93 requestPayload,
94 responsePayload,
95 errorMessage: (error as Error).message,
96 errorStack: (error as Error).stack,
9d73266c 97 errorDetails: (error as OCPPError).details,
6c8f5d90 98 };
623b39b5
JB
99 } finally {
100 // Send response for payload not forwarded to broadcast channel
101 if (responsePayload !== undefined) {
d3195f0a 102 this.sendResponse(messageId, responsePayload);
623b39b5 103 }
4198ad5c 104 }
6c8f5d90
JB
105 }
106
107 public sendRequest(
108 messageId: string,
109 procedureName: ProcedureName,
110 requestPayload: RequestPayload
111 ): void {
852a4c5f
JB
112 this.uiServer.sendRequest(
113 this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload)
114 );
6c8f5d90 115 }
32de5a57 116
6c8f5d90 117 public sendResponse(messageId: string, responsePayload: ResponsePayload): void {
852a4c5f 118 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload));
4198ad5c
JB
119 }
120
6c8f5d90 121 public logPrefix(modName: string, methodName: string): string {
0d2cec76
JB
122 return this.uiServer.logPrefix(modName, methodName, this.version);
123 }
124
125 public deleteBroadcastChannelRequest(uuid: string): void {
126 this.broadcastChannelRequests.delete(uuid);
127 }
128
129 public getBroadcastChannelExpectedResponses(uuid: string): number {
130 return this.broadcastChannelRequests.get(uuid) ?? 0;
131 }
132
2a3cf7fc
JB
133 protected handleProtocolRequest(
134 uuid: string,
135 procedureName: ProcedureName,
136 payload: RequestPayload
137 ): void {
138 this.sendBroadcastChannelRequest(
139 uuid,
140 AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMap[
141 procedureName
142 ] as BroadcastChannelProcedureName,
143 payload
144 );
145 }
146
147 private sendBroadcastChannelRequest(
0d2cec76
JB
148 uuid: string,
149 procedureName: BroadcastChannelProcedureName,
150 payload: BroadcastChannelRequestPayload
151 ): void {
152 if (!Utils.isEmptyArray(payload.hashIds)) {
153 payload.hashIds = payload.hashIds
154 .map((hashId) => {
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 );
164 })
165 .filter((hashId) => hashId !== undefined);
166 }
167 const expectedNumberOfResponses = !Utils.isEmptyArray(payload.hashIds)
168 ? payload.hashIds.length
169 : this.uiServer.chargingStations.size;
0d2cec76 170 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload]);
853ed24a 171 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses);
6c8f5d90
JB
172 }
173
89b7a234 174 private handleListChargingStations(): ResponsePayload {
32de5a57
LM
175 return {
176 status: ResponseStatus.SUCCESS,
5e3cb728
JB
177 chargingStations: [...this.uiServer.chargingStations.values()],
178 } as ResponsePayload;
32de5a57
LM
179 }
180
181 private async handleStartSimulator(): Promise<ResponsePayload> {
182 await Bootstrap.getInstance().start();
183 return { status: ResponseStatus.SUCCESS };
184 }
185
186 private async handleStopSimulator(): Promise<ResponsePayload> {
187 await Bootstrap.getInstance().stop();
188 return { status: ResponseStatus.SUCCESS };
4198ad5c
JB
189 }
190}