feat(ui): add right action bar and use it to start transaction
[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 registerWSonOpenListener(listener: (event: Event) => void) {
37 this.ws.addEventListener('open', listener)
38 }
39
40 public async startSimulator(): Promise<ResponsePayload> {
41 return this.sendRequest(ProcedureName.START_SIMULATOR, {})
42 }
43
44 public async stopSimulator(): Promise<ResponsePayload> {
45 return this.sendRequest(ProcedureName.STOP_SIMULATOR, {})
46 }
47
48 public async listTemplates(): Promise<ResponsePayload> {
49 return this.sendRequest(ProcedureName.LIST_TEMPLATES, {})
50 }
51
52 public async listChargingStations(): Promise<ResponsePayload> {
53 return this.sendRequest(ProcedureName.LIST_CHARGING_STATIONS, {})
54 }
55
56 public async addChargingStations(
57 template: string,
58 numberOfStations: number
59 ): Promise<ResponsePayload> {
60 return this.sendRequest(ProcedureName.ADD_CHARGING_STATIONS, { template, numberOfStations })
61 }
62
63 public async deleteChargingStation(hashId: string): Promise<ResponsePayload> {
64 return this.sendRequest(ProcedureName.DELETE_CHARGING_STATIONS, { hashIds: [hashId] })
65 }
66
67 public async startChargingStation(hashId: string): Promise<ResponsePayload> {
68 return this.sendRequest(ProcedureName.START_CHARGING_STATION, { hashIds: [hashId] })
69 }
70
71 public async stopChargingStation(hashId: string): Promise<ResponsePayload> {
72 return this.sendRequest(ProcedureName.STOP_CHARGING_STATION, { hashIds: [hashId] })
73 }
74
75 public async openConnection(hashId: string): Promise<ResponsePayload> {
76 return this.sendRequest(ProcedureName.OPEN_CONNECTION, {
77 hashIds: [hashId]
78 })
79 }
80
81 public async closeConnection(hashId: string): Promise<ResponsePayload> {
82 return this.sendRequest(ProcedureName.CLOSE_CONNECTION, {
83 hashIds: [hashId]
84 })
85 }
86
87 public async startTransaction(
88 hashId: string,
89 connectorId: number,
90 idTag: string | undefined
91 ): Promise<ResponsePayload> {
92 return this.sendRequest(ProcedureName.START_TRANSACTION, {
93 hashIds: [hashId],
94 connectorId,
95 idTag
96 })
97 }
98
99 public async stopTransaction(
100 hashId: string,
101 transactionId: number | undefined
102 ): Promise<ResponsePayload> {
103 return this.sendRequest(ProcedureName.STOP_TRANSACTION, {
104 hashIds: [hashId],
105 transactionId
106 })
107 }
108
109 public async startAutomaticTransactionGenerator(
110 hashId: string,
111 connectorId: number
112 ): Promise<ResponsePayload> {
113 return this.sendRequest(ProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR, {
114 hashIds: [hashId],
115 connectorIds: [connectorId]
116 })
117 }
118
119 public async stopAutomaticTransactionGenerator(
120 hashId: string,
121 connectorId: number
122 ): Promise<ResponsePayload> {
123 return this.sendRequest(ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR, {
124 hashIds: [hashId],
125 connectorIds: [connectorId]
126 })
127 }
128
129 private openWS(): void {
130 const protocols =
131 this.configuration.uiServer.authentication?.enabled === true &&
132 this.configuration.uiServer.authentication?.type === AuthenticationType.PROTOCOL_BASIC_AUTH
133 ? [
134 `${this.configuration.uiServer.protocol}${this.configuration.uiServer.version}`,
135 `authorization.basic.${btoa(`${this.configuration.uiServer.authentication.username}:${this.configuration.uiServer.authentication.password}`).replace(/={1,2}$/, '')}`
136 ]
137 : `${this.configuration.uiServer.protocol}${this.configuration.uiServer.version}`
138 this.ws = new WebSocket(
139 `${this.configuration.uiServer.secure === true ? ApplicationProtocol.WSS : ApplicationProtocol.WS}://${this.configuration.uiServer.host}:${this.configuration.uiServer.port}`,
140 protocols
141 )
142 this.ws.onopen = openEvent => {
143 console.info('WebSocket opened', openEvent)
144 }
145 this.ws.onmessage = this.responseHandler.bind(this)
146 this.ws.onerror = errorEvent => {
147 console.error('WebSocket error: ', errorEvent)
148 }
149 this.ws.onclose = closeEvent => {
150 console.info('WebSocket closed: ', closeEvent)
151 }
152 }
153
154 private async sendRequest(
155 procedureName: ProcedureName,
156 payload: RequestPayload
157 ): Promise<ResponsePayload> {
158 return new Promise<ResponsePayload>((resolve, reject) => {
159 if (this.ws.readyState === WebSocket.OPEN) {
160 const uuid = crypto.randomUUID()
161 const msg = JSON.stringify([uuid, procedureName, payload])
162 const sendTimeout = setTimeout(() => {
163 this.responseHandlers.delete(uuid)
164 return reject(new Error(`Send request '${procedureName}' message: connection timeout`))
165 }, 60000)
166 try {
167 this.ws.send(msg)
168 this.responseHandlers.set(uuid, { procedureName, resolve, reject })
169 } catch (error) {
170 this.responseHandlers.delete(uuid)
171 reject(error)
172 } finally {
173 clearTimeout(sendTimeout)
174 }
175 } else {
176 reject(new Error(`Send request '${procedureName}' message: connection closed`))
177 }
178 })
179 }
180
181 private responseHandler(messageEvent: MessageEvent<string>): void {
182 const response = JSON.parse(messageEvent.data) as ProtocolResponse
183
184 if (Array.isArray(response) === false) {
185 throw new Error(`Response not an array: ${JSON.stringify(response, undefined, 2)}`)
186 }
187
188 const [uuid, responsePayload] = response
189
190 if (this.responseHandlers.has(uuid) === true) {
191 const { procedureName, resolve, reject } = this.responseHandlers.get(uuid)!
192 switch (responsePayload.status) {
193 case ResponseStatus.SUCCESS:
194 resolve(responsePayload)
195 break
196 case ResponseStatus.FAILURE:
197 reject(responsePayload)
198 break
199 default:
200 console.error(
201 `Response status for procedure '${procedureName}' not supported: '${responsePayload.status}'`
202 )
203 }
204 this.responseHandlers.delete(uuid)
205 } else {
206 throw new Error(`Not a response to a request: ${JSON.stringify(response, undefined, 2)}`)
207 }
208 }
209 }