1 import { useToast
} from
'vue-toast-notification'
2 import { randomUUID
} from
'./Utils'
6 type ChargingStationOptions
,
12 type UIServerConfigurationSection
15 type ResponseHandler
= {
16 procedureName
: ProcedureName
17 resolve
: (value
: ResponsePayload
| PromiseLike
<ResponsePayload
>) => void
18 reject
: (reason
?: unknown
) => void
21 export class UIClient
{
22 private static instance
: UIClient
| null = null
24 private ws
?: WebSocket
25 private responseHandlers
: Map
<string, ResponseHandler
>
27 private constructor(private uiServerConfiguration
: UIServerConfigurationSection
) {
29 this.responseHandlers
= new Map
<string, ResponseHandler
>()
32 public static getInstance(uiServerConfiguration
?: UIServerConfigurationSection
): UIClient
{
33 if (UIClient
.instance
=== null) {
34 if (uiServerConfiguration
== null) {
35 throw new Error('Cannot initialize UIClient if no configuration is provided')
37 UIClient
.instance
= new UIClient(uiServerConfiguration
)
39 return UIClient
.instance
42 public setConfiguration(uiServerConfiguration
: UIServerConfigurationSection
): void {
43 if (this.ws
?.readyState
=== WebSocket
.OPEN
) {
47 this.uiServerConfiguration
= uiServerConfiguration
51 public registerWSEventListener
<K
extends keyof WebSocketEventMap
>(
53 listener
: (event
: WebSocketEventMap
[K
]) => void,
54 options
?: boolean | AddEventListenerOptions
56 this.ws
?.addEventListener(event
, listener
, options
)
59 public unregisterWSEventListener
<K
extends keyof WebSocketEventMap
>(
61 listener
: (event
: WebSocketEventMap
[K
]) => void,
62 options
?: boolean | AddEventListenerOptions
64 this.ws
?.removeEventListener(event
, listener
, options
)
67 public async simulatorState(): Promise
<ResponsePayload
> {
68 return this.sendRequest(ProcedureName
.SIMULATOR_STATE
, {})
71 public async startSimulator(): Promise
<ResponsePayload
> {
72 return this.sendRequest(ProcedureName
.START_SIMULATOR
, {})
75 public async stopSimulator(): Promise
<ResponsePayload
> {
76 return this.sendRequest(ProcedureName
.STOP_SIMULATOR
, {})
79 public async listTemplates(): Promise
<ResponsePayload
> {
80 return this.sendRequest(ProcedureName
.LIST_TEMPLATES
, {})
83 public async listChargingStations(): Promise
<ResponsePayload
> {
84 return this.sendRequest(ProcedureName
.LIST_CHARGING_STATIONS
, {})
87 public async addChargingStations(
89 numberOfStations
: number,
90 options
?: ChargingStationOptions
91 ): Promise
<ResponsePayload
> {
92 return this.sendRequest(ProcedureName
.ADD_CHARGING_STATIONS
, {
99 public async deleteChargingStation(hashId
: string): Promise
<ResponsePayload
> {
100 return this.sendRequest(ProcedureName
.DELETE_CHARGING_STATIONS
, { hashIds
: [hashId
] })
103 public async setSupervisionUrl(hashId
: string, supervisionUrl
: string): Promise
<ResponsePayload
> {
104 return this.sendRequest(ProcedureName
.SET_SUPERVISION_URL
, {
110 public async startChargingStation(hashId
: string): Promise
<ResponsePayload
> {
111 return this.sendRequest(ProcedureName
.START_CHARGING_STATION
, { hashIds
: [hashId
] })
114 public async stopChargingStation(hashId
: string): Promise
<ResponsePayload
> {
115 return this.sendRequest(ProcedureName
.STOP_CHARGING_STATION
, { hashIds
: [hashId
] })
118 public async openConnection(hashId
: string): Promise
<ResponsePayload
> {
119 return this.sendRequest(ProcedureName
.OPEN_CONNECTION
, {
124 public async closeConnection(hashId
: string): Promise
<ResponsePayload
> {
125 return this.sendRequest(ProcedureName
.CLOSE_CONNECTION
, {
130 public async startTransaction(
133 idTag
: string | undefined
134 ): Promise
<ResponsePayload
> {
135 return this.sendRequest(ProcedureName
.START_TRANSACTION
, {
142 public async stopTransaction(
144 transactionId
: number | undefined
145 ): Promise
<ResponsePayload
> {
146 return this.sendRequest(ProcedureName
.STOP_TRANSACTION
, {
152 public async startAutomaticTransactionGenerator(
155 ): Promise
<ResponsePayload
> {
156 return this.sendRequest(ProcedureName
.START_AUTOMATIC_TRANSACTION_GENERATOR
, {
158 connectorIds
: [connectorId
]
162 public async stopAutomaticTransactionGenerator(
165 ): Promise
<ResponsePayload
> {
166 return this.sendRequest(ProcedureName
.STOP_AUTOMATIC_TRANSACTION_GENERATOR
, {
168 connectorIds
: [connectorId
]
172 private openWS(): void {
174 this.uiServerConfiguration
.authentication
?.enabled
=== true &&
175 this.uiServerConfiguration
.authentication
?.type === AuthenticationType
.PROTOCOL_BASIC_AUTH
177 `${this.uiServerConfiguration.protocol}${this.uiServerConfiguration.version}`,
178 `authorization.basic.${btoa(`${this.uiServerConfiguration.authentication.username}:${this.uiServerConfiguration.authentication.password}`).replace(/={1,2}$
/, '')}`
180 : `${this.uiServerConfiguration.protocol}${this.uiServerConfiguration.version}
`
181 this.ws = new WebSocket(
182 `${this.uiServerConfiguration.secure === true ? ApplicationProtocol.WSS : ApplicationProtocol.WS}
://${this.uiServerConfiguration.host}:${this.uiServerConfiguration.port}`,
185 this.ws
.onopen
= () => {
187 `WebSocket to UI server '${this.uiServerConfiguration.host}' successfully opened`
190 this.ws
.onmessage
= this.responseHandler
.bind(this)
191 this.ws
.onerror
= errorEvent
=> {
192 useToast().error(`Error in WebSocket to UI server '${this.uiServerConfiguration.host}'`)
194 `Error in WebSocket to UI server '${this.uiServerConfiguration.host}'`,
198 this.ws
.onclose
= () => {
199 useToast().info(`WebSocket to UI server closed`)
203 private async sendRequest(
204 procedureName
: ProcedureName
,
205 payload
: RequestPayload
206 ): Promise
<ResponsePayload
> {
207 return new Promise
<ResponsePayload
>((resolve
, reject
) => {
208 if (this.ws
?.readyState
=== WebSocket
.OPEN
) {
209 const uuid
= randomUUID()
210 const msg
= JSON
.stringify([uuid
, procedureName
, payload
])
211 const sendTimeout
= setTimeout(() => {
212 this.responseHandlers
.delete(uuid
)
213 return reject(new Error(`Send request '${procedureName}' message: connection timeout`))
217 this.responseHandlers
.set(uuid
, { procedureName
, resolve
, reject
})
219 this.responseHandlers
.delete(uuid
)
222 clearTimeout(sendTimeout
)
225 reject(new Error(`Send request '${procedureName}' message: connection closed`))
230 private responseHandler(messageEvent
: MessageEvent
<string>): void {
231 const response
= JSON
.parse(messageEvent
.data
) as ProtocolResponse
233 if (Array.isArray(response
) === false) {
234 throw new Error(`Response not an array: ${JSON.stringify(response, undefined, 2)}`)
237 const [uuid
, responsePayload
] = response
239 if (this.responseHandlers
.has(uuid
) === true) {
240 const { procedureName
, resolve
, reject
} = this.responseHandlers
.get(uuid
)!
241 switch (responsePayload
.status) {
242 case ResponseStatus
.SUCCESS
:
243 resolve(responsePayload
)
245 case ResponseStatus
.FAILURE
:
246 reject(responsePayload
)
251 `Response status for procedure '${procedureName}' not supported: '${responsePayload.status}'`
255 this.responseHandlers
.delete(uuid
)
257 throw new Error(`Not a response to a request: ${JSON.stringify(response, undefined, 2)}`)