build: properly workaround Ajv TS type definitions bug
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / AbstractUIService.ts
CommitLineData
a6ef1ece 1import { BaseError, type OCPPError } from '../../../exception/index.js';
675fa8e3 2import {
268a74bb
JB
3 BroadcastChannelProcedureName,
4 type BroadcastChannelRequestPayload,
32de5a57 5 ProcedureName,
976d11ec
JB
6 type ProtocolRequest,
7 type ProtocolRequestHandler,
f130b8e6 8 type ProtocolResponse,
976d11ec
JB
9 type ProtocolVersion,
10 type RequestPayload,
11 type ResponsePayload,
32de5a57 12 ResponseStatus,
a6ef1ece
JB
13} from '../../../types/index.js';
14import { isNotEmptyArray, isNullOrUndefined, logger } from '../../../utils/index.js';
15import { Bootstrap } from '../../Bootstrap.js';
16import { UIServiceWorkerBroadcastChannel } from '../../broadcast-channel/UIServiceWorkerBroadcastChannel.js';
17import type { AbstractUIServer } from '../AbstractUIServer.js';
4198ad5c 18
32de5a57
LM
19const moduleName = 'AbstractUIService';
20
268a74bb 21export abstract class AbstractUIService {
a37fc6dc
JB
22 protected static readonly ProcedureNameToBroadCastChannelProcedureNameMapping = new Map<
23 ProcedureName,
24 BroadcastChannelProcedureName
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 [
31 ProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR,
976d11ec 32 BroadcastChannelProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR,
a37fc6dc
JB
33 ],
34 [
35 ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR,
976d11ec 36 BroadcastChannelProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR,
a37fc6dc
JB
37 ],
38 [ProcedureName.SET_SUPERVISION_URL, BroadcastChannelProcedureName.SET_SUPERVISION_URL],
39 [ProcedureName.START_TRANSACTION, BroadcastChannelProcedureName.START_TRANSACTION],
40 [ProcedureName.STOP_TRANSACTION, BroadcastChannelProcedureName.STOP_TRANSACTION],
41 [ProcedureName.AUTHORIZE, BroadcastChannelProcedureName.AUTHORIZE],
42 [ProcedureName.BOOT_NOTIFICATION, BroadcastChannelProcedureName.BOOT_NOTIFICATION],
43 [ProcedureName.STATUS_NOTIFICATION, BroadcastChannelProcedureName.STATUS_NOTIFICATION],
44 [ProcedureName.HEARTBEAT, BroadcastChannelProcedureName.HEARTBEAT],
45 [ProcedureName.METER_VALUES, BroadcastChannelProcedureName.METER_VALUES],
46 [ProcedureName.DATA_TRANSFER, BroadcastChannelProcedureName.DATA_TRANSFER],
47 [
48 ProcedureName.DIAGNOSTICS_STATUS_NOTIFICATION,
c9a4f9ea 49 BroadcastChannelProcedureName.DIAGNOSTICS_STATUS_NOTIFICATION,
a37fc6dc
JB
50 ],
51 [
52 ProcedureName.FIRMWARE_STATUS_NOTIFICATION,
c9a4f9ea 53 BroadcastChannelProcedureName.FIRMWARE_STATUS_NOTIFICATION,
a37fc6dc
JB
54 ],
55 ]);
976d11ec 56
02a6943a 57 protected readonly requestHandlers: Map<ProcedureName, ProtocolRequestHandler>;
53870cff
JB
58 private readonly version: ProtocolVersion;
59 private readonly uiServer: AbstractUIServer;
60 private readonly uiServiceWorkerBroadcastChannel: UIServiceWorkerBroadcastChannel;
0d2cec76 61 private readonly broadcastChannelRequests: Map<string, number>;
4198ad5c 62
33cea517 63 constructor(uiServer: AbstractUIServer, version: ProtocolVersion) {
675fa8e3 64 this.uiServer = uiServer;
976d11ec 65 this.version = version;
02a6943a 66 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
32de5a57
LM
67 [ProcedureName.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
68 [ProcedureName.START_SIMULATOR, this.handleStartSimulator.bind(this)],
69 [ProcedureName.STOP_SIMULATOR, this.handleStopSimulator.bind(this)],
4198ad5c 70 ]);
6812b4e1 71 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this);
0d2cec76 72 this.broadcastChannelRequests = new Map<string, number>();
4198ad5c
JB
73 }
74
f130b8e6 75 public async requestHandler(request: ProtocolRequest): Promise<ProtocolResponse | undefined> {
e1d9a0f4
JB
76 let messageId: string | undefined;
77 let command: ProcedureName | undefined;
6c8f5d90 78 let requestPayload: RequestPayload | undefined;
f130b8e6 79 let responsePayload: ResponsePayload | undefined;
32de5a57 80 try {
5e3cb728 81 [messageId, command, requestPayload] = request;
32de5a57 82
02a6943a 83 if (this.requestHandlers.has(command) === false) {
32de5a57
LM
84 throw new BaseError(
85 `${command} is not implemented to handle message payload ${JSON.stringify(
86 requestPayload,
4ed03b6e 87 undefined,
5edd8ba0
JB
88 2,
89 )}`,
32de5a57 90 );
4198ad5c 91 }
89b7a234 92
6c8f5d90 93 // Call the request handler to build the response payload
e1d9a0f4
JB
94 responsePayload = await this.requestHandlers.get(command)!(
95 messageId,
96 command,
97 requestPayload,
98 );
32de5a57
LM
99 } catch (error) {
100 // Log
6bd808fd 101 logger.error(`${this.logPrefix(moduleName, 'requestHandler')} Handle request error:`, error);
6c8f5d90 102 responsePayload = {
551e477c 103 hashIds: requestPayload?.hashIds,
6c8f5d90
JB
104 status: ResponseStatus.FAILURE,
105 command,
106 requestPayload,
107 responsePayload,
7375968c
JB
108 errorMessage: (error as OCPPError).message,
109 errorStack: (error as OCPPError).stack,
9d73266c 110 errorDetails: (error as OCPPError).details,
6c8f5d90 111 };
f130b8e6 112 }
9bf0ef23 113 if (!isNullOrUndefined(responsePayload)) {
e1d9a0f4 114 return this.uiServer.buildProtocolResponse(messageId!, responsePayload!);
4198ad5c 115 }
6c8f5d90
JB
116 }
117
0b22144c
JB
118 // public sendRequest(
119 // messageId: string,
120 // procedureName: ProcedureName,
3c8798b1 121 // requestPayload: RequestPayload,
0b22144c
JB
122 // ): void {
123 // this.uiServer.sendRequest(
3c8798b1 124 // this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload),
0b22144c
JB
125 // );
126 // }
32de5a57 127
6c8f5d90 128 public sendResponse(messageId: string, responsePayload: ResponsePayload): void {
1ca4a038
JB
129 if (this.uiServer.hasResponseHandler(messageId)) {
130 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload));
131 }
4198ad5c
JB
132 }
133
8b7072dc 134 public logPrefix = (modName: string, methodName: string): string => {
0d2cec76 135 return this.uiServer.logPrefix(modName, methodName, this.version);
8b7072dc 136 };
0d2cec76
JB
137
138 public deleteBroadcastChannelRequest(uuid: string): void {
139 this.broadcastChannelRequests.delete(uuid);
140 }
141
142 public getBroadcastChannelExpectedResponses(uuid: string): number {
3a6ef20a 143 return this.broadcastChannelRequests.get(uuid)!;
0d2cec76
JB
144 }
145
2a3cf7fc
JB
146 protected handleProtocolRequest(
147 uuid: string,
148 procedureName: ProcedureName,
5edd8ba0 149 payload: RequestPayload,
2a3cf7fc
JB
150 ): void {
151 this.sendBroadcastChannelRequest(
152 uuid,
a37fc6dc 153 AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMapping.get(procedureName)!,
5edd8ba0 154 payload,
2a3cf7fc
JB
155 );
156 }
157
158 private sendBroadcastChannelRequest(
0d2cec76
JB
159 uuid: string,
160 procedureName: BroadcastChannelProcedureName,
5edd8ba0 161 payload: BroadcastChannelRequestPayload,
0d2cec76 162 ): void {
9bf0ef23 163 if (isNotEmptyArray(payload.hashIds)) {
0d2cec76 164 payload.hashIds = payload.hashIds
e1d9a0f4 165 ?.map((hashId) => {
31fdd918 166 if (hashId !== undefined && this.uiServer.chargingStations.has(hashId) === true) {
0d2cec76
JB
167 return hashId;
168 }
3a6ef20a
JB
169 logger.warn(
170 `${this.logPrefix(
171 moduleName,
172 'sendBroadcastChannelRequest',
173 )} Charging station with hashId '${hashId}' not found`,
174 );
f12cf7ef
JB
175 })
176 ?.filter((hashId) => !isNullOrUndefined(hashId)) as string[];
3a6ef20a
JB
177 } else {
178 delete payload.hashIds;
0d2cec76 179 }
3a6ef20a
JB
180 const expectedNumberOfResponses = Array.isArray(payload.hashIds)
181 ? payload.hashIds.length
0d2cec76 182 : this.uiServer.chargingStations.size;
3a6ef20a
JB
183 if (expectedNumberOfResponses === 0) {
184 throw new BaseError(
185 'hashIds array in the request payload does not contain any valid charging station hashId',
186 );
187 }
0d2cec76 188 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload]);
853ed24a 189 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses);
6c8f5d90
JB
190 }
191
89b7a234 192 private handleListChargingStations(): ResponsePayload {
32de5a57
LM
193 return {
194 status: ResponseStatus.SUCCESS,
5e3cb728
JB
195 chargingStations: [...this.uiServer.chargingStations.values()],
196 } as ResponsePayload;
32de5a57
LM
197 }
198
199 private async handleStartSimulator(): Promise<ResponsePayload> {
4ec634b7
JB
200 try {
201 await Bootstrap.getInstance().start();
202 return { status: ResponseStatus.SUCCESS };
9c0ecbdf 203 } catch {
4ec634b7
JB
204 return { status: ResponseStatus.FAILURE };
205 }
32de5a57
LM
206 }
207
208 private async handleStopSimulator(): Promise<ResponsePayload> {
4ec634b7
JB
209 try {
210 await Bootstrap.getInstance().stop();
211 return { status: ResponseStatus.SUCCESS };
9c0ecbdf 212 } catch {
4ec634b7
JB
213 return { status: ResponseStatus.FAILURE };
214 }
4198ad5c
JB
215 }
216}