d0478b99573c2da29de611e05dba6a737bf21d84
[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 ProtocolResponse,
9 type ProtocolVersion,
10 type RequestPayload,
11 type ResponsePayload,
12 ResponseStatus,
13 } from '../../../types';
14 import { isNotEmptyArray, isNullOrUndefined, logger } from '../../../utils';
15 import { Bootstrap } from '../../Bootstrap';
16 import { UIServiceWorkerBroadcastChannel } from '../../broadcast-channel/UIServiceWorkerBroadcastChannel';
17 import type { AbstractUIServer } from '../AbstractUIServer';
18
19 const moduleName = 'AbstractUIService';
20
21 export abstract class AbstractUIService {
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,
32 BroadcastChannelProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR,
33 ],
34 [
35 ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR,
36 BroadcastChannelProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR,
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,
49 BroadcastChannelProcedureName.DIAGNOSTICS_STATUS_NOTIFICATION,
50 ],
51 [
52 ProcedureName.FIRMWARE_STATUS_NOTIFICATION,
53 BroadcastChannelProcedureName.FIRMWARE_STATUS_NOTIFICATION,
54 ],
55 ]);
56
57 protected readonly requestHandlers: Map<ProcedureName, ProtocolRequestHandler>;
58 private readonly version: ProtocolVersion;
59 private readonly uiServer: AbstractUIServer;
60 private readonly uiServiceWorkerBroadcastChannel: UIServiceWorkerBroadcastChannel;
61 private readonly broadcastChannelRequests: Map<string, number>;
62
63 constructor(uiServer: AbstractUIServer, version: ProtocolVersion) {
64 this.uiServer = uiServer;
65 this.version = version;
66 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
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)],
70 ]);
71 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this);
72 this.broadcastChannelRequests = new Map<string, number>();
73 }
74
75 public async requestHandler(request: ProtocolRequest): Promise<ProtocolResponse | undefined> {
76 let messageId: string | undefined;
77 let command: ProcedureName | undefined;
78 let requestPayload: RequestPayload | undefined;
79 let responsePayload: ResponsePayload | undefined;
80 try {
81 [messageId, command, requestPayload] = request;
82
83 if (this.requestHandlers.has(command) === false) {
84 throw new BaseError(
85 `${command} is not implemented to handle message payload ${JSON.stringify(
86 requestPayload,
87 undefined,
88 2,
89 )}`,
90 );
91 }
92
93 // Call the request handler to build the response payload
94 responsePayload = await this.requestHandlers.get(command)!(
95 messageId,
96 command,
97 requestPayload,
98 );
99 } catch (error) {
100 // Log
101 logger.error(`${this.logPrefix(moduleName, 'requestHandler')} Handle request error:`, error);
102 responsePayload = {
103 hashIds: requestPayload?.hashIds,
104 status: ResponseStatus.FAILURE,
105 command,
106 requestPayload,
107 responsePayload,
108 errorMessage: (error as OCPPError).message,
109 errorStack: (error as OCPPError).stack,
110 errorDetails: (error as OCPPError).details,
111 };
112 }
113 if (!isNullOrUndefined(responsePayload)) {
114 return this.uiServer.buildProtocolResponse(messageId!, responsePayload!);
115 }
116 }
117
118 // public sendRequest(
119 // messageId: string,
120 // procedureName: ProcedureName,
121 // requestPayload: RequestPayload,
122 // ): void {
123 // this.uiServer.sendRequest(
124 // this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload),
125 // );
126 // }
127
128 public sendResponse(messageId: string, responsePayload: ResponsePayload): void {
129 if (this.uiServer.hasResponseHandler(messageId)) {
130 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload));
131 }
132 }
133
134 public logPrefix = (modName: string, methodName: string): string => {
135 return this.uiServer.logPrefix(modName, methodName, this.version);
136 };
137
138 public deleteBroadcastChannelRequest(uuid: string): void {
139 this.broadcastChannelRequests.delete(uuid);
140 }
141
142 public getBroadcastChannelExpectedResponses(uuid: string): number {
143 return this.broadcastChannelRequests.get(uuid) ?? 0;
144 }
145
146 protected handleProtocolRequest(
147 uuid: string,
148 procedureName: ProcedureName,
149 payload: RequestPayload,
150 ): void {
151 this.sendBroadcastChannelRequest(
152 uuid,
153 AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMapping.get(procedureName)!,
154 payload,
155 );
156 }
157
158 private sendBroadcastChannelRequest(
159 uuid: string,
160 procedureName: BroadcastChannelProcedureName,
161 payload: BroadcastChannelRequestPayload,
162 ): void {
163 if (isNotEmptyArray(payload.hashIds)) {
164 payload.hashIds = payload.hashIds
165 ?.map((hashId) => {
166 if (hashId !== undefined && this.uiServer.chargingStations.has(hashId) === true) {
167 return hashId;
168 }
169 const msg = `${this.logPrefix(
170 moduleName,
171 'sendBroadcastChannelRequest',
172 )} Charging station with hashId '${hashId}' not found`;
173 if (payload.hashIds?.length === 1) {
174 throw new BaseError(msg);
175 } else {
176 logger.warn(msg);
177 }
178 })
179 ?.filter((hashId) => !isNullOrUndefined(hashId)) as string[];
180 }
181 const expectedNumberOfResponses = isNotEmptyArray(payload.hashIds)
182 ? payload.hashIds!.length
183 : this.uiServer.chargingStations.size;
184 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload]);
185 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses);
186 }
187
188 private handleListChargingStations(): ResponsePayload {
189 return {
190 status: ResponseStatus.SUCCESS,
191 chargingStations: [...this.uiServer.chargingStations.values()],
192 } as ResponsePayload;
193 }
194
195 private async handleStartSimulator(): Promise<ResponsePayload> {
196 try {
197 await Bootstrap.getInstance().start();
198 return { status: ResponseStatus.SUCCESS };
199 } catch {
200 return { status: ResponseStatus.FAILURE };
201 }
202 }
203
204 private async handleStopSimulator(): Promise<ResponsePayload> {
205 try {
206 await Bootstrap.getInstance().stop();
207 return { status: ResponseStatus.SUCCESS };
208 } catch {
209 return { status: ResponseStatus.FAILURE };
210 }
211 }
212 }