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