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