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