89db2302c81e1dec901965efeb4c6444196a5d30
[e-mobility-charging-stations-simulator.git] / ui / web / src / composables / UIClient.ts
1 import {
2 ProcedureName,
3 type ProtocolResponse,
4 type RequestPayload,
5 type ResponsePayload,
6 ResponseStatus,
7 } from '@/types';
8 import config from '@/assets/config';
9
10 type ResponseHandler = {
11 procedureName: ProcedureName;
12 resolve: (value: ResponsePayload | PromiseLike<ResponsePayload>) => void;
13 reject: (reason?: unknown) => void;
14 };
15
16 export class UIClient {
17 private static instance: UIClient | null = null;
18
19 private ws!: WebSocket;
20 private responseHandlers: Map<string, ResponseHandler>;
21
22 private constructor() {
23 this.openWS();
24 this.responseHandlers = new Map<string, ResponseHandler>();
25 }
26
27 public static getInstance() {
28 if (UIClient.instance === null) {
29 UIClient.instance = new UIClient();
30 }
31 return UIClient.instance;
32 }
33
34 public registerWSonOpenListener(listener: (event: Event) => void) {
35 this.ws.addEventListener('open', listener);
36 }
37
38 public async startSimulator(): Promise<ResponsePayload> {
39 return this.sendRequest(ProcedureName.START_SIMULATOR, {});
40 }
41
42 public async stopSimulator(): Promise<ResponsePayload> {
43 return this.sendRequest(ProcedureName.STOP_SIMULATOR, {});
44 }
45
46 public async listChargingStations(): Promise<ResponsePayload> {
47 return this.sendRequest(ProcedureName.LIST_CHARGING_STATIONS, {});
48 }
49
50 public async startChargingStation(hashId: string): Promise<ResponsePayload> {
51 return this.sendRequest(ProcedureName.START_CHARGING_STATION, { hashIds: [hashId] });
52 }
53
54 public async stopChargingStation(hashId: string): Promise<ResponsePayload> {
55 return this.sendRequest(ProcedureName.STOP_CHARGING_STATION, { hashIds: [hashId] });
56 }
57
58 public async openConnection(hashId: string): Promise<ResponsePayload> {
59 return this.sendRequest(ProcedureName.OPEN_CONNECTION, {
60 hashIds: [hashId],
61 });
62 }
63
64 public async closeConnection(hashId: string): Promise<ResponsePayload> {
65 return this.sendRequest(ProcedureName.CLOSE_CONNECTION, {
66 hashIds: [hashId],
67 });
68 }
69
70 public async startTransaction(
71 hashId: string,
72 connectorId: number,
73 idTag: string | undefined,
74 ): Promise<ResponsePayload> {
75 return this.sendRequest(ProcedureName.START_TRANSACTION, {
76 hashIds: [hashId],
77 connectorId,
78 idTag,
79 });
80 }
81
82 public async stopTransaction(
83 hashId: string,
84 transactionId: number | undefined,
85 ): Promise<ResponsePayload> {
86 return this.sendRequest(ProcedureName.STOP_TRANSACTION, {
87 hashIds: [hashId],
88 transactionId,
89 });
90 }
91
92 public async startAutomaticTransactionGenerator(
93 hashId: string,
94 connectorId: number,
95 ): Promise<ResponsePayload> {
96 return this.sendRequest(ProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR, {
97 hashIds: [hashId],
98 connectorIds: [connectorId],
99 });
100 }
101
102 public async stopAutomaticTransactionGenerator(
103 hashId: string,
104 connectorId: number,
105 ): Promise<ResponsePayload> {
106 return this.sendRequest(ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR, {
107 hashIds: [hashId],
108 connectorIds: [connectorId],
109 });
110 }
111
112 private openWS(): void {
113 this.ws = new WebSocket(
114 `ws://${config.uiServer.host}:${config.uiServer.port}`,
115 config.uiServer.protocol,
116 );
117 this.ws.onmessage = this.responseHandler.bind(this);
118 this.ws.onerror = (errorEvent) => {
119 console.error('WebSocket error: ', errorEvent);
120 };
121 this.ws.onclose = (closeEvent) => {
122 console.info('WebSocket closed: ', closeEvent);
123 };
124 }
125
126 private setResponseHandler(
127 id: string,
128 procedureName: ProcedureName,
129 resolve: (value: ResponsePayload | PromiseLike<ResponsePayload>) => void,
130 reject: (reason?: unknown) => void,
131 ): void {
132 this.responseHandlers.set(id, { procedureName, resolve, reject });
133 }
134
135 private getResponseHandler(id: string): ResponseHandler | undefined {
136 return this.responseHandlers.get(id);
137 }
138
139 private deleteResponseHandler(id: string): boolean {
140 return this.responseHandlers.delete(id);
141 }
142
143 private async sendRequest(
144 command: ProcedureName,
145 data: RequestPayload,
146 ): Promise<ResponsePayload> {
147 let uuid: string;
148 return new Promise<ResponsePayload>((resolve, reject) => {
149 uuid = crypto.randomUUID();
150 const msg = JSON.stringify([uuid, command, data]);
151
152 if (this.ws.readyState !== WebSocket.OPEN) {
153 this.openWS();
154 }
155 if (this.ws.readyState === WebSocket.OPEN) {
156 const sendTimeout = setTimeout(() => {
157 this.deleteResponseHandler(uuid);
158 return reject(new Error(`Send request '${command}' message timeout`));
159 }, 60 * 1000);
160 try {
161 this.ws.send(msg);
162 this.setResponseHandler(uuid, command, resolve, reject);
163 } catch (error) {
164 this.deleteResponseHandler(uuid);
165 reject(error);
166 } finally {
167 clearTimeout(sendTimeout);
168 }
169 } else {
170 throw new Error(`Send request '${command}' message: connection not opened`);
171 }
172 });
173 }
174
175 private responseHandler(messageEvent: MessageEvent<string>): void {
176 const response = JSON.parse(messageEvent.data) as ProtocolResponse;
177
178 if (Array.isArray(response) === false) {
179 throw new Error(`Response not an array: ${JSON.stringify(response, undefined, 2)}`);
180 }
181
182 const [uuid, responsePayload] = response;
183
184 if (this.responseHandlers.has(uuid) === true) {
185 const { procedureName, resolve, reject } = this.getResponseHandler(uuid)!;
186 switch (responsePayload.status) {
187 case ResponseStatus.SUCCESS:
188 resolve(responsePayload);
189 break;
190 case ResponseStatus.FAILURE:
191 reject(responsePayload);
192 break;
193 default:
194 console.error(
195 `Response status for procedure '${procedureName}' not supported: '${responsePayload.status}'`,
196 );
197 }
198 this.deleteResponseHandler(uuid);
199 } else {
200 throw new Error(`Not a response to a request: ${JSON.stringify(response, undefined, 2)}`);
201 }
202 }
203 }