refactor(ui): use JSON format as runtime configuration
[e-mobility-charging-stations-simulator.git] / ui / web / src / composables / UIClient.ts
1 import {
2 ApplicationProtocol,
3 type ConfigurationData,
4 ProcedureName,
5 type ProtocolResponse,
6 type RequestPayload,
7 type ResponsePayload,
8 ResponseStatus
9 } from '@/types'
10
11 type ResponseHandler = {
12 procedureName: ProcedureName
13 resolve: (value: ResponsePayload | PromiseLike<ResponsePayload>) => void
14 reject: (reason?: unknown) => void
15 }
16
17 export class UIClient {
18 private static instance: UIClient | null = null
19
20 private ws!: WebSocket
21 private responseHandlers: Map<string, ResponseHandler>
22
23 private constructor(private configuration: ConfigurationData) {
24 this.openWS()
25 this.responseHandlers = new Map<string, ResponseHandler>()
26 }
27
28 public static getInstance(configuration: ConfigurationData) {
29 if (UIClient.instance === null) {
30 UIClient.instance = new UIClient(configuration)
31 }
32 return UIClient.instance
33 }
34
35 public registerWSonOpenListener(listener: (event: Event) => void) {
36 this.ws.addEventListener('open', listener)
37 }
38
39 public async startSimulator(): Promise<ResponsePayload> {
40 return this.sendRequest(ProcedureName.START_SIMULATOR, {})
41 }
42
43 public async stopSimulator(): Promise<ResponsePayload> {
44 return this.sendRequest(ProcedureName.STOP_SIMULATOR, {})
45 }
46
47 public async listChargingStations(): Promise<ResponsePayload> {
48 return this.sendRequest(ProcedureName.LIST_CHARGING_STATIONS, {})
49 }
50
51 public async startChargingStation(hashId: string): Promise<ResponsePayload> {
52 return this.sendRequest(ProcedureName.START_CHARGING_STATION, { hashIds: [hashId] })
53 }
54
55 public async stopChargingStation(hashId: string): Promise<ResponsePayload> {
56 return this.sendRequest(ProcedureName.STOP_CHARGING_STATION, { hashIds: [hashId] })
57 }
58
59 public async openConnection(hashId: string): Promise<ResponsePayload> {
60 return this.sendRequest(ProcedureName.OPEN_CONNECTION, {
61 hashIds: [hashId]
62 })
63 }
64
65 public async closeConnection(hashId: string): Promise<ResponsePayload> {
66 return this.sendRequest(ProcedureName.CLOSE_CONNECTION, {
67 hashIds: [hashId]
68 })
69 }
70
71 public async startTransaction(
72 hashId: string,
73 connectorId: number,
74 idTag: string | undefined
75 ): Promise<ResponsePayload> {
76 return this.sendRequest(ProcedureName.START_TRANSACTION, {
77 hashIds: [hashId],
78 connectorId,
79 idTag
80 })
81 }
82
83 public async stopTransaction(
84 hashId: string,
85 transactionId: number | undefined
86 ): Promise<ResponsePayload> {
87 return this.sendRequest(ProcedureName.STOP_TRANSACTION, {
88 hashIds: [hashId],
89 transactionId
90 })
91 }
92
93 public async startAutomaticTransactionGenerator(
94 hashId: string,
95 connectorId: number
96 ): Promise<ResponsePayload> {
97 return this.sendRequest(ProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR, {
98 hashIds: [hashId],
99 connectorIds: [connectorId]
100 })
101 }
102
103 public async stopAutomaticTransactionGenerator(
104 hashId: string,
105 connectorId: number
106 ): Promise<ResponsePayload> {
107 return this.sendRequest(ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR, {
108 hashIds: [hashId],
109 connectorIds: [connectorId]
110 })
111 }
112
113 private openWS(): void {
114 this.ws = new WebSocket(
115 `${this.configuration.uiServer.secure === true ? ApplicationProtocol.WSS : ApplicationProtocol.WS}://${this.configuration.uiServer.host}:${this.configuration.uiServer.port}`,
116 `${this.configuration.uiServer.protocol}${this.configuration.uiServer.version}`
117 )
118 this.ws.onmessage = this.responseHandler.bind(this)
119 this.ws.onerror = errorEvent => {
120 console.error('WebSocket error: ', errorEvent)
121 }
122 this.ws.onclose = closeEvent => {
123 console.info('WebSocket closed: ', closeEvent)
124 }
125 }
126
127 private async sendRequest(
128 procedureName: ProcedureName,
129 payload: RequestPayload
130 ): Promise<ResponsePayload> {
131 return new Promise<ResponsePayload>((resolve, reject) => {
132 if (this.ws.readyState !== WebSocket.OPEN) {
133 this.openWS()
134 }
135 if (this.ws.readyState === WebSocket.OPEN) {
136 const uuid = crypto.randomUUID()
137 const msg = JSON.stringify([uuid, procedureName, payload])
138 const sendTimeout = setTimeout(() => {
139 this.responseHandlers.delete(uuid)
140 return reject(new Error(`Send request '${procedureName}' message timeout`))
141 }, 60000)
142 try {
143 this.ws.send(msg)
144 this.responseHandlers.set(uuid, { procedureName, resolve, reject })
145 } catch (error) {
146 this.responseHandlers.delete(uuid)
147 reject(error)
148 } finally {
149 clearTimeout(sendTimeout)
150 }
151 } else {
152 throw new Error(`Send request '${procedureName}' message: connection not opened`)
153 }
154 })
155 }
156
157 private responseHandler(messageEvent: MessageEvent<string>): void {
158 const response = JSON.parse(messageEvent.data) as ProtocolResponse
159
160 if (Array.isArray(response) === false) {
161 throw new Error(`Response not an array: ${JSON.stringify(response, undefined, 2)}`)
162 }
163
164 const [uuid, responsePayload] = response
165
166 if (this.responseHandlers.has(uuid) === true) {
167 const { procedureName, resolve, reject } = this.responseHandlers.get(uuid)!
168 switch (responsePayload.status) {
169 case ResponseStatus.SUCCESS:
170 resolve(responsePayload)
171 break
172 case ResponseStatus.FAILURE:
173 reject(responsePayload)
174 break
175 default:
176 console.error(
177 `Response status for procedure '${procedureName}' not supported: '${responsePayload.status}'`
178 )
179 }
180 this.responseHandlers.delete(uuid)
181 } else {
182 throw new Error(`Not a response to a request: ${JSON.stringify(response, undefined, 2)}`)
183 }
184 }
185 }