1 import { useToast
} from
'vue-toast-notification'
5 type ChargingStationOptions
,
11 type UIServerConfigurationSection
14 type ResponseHandler
= {
15 procedureName
: ProcedureName
16 resolve
: (value
: ResponsePayload
| PromiseLike
<ResponsePayload
>) => void
17 reject
: (reason
?: unknown
) => void
20 export class UIClient
{
21 private static instance
: UIClient
| null = null
23 private ws
!: WebSocket
24 private responseHandlers
: Map
<string, ResponseHandler
>
26 private constructor(private uiServerConfiguration
: UIServerConfigurationSection
) {
28 this.responseHandlers
= new Map
<string, ResponseHandler
>()
31 public static getInstance(uiServerConfiguration
: UIServerConfigurationSection
): UIClient
{
32 if (UIClient
.instance
=== null) {
33 UIClient
.instance
= new UIClient(uiServerConfiguration
)
35 return UIClient
.instance
38 public setConfiguration(uiServerConfiguration
: UIServerConfigurationSection
): void {
40 this.uiServerConfiguration
= uiServerConfiguration
44 public registerWSEventListener
<K
extends keyof WebSocketEventMap
>(
46 listener
: (event
: WebSocketEventMap
[K
]) => void,
47 options
?: boolean | AddEventListenerOptions
49 this.ws
.addEventListener(event
, listener
, options
)
52 public async startSimulator(): Promise
<ResponsePayload
> {
53 return this.sendRequest(ProcedureName
.START_SIMULATOR
, {})
56 public async stopSimulator(): Promise
<ResponsePayload
> {
57 return this.sendRequest(ProcedureName
.STOP_SIMULATOR
, {})
60 public async listTemplates(): Promise
<ResponsePayload
> {
61 return this.sendRequest(ProcedureName
.LIST_TEMPLATES
, {})
64 public async listChargingStations(): Promise
<ResponsePayload
> {
65 return this.sendRequest(ProcedureName
.LIST_CHARGING_STATIONS
, {})
68 public async addChargingStations(
70 numberOfStations
: number,
71 options
?: ChargingStationOptions
72 ): Promise
<ResponsePayload
> {
73 return this.sendRequest(ProcedureName
.ADD_CHARGING_STATIONS
, {
80 public async deleteChargingStation(hashId
: string): Promise
<ResponsePayload
> {
81 return this.sendRequest(ProcedureName
.DELETE_CHARGING_STATIONS
, { hashIds
: [hashId
] })
84 public async setSupervisionUrl(hashId
: string, supervisionUrl
: string): Promise
<ResponsePayload
> {
85 return this.sendRequest(ProcedureName
.SET_SUPERVISION_URL
, {
91 public async startChargingStation(hashId
: string): Promise
<ResponsePayload
> {
92 return this.sendRequest(ProcedureName
.START_CHARGING_STATION
, { hashIds
: [hashId
] })
95 public async stopChargingStation(hashId
: string): Promise
<ResponsePayload
> {
96 return this.sendRequest(ProcedureName
.STOP_CHARGING_STATION
, { hashIds
: [hashId
] })
99 public async openConnection(hashId
: string): Promise
<ResponsePayload
> {
100 return this.sendRequest(ProcedureName
.OPEN_CONNECTION
, {
105 public async closeConnection(hashId
: string): Promise
<ResponsePayload
> {
106 return this.sendRequest(ProcedureName
.CLOSE_CONNECTION
, {
111 public async startTransaction(
114 idTag
: string | undefined
115 ): Promise
<ResponsePayload
> {
116 return this.sendRequest(ProcedureName
.START_TRANSACTION
, {
123 public async stopTransaction(
125 transactionId
: number | undefined
126 ): Promise
<ResponsePayload
> {
127 return this.sendRequest(ProcedureName
.STOP_TRANSACTION
, {
133 public async startAutomaticTransactionGenerator(
136 ): Promise
<ResponsePayload
> {
137 return this.sendRequest(ProcedureName
.START_AUTOMATIC_TRANSACTION_GENERATOR
, {
139 connectorIds
: [connectorId
]
143 public async stopAutomaticTransactionGenerator(
146 ): Promise
<ResponsePayload
> {
147 return this.sendRequest(ProcedureName
.STOP_AUTOMATIC_TRANSACTION_GENERATOR
, {
149 connectorIds
: [connectorId
]
153 private openWS(): void {
155 this.uiServerConfiguration
.authentication
?.enabled
=== true &&
156 this.uiServerConfiguration
.authentication
?.type === AuthenticationType
.PROTOCOL_BASIC_AUTH
158 `${this.uiServerConfiguration.protocol}${this.uiServerConfiguration.version}`,
159 `authorization.basic.${btoa(`${this.uiServerConfiguration.authentication.username}:${this.uiServerConfiguration.authentication.password}`).replace(/={1,2}$
/, '')}`
161 : `${this.uiServerConfiguration.protocol}${this.uiServerConfiguration.version}
`
162 this.ws = new WebSocket(
163 `${this.uiServerConfiguration.secure === true ? ApplicationProtocol.WSS : ApplicationProtocol.WS}
://${this.uiServerConfiguration.host}:${this.uiServerConfiguration.port}`,
166 this.ws
.onopen
= () => {
168 `WebSocket to UI server '${this.uiServerConfiguration.host}' successfully opened`
171 this.ws
.onmessage
= this.responseHandler
.bind(this)
172 this.ws
.onerror
= errorEvent
=> {
173 useToast().error(`Error in WebSocket to UI server '${this.uiServerConfiguration.host}'`)
175 `Error in WebSocket to UI server '${this.uiServerConfiguration.host}'`,
179 this.ws
.onclose
= () => {
180 useToast().info(`WebSocket to UI server closed`)
184 private async sendRequest(
185 procedureName
: ProcedureName
,
186 payload
: RequestPayload
187 ): Promise
<ResponsePayload
> {
188 return new Promise
<ResponsePayload
>((resolve
, reject
) => {
189 if (this.ws
.readyState
=== WebSocket
.OPEN
) {
190 const uuid
= crypto
.randomUUID()
191 const msg
= JSON
.stringify([uuid
, procedureName
, payload
])
192 const sendTimeout
= setTimeout(() => {
193 this.responseHandlers
.delete(uuid
)
194 return reject(new Error(`Send request '${procedureName}' message: connection timeout`))
198 this.responseHandlers
.set(uuid
, { procedureName
, resolve
, reject
})
200 this.responseHandlers
.delete(uuid
)
203 clearTimeout(sendTimeout
)
206 reject(new Error(`Send request '${procedureName}' message: connection closed`))
211 private responseHandler(messageEvent
: MessageEvent
<string>): void {
212 const response
= JSON
.parse(messageEvent
.data
) as ProtocolResponse
214 if (Array.isArray(response
) === false) {
215 throw new Error(`Response not an array: ${JSON.stringify(response, undefined, 2)}`)
218 const [uuid
, responsePayload
] = response
220 if (this.responseHandlers
.has(uuid
) === true) {
221 const { procedureName
, resolve
, reject
} = this.responseHandlers
.get(uuid
)!
222 switch (responsePayload
.status) {
223 case ResponseStatus
.SUCCESS
:
224 resolve(responsePayload
)
226 case ResponseStatus
.FAILURE
:
227 reject(responsePayload
)
232 `Response status for procedure '${procedureName}' not supported: '${responsePayload.status}'`
236 this.responseHandlers
.delete(uuid
)
238 throw new Error(`Not a response to a request: ${JSON.stringify(response, undefined, 2)}`)