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 UIClient
.instance
= new UIClient(uiServerConfiguration
)
36 return UIClient
.instance
39 public setConfiguration(uiServerConfiguration
: UIServerConfigurationSection
): void {
40 if (this.ws
?.readyState
=== WebSocket
.OPEN
) {
44 this.uiServerConfiguration
= uiServerConfiguration
48 public registerWSEventListener
<K
extends keyof WebSocketEventMap
>(
50 listener
: (event
: WebSocketEventMap
[K
]) => void,
51 options
?: boolean | AddEventListenerOptions
53 this.ws
?.addEventListener(event
, listener
, options
)
56 public async startSimulator(): Promise
<ResponsePayload
> {
57 return this.sendRequest(ProcedureName
.START_SIMULATOR
, {})
60 public async stopSimulator(): Promise
<ResponsePayload
> {
61 return this.sendRequest(ProcedureName
.STOP_SIMULATOR
, {})
64 public async listTemplates(): Promise
<ResponsePayload
> {
65 return this.sendRequest(ProcedureName
.LIST_TEMPLATES
, {})
68 public async listChargingStations(): Promise
<ResponsePayload
> {
69 return this.sendRequest(ProcedureName
.LIST_CHARGING_STATIONS
, {})
72 public async addChargingStations(
74 numberOfStations
: number,
75 options
?: ChargingStationOptions
76 ): Promise
<ResponsePayload
> {
77 return this.sendRequest(ProcedureName
.ADD_CHARGING_STATIONS
, {
84 public async deleteChargingStation(hashId
: string): Promise
<ResponsePayload
> {
85 return this.sendRequest(ProcedureName
.DELETE_CHARGING_STATIONS
, { hashIds
: [hashId
] })
88 public async setSupervisionUrl(hashId
: string, supervisionUrl
: string): Promise
<ResponsePayload
> {
89 return this.sendRequest(ProcedureName
.SET_SUPERVISION_URL
, {
95 public async startChargingStation(hashId
: string): Promise
<ResponsePayload
> {
96 return this.sendRequest(ProcedureName
.START_CHARGING_STATION
, { hashIds
: [hashId
] })
99 public async stopChargingStation(hashId
: string): Promise
<ResponsePayload
> {
100 return this.sendRequest(ProcedureName
.STOP_CHARGING_STATION
, { hashIds
: [hashId
] })
103 public async openConnection(hashId
: string): Promise
<ResponsePayload
> {
104 return this.sendRequest(ProcedureName
.OPEN_CONNECTION
, {
109 public async closeConnection(hashId
: string): Promise
<ResponsePayload
> {
110 return this.sendRequest(ProcedureName
.CLOSE_CONNECTION
, {
115 public async startTransaction(
118 idTag
: string | undefined
119 ): Promise
<ResponsePayload
> {
120 return this.sendRequest(ProcedureName
.START_TRANSACTION
, {
127 public async stopTransaction(
129 transactionId
: number | undefined
130 ): Promise
<ResponsePayload
> {
131 return this.sendRequest(ProcedureName
.STOP_TRANSACTION
, {
137 public async startAutomaticTransactionGenerator(
140 ): Promise
<ResponsePayload
> {
141 return this.sendRequest(ProcedureName
.START_AUTOMATIC_TRANSACTION_GENERATOR
, {
143 connectorIds
: [connectorId
]
147 public async stopAutomaticTransactionGenerator(
150 ): Promise
<ResponsePayload
> {
151 return this.sendRequest(ProcedureName
.STOP_AUTOMATIC_TRANSACTION_GENERATOR
, {
153 connectorIds
: [connectorId
]
157 private openWS(): void {
159 this.uiServerConfiguration
.authentication
?.enabled
=== true &&
160 this.uiServerConfiguration
.authentication
?.type === AuthenticationType
.PROTOCOL_BASIC_AUTH
162 `${this.uiServerConfiguration.protocol}${this.uiServerConfiguration.version}`,
163 `authorization.basic.${btoa(`${this.uiServerConfiguration.authentication.username}:${this.uiServerConfiguration.authentication.password}`).replace(/={1,2}$
/, '')}`
165 : `${this.uiServerConfiguration.protocol}${this.uiServerConfiguration.version}
`
166 this.ws = new WebSocket(
167 `${this.uiServerConfiguration.secure === true ? ApplicationProtocol.WSS : ApplicationProtocol.WS}
://${this.uiServerConfiguration.host}:${this.uiServerConfiguration.port}`,
170 this.ws
.onopen
= () => {
172 `WebSocket to UI server '${this.uiServerConfiguration.host}' successfully opened`
175 this.ws
.onmessage
= this.responseHandler
.bind(this)
176 this.ws
.onerror
= errorEvent
=> {
177 useToast().error(`Error in WebSocket to UI server '${this.uiServerConfiguration.host}'`)
179 `Error in WebSocket to UI server '${this.uiServerConfiguration.host}'`,
183 this.ws
.onclose
= () => {
184 useToast().info(`WebSocket to UI server closed`)
188 private async sendRequest(
189 procedureName
: ProcedureName
,
190 payload
: RequestPayload
191 ): Promise
<ResponsePayload
> {
192 return new Promise
<ResponsePayload
>((resolve
, reject
) => {
193 if (this.ws
?.readyState
=== WebSocket
.OPEN
) {
194 const uuid
= randomUUID()
195 const msg
= JSON
.stringify([uuid
, procedureName
, payload
])
196 const sendTimeout
= setTimeout(() => {
197 this.responseHandlers
.delete(uuid
)
198 return reject(new Error(`Send request '${procedureName}' message: connection timeout`))
202 this.responseHandlers
.set(uuid
, { procedureName
, resolve
, reject
})
204 this.responseHandlers
.delete(uuid
)
207 clearTimeout(sendTimeout
)
210 reject(new Error(`Send request '${procedureName}' message: connection closed`))
215 private responseHandler(messageEvent
: MessageEvent
<string>): void {
216 const response
= JSON
.parse(messageEvent
.data
) as ProtocolResponse
218 if (Array.isArray(response
) === false) {
219 throw new Error(`Response not an array: ${JSON.stringify(response, undefined, 2)}`)
222 const [uuid
, responsePayload
] = response
224 if (this.responseHandlers
.has(uuid
) === true) {
225 const { procedureName
, resolve
, reject
} = this.responseHandlers
.get(uuid
)!
226 switch (responsePayload
.status) {
227 case ResponseStatus
.SUCCESS
:
228 resolve(responsePayload
)
230 case ResponseStatus
.FAILURE
:
231 reject(responsePayload
)
236 `Response status for procedure '${procedureName}' not supported: '${responsePayload.status}'`
240 this.responseHandlers
.delete(uuid
)
242 throw new Error(`Not a response to a request: ${JSON.stringify(response, undefined, 2)}`)