1 import { useToast
} from
'vue-toast-notification'
6 type ChargingStationOptions
,
12 type UIServerConfigurationSection
15 import { randomUUID
, validateUUID
} from
'./Utils'
17 type ResponseHandler
= {
18 procedureName
: ProcedureName
19 resolve
: (value
: ResponsePayload
| PromiseLike
<ResponsePayload
>) => void
20 reject
: (reason
?: unknown
) => void
23 export class UIClient
{
24 private static instance
: UIClient
| null = null
26 private ws
?: WebSocket
27 private responseHandlers
: Map
<
28 `${string}-${string}-${string}-${string}-${string}`,
32 private constructor(private uiServerConfiguration
: UIServerConfigurationSection
) {
34 this.responseHandlers
= new Map
<
35 `${string}-${string}-${string}-${string}-${string}`,
40 public static getInstance(uiServerConfiguration
?: UIServerConfigurationSection
): UIClient
{
41 if (UIClient
.instance
=== null) {
42 if (uiServerConfiguration
== null) {
43 throw new Error('Cannot initialize UIClient if no configuration is provided')
45 UIClient
.instance
= new UIClient(uiServerConfiguration
)
47 return UIClient
.instance
50 public setConfiguration(uiServerConfiguration
: UIServerConfigurationSection
): void {
51 if (this.ws
?.readyState
=== WebSocket
.OPEN
) {
55 this.uiServerConfiguration
= uiServerConfiguration
59 public registerWSEventListener
<K
extends keyof WebSocketEventMap
>(
61 listener
: (event
: WebSocketEventMap
[K
]) => void,
62 options
?: boolean | AddEventListenerOptions
64 this.ws
?.addEventListener(event
, listener
, options
)
67 public unregisterWSEventListener
<K
extends keyof WebSocketEventMap
>(
69 listener
: (event
: WebSocketEventMap
[K
]) => void,
70 options
?: boolean | AddEventListenerOptions
72 this.ws
?.removeEventListener(event
, listener
, options
)
75 public async simulatorState(): Promise
<ResponsePayload
> {
76 return this.sendRequest(ProcedureName
.SIMULATOR_STATE
, {})
79 public async startSimulator(): Promise
<ResponsePayload
> {
80 return this.sendRequest(ProcedureName
.START_SIMULATOR
, {})
83 public async stopSimulator(): Promise
<ResponsePayload
> {
84 return this.sendRequest(ProcedureName
.STOP_SIMULATOR
, {})
87 public async listTemplates(): Promise
<ResponsePayload
> {
88 return this.sendRequest(ProcedureName
.LIST_TEMPLATES
, {})
91 public async listChargingStations(): Promise
<ResponsePayload
> {
92 return this.sendRequest(ProcedureName
.LIST_CHARGING_STATIONS
, {})
95 public async addChargingStations(
97 numberOfStations
: number,
98 options
?: ChargingStationOptions
99 ): Promise
<ResponsePayload
> {
100 return this.sendRequest(ProcedureName
.ADD_CHARGING_STATIONS
, {
107 public async deleteChargingStation(hashId
: string): Promise
<ResponsePayload
> {
108 return this.sendRequest(ProcedureName
.DELETE_CHARGING_STATIONS
, { hashIds
: [hashId
] })
111 public async setSupervisionUrl(hashId
: string, supervisionUrl
: string): Promise
<ResponsePayload
> {
112 return this.sendRequest(ProcedureName
.SET_SUPERVISION_URL
, {
118 public async startChargingStation(hashId
: string): Promise
<ResponsePayload
> {
119 return this.sendRequest(ProcedureName
.START_CHARGING_STATION
, { hashIds
: [hashId
] })
122 public async stopChargingStation(hashId
: string): Promise
<ResponsePayload
> {
123 return this.sendRequest(ProcedureName
.STOP_CHARGING_STATION
, { hashIds
: [hashId
] })
126 public async openConnection(hashId
: string): Promise
<ResponsePayload
> {
127 return this.sendRequest(ProcedureName
.OPEN_CONNECTION
, {
132 public async closeConnection(hashId
: string): Promise
<ResponsePayload
> {
133 return this.sendRequest(ProcedureName
.CLOSE_CONNECTION
, {
138 public async startTransaction(
141 idTag
: string | undefined
142 ): Promise
<ResponsePayload
> {
143 return this.sendRequest(ProcedureName
.START_TRANSACTION
, {
150 public async stopTransaction(
152 transactionId
: number | undefined
153 ): Promise
<ResponsePayload
> {
154 return this.sendRequest(ProcedureName
.STOP_TRANSACTION
, {
160 public async startAutomaticTransactionGenerator(
163 ): Promise
<ResponsePayload
> {
164 return this.sendRequest(ProcedureName
.START_AUTOMATIC_TRANSACTION_GENERATOR
, {
166 connectorIds
: [connectorId
]
170 public async stopAutomaticTransactionGenerator(
173 ): Promise
<ResponsePayload
> {
174 return this.sendRequest(ProcedureName
.STOP_AUTOMATIC_TRANSACTION_GENERATOR
, {
176 connectorIds
: [connectorId
]
180 private openWS(): void {
182 this.uiServerConfiguration
.authentication
?.enabled
=== true &&
183 this.uiServerConfiguration
.authentication
?.type === AuthenticationType
.PROTOCOL_BASIC_AUTH
185 `${this.uiServerConfiguration.protocol}${this.uiServerConfiguration.version}`,
186 `authorization.basic.${btoa(`${this.uiServerConfiguration.authentication.username}:${this.uiServerConfiguration.authentication.password}`).replace(/={1,2}$
/, '')}`
188 : `${this.uiServerConfiguration.protocol}${this.uiServerConfiguration.version}
`
189 this.ws = new WebSocket(
190 `${this.uiServerConfiguration.secure === true ? ApplicationProtocol.WSS : ApplicationProtocol.WS}
://${this.uiServerConfiguration.host}:${this.uiServerConfiguration.port}`,
193 this.ws
.onopen
= () => {
195 `WebSocket to UI server '${this.uiServerConfiguration.host}' successfully opened`
198 this.ws
.onmessage
= this.responseHandler
.bind(this)
199 this.ws
.onerror
= errorEvent
=> {
200 useToast().error(`Error in WebSocket to UI server '${this.uiServerConfiguration.host}'`)
202 `Error in WebSocket to UI server '${this.uiServerConfiguration.host}'`,
206 this.ws
.onclose
= () => {
207 useToast().info(`WebSocket to UI server closed`)
211 private async sendRequest(
212 procedureName
: ProcedureName
,
213 payload
: RequestPayload
214 ): Promise
<ResponsePayload
> {
215 return new Promise
<ResponsePayload
>((resolve
, reject
) => {
216 if (this.ws
?.readyState
=== WebSocket
.OPEN
) {
217 const uuid
= randomUUID()
218 const msg
= JSON
.stringify([uuid
, procedureName
, payload
])
219 const sendTimeout
= setTimeout(() => {
220 this.responseHandlers
.delete(uuid
)
221 return reject(new Error(`Send request '${procedureName}' message: connection timeout`))
225 this.responseHandlers
.set(uuid
, { procedureName
, resolve
, reject
})
227 this.responseHandlers
.delete(uuid
)
230 clearTimeout(sendTimeout
)
233 reject(new Error(`Send request '${procedureName}' message: connection closed`))
238 private responseHandler(messageEvent
: MessageEvent
<string>): void {
239 let response
: ProtocolResponse
241 response
= JSON
.parse(messageEvent
.data
)
243 useToast().error('Invalid response JSON format')
244 console
.error('Invalid response JSON format', error
)
248 if (!Array.isArray(response
)) {
249 useToast().error('Response not an array')
250 console
.error('Response not an array:', response
)
254 const [uuid
, responsePayload
] = response
256 if (!validateUUID(uuid
)) {
257 useToast().error('Response UUID field is invalid')
258 console
.error('Response UUID field is invalid:', response
)
262 if (this.responseHandlers
.has(uuid
)) {
263 const { procedureName
, resolve
, reject
} = this.responseHandlers
.get(uuid
)!
264 switch (responsePayload
.status) {
265 case ResponseStatus
.SUCCESS
:
266 resolve(responsePayload
)
268 case ResponseStatus
.FAILURE
:
269 reject(responsePayload
)
274 `Response status for procedure '${procedureName}' not supported: '${responsePayload.status}'`
278 this.responseHandlers
.delete(uuid
)
280 throw new Error(`Not a response to a request: ${JSON.stringify(response, undefined, 2)}`)