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