refactor(simulator): switch to internal modules export/import design
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / AbstractUIService.ts
1 import { BaseError, type OCPPError } from '../../../exception';
2 import {
3 BroadcastChannelProcedureName,
4 type BroadcastChannelRequestPayload,
5 ProcedureName,
6 type ProtocolRequest,
7 type ProtocolRequestHandler,
8 type ProtocolVersion,
9 type RequestPayload,
10 type ResponsePayload,
11 ResponseStatus,
12 } from '../../../types';
13 import { logger } from '../../../utils/Logger';
14 import { Utils } from '../../../utils/Utils';
15 import { type AbstractUIServer, Bootstrap, UIServiceWorkerBroadcastChannel } from '../../internal';
16
17 const moduleName = 'AbstractUIService';
18
19 export abstract class AbstractUIService {
20 protected static readonly ProcedureNameToBroadCastChannelProcedureNameMap: Omit<
21 Record<ProcedureName, BroadcastChannelProcedureName>,
22 | ProcedureName.START_SIMULATOR
23 | ProcedureName.STOP_SIMULATOR
24 | ProcedureName.LIST_CHARGING_STATIONS
25 > = {
26 [ProcedureName.START_CHARGING_STATION]: BroadcastChannelProcedureName.START_CHARGING_STATION,
27 [ProcedureName.STOP_CHARGING_STATION]: BroadcastChannelProcedureName.STOP_CHARGING_STATION,
28 [ProcedureName.CLOSE_CONNECTION]: BroadcastChannelProcedureName.CLOSE_CONNECTION,
29 [ProcedureName.OPEN_CONNECTION]: BroadcastChannelProcedureName.OPEN_CONNECTION,
30 [ProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR]:
31 BroadcastChannelProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR,
32 [ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR]:
33 BroadcastChannelProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR,
34 [ProcedureName.START_TRANSACTION]: BroadcastChannelProcedureName.START_TRANSACTION,
35 [ProcedureName.STOP_TRANSACTION]: BroadcastChannelProcedureName.STOP_TRANSACTION,
36 [ProcedureName.AUTHORIZE]: BroadcastChannelProcedureName.AUTHORIZE,
37 [ProcedureName.BOOT_NOTIFICATION]: BroadcastChannelProcedureName.BOOT_NOTIFICATION,
38 [ProcedureName.STATUS_NOTIFICATION]: BroadcastChannelProcedureName.STATUS_NOTIFICATION,
39 [ProcedureName.HEARTBEAT]: BroadcastChannelProcedureName.HEARTBEAT,
40 [ProcedureName.METER_VALUES]: BroadcastChannelProcedureName.METER_VALUES,
41 [ProcedureName.DATA_TRANSFER]: BroadcastChannelProcedureName.DATA_TRANSFER,
42 [ProcedureName.DIAGNOSTICS_STATUS_NOTIFICATION]:
43 BroadcastChannelProcedureName.DIAGNOSTICS_STATUS_NOTIFICATION,
44 [ProcedureName.FIRMWARE_STATUS_NOTIFICATION]:
45 BroadcastChannelProcedureName.FIRMWARE_STATUS_NOTIFICATION,
46 };
47
48 protected readonly requestHandlers: Map<ProcedureName, ProtocolRequestHandler>;
49 private readonly version: ProtocolVersion;
50 private readonly uiServer: AbstractUIServer;
51 private readonly uiServiceWorkerBroadcastChannel: UIServiceWorkerBroadcastChannel;
52 private readonly broadcastChannelRequests: Map<string, number>;
53
54 constructor(uiServer: AbstractUIServer, version: ProtocolVersion) {
55 this.uiServer = uiServer;
56 this.version = version;
57 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
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)],
61 ]);
62 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this);
63 this.broadcastChannelRequests = new Map<string, number>();
64 }
65
66 public async requestHandler(request: ProtocolRequest): Promise<void> {
67 let messageId: string;
68 let command: ProcedureName;
69 let requestPayload: RequestPayload | undefined;
70 let responsePayload: ResponsePayload;
71 try {
72 [messageId, command, requestPayload] = request;
73
74 if (this.requestHandlers.has(command) === false) {
75 throw new BaseError(
76 `${command} is not implemented to handle message payload ${JSON.stringify(
77 requestPayload,
78 null,
79 2
80 )}`
81 );
82 }
83
84 // Call the request handler to build the response payload
85 responsePayload = await this.requestHandlers.get(command)(messageId, command, requestPayload);
86 } catch (error) {
87 // Log
88 logger.error(`${this.logPrefix(moduleName, 'messageHandler')} Handle request error:`, error);
89 responsePayload = {
90 hashIds: requestPayload?.hashIds,
91 status: ResponseStatus.FAILURE,
92 command,
93 requestPayload,
94 responsePayload,
95 errorMessage: (error as Error).message,
96 errorStack: (error as Error).stack,
97 errorDetails: (error as OCPPError).details,
98 };
99 } finally {
100 // Send response for payload not forwarded to broadcast channel
101 if (responsePayload !== undefined) {
102 this.sendResponse(messageId, responsePayload);
103 }
104 }
105 }
106
107 public sendRequest(
108 messageId: string,
109 procedureName: ProcedureName,
110 requestPayload: RequestPayload
111 ): void {
112 this.uiServer.sendRequest(
113 this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload)
114 );
115 }
116
117 public sendResponse(messageId: string, responsePayload: ResponsePayload): void {
118 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload));
119 }
120
121 public logPrefix = (modName: string, methodName: string): string => {
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
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(
148 uuid: string,
149 procedureName: BroadcastChannelProcedureName,
150 payload: BroadcastChannelRequestPayload
151 ): void {
152 if (Utils.isNotEmptyArray(payload.hashIds)) {
153 payload.hashIds = payload.hashIds
154 .filter((hashId) => hashId !== undefined)
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 }
167 const expectedNumberOfResponses = Utils.isNotEmptyArray(payload.hashIds)
168 ? payload.hashIds.length
169 : this.uiServer.chargingStations.size;
170 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload]);
171 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses);
172 }
173
174 private handleListChargingStations(): ResponsePayload {
175 return {
176 status: ResponseStatus.SUCCESS,
177 chargingStations: [...this.uiServer.chargingStations.values()],
178 } as ResponsePayload;
179 }
180
181 private async handleStartSimulator(): Promise<ResponsePayload> {
182 try {
183 await Bootstrap.getInstance().start();
184 return { status: ResponseStatus.SUCCESS };
185 } catch (error) {
186 return { status: ResponseStatus.FAILURE };
187 }
188 }
189
190 private async handleStopSimulator(): Promise<ResponsePayload> {
191 try {
192 await Bootstrap.getInstance().stop();
193 return { status: ResponseStatus.SUCCESS };
194 } catch (error) {
195 return { status: ResponseStatus.FAILURE };
196 }
197 }
198 }