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