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 simulatorState(): Promise
<ResponsePayload
> {
57 return this.sendRequest(ProcedureName
.SIMULATOR_STATE
, {})
60 public async startSimulator(): Promise
<ResponsePayload
> {
61 return this.sendRequest(ProcedureName
.START_SIMULATOR
, {})
64 public async stopSimulator(): Promise
<ResponsePayload
> {
65 return this.sendRequest(ProcedureName
.STOP_SIMULATOR
, {})
68 public async listTemplates(): Promise
<ResponsePayload
> {
69 return this.sendRequest(ProcedureName
.LIST_TEMPLATES
, {})
72 public async listChargingStations(): Promise
<ResponsePayload
> {
73 return this.sendRequest(ProcedureName
.LIST_CHARGING_STATIONS
, {})
76 public async addChargingStations(
78 numberOfStations
: number,
79 options
?: ChargingStationOptions
80 ): Promise
<ResponsePayload
> {
81 return this.sendRequest(ProcedureName
.ADD_CHARGING_STATIONS
, {
88 public async deleteChargingStation(hashId
: string): Promise
<ResponsePayload
> {
89 return this.sendRequest(ProcedureName
.DELETE_CHARGING_STATIONS
, { hashIds
: [hashId
] })
92 public async setSupervisionUrl(hashId
: string, supervisionUrl
: string): Promise
<ResponsePayload
> {
93 return this.sendRequest(ProcedureName
.SET_SUPERVISION_URL
, {
99 public async startChargingStation(hashId
: string): Promise
<ResponsePayload
> {
100 return this.sendRequest(ProcedureName
.START_CHARGING_STATION
, { hashIds
: [hashId
] })
103 public async stopChargingStation(hashId
: string): Promise
<ResponsePayload
> {
104 return this.sendRequest(ProcedureName
.STOP_CHARGING_STATION
, { hashIds
: [hashId
] })
107 public async openConnection(hashId
: string): Promise
<ResponsePayload
> {
108 return this.sendRequest(ProcedureName
.OPEN_CONNECTION
, {
113 public async closeConnection(hashId
: string): Promise
<ResponsePayload
> {
114 return this.sendRequest(ProcedureName
.CLOSE_CONNECTION
, {
119 public async startTransaction(
122 idTag
: string | undefined
123 ): Promise
<ResponsePayload
> {
124 return this.sendRequest(ProcedureName
.START_TRANSACTION
, {
131 public async stopTransaction(
133 transactionId
: number | undefined
134 ): Promise
<ResponsePayload
> {
135 return this.sendRequest(ProcedureName
.STOP_TRANSACTION
, {
141 public async startAutomaticTransactionGenerator(
144 ): Promise
<ResponsePayload
> {
145 return this.sendRequest(ProcedureName
.START_AUTOMATIC_TRANSACTION_GENERATOR
, {
147 connectorIds
: [connectorId
]
151 public async stopAutomaticTransactionGenerator(
154 ): Promise
<ResponsePayload
> {
155 return this.sendRequest(ProcedureName
.STOP_AUTOMATIC_TRANSACTION_GENERATOR
, {
157 connectorIds
: [connectorId
]
161 private openWS(): void {
163 this.uiServerConfiguration
.authentication
?.enabled
=== true &&
164 this.uiServerConfiguration
.authentication
?.type === AuthenticationType
.PROTOCOL_BASIC_AUTH
166 `${this.uiServerConfiguration.protocol}${this.uiServerConfiguration.version}`,
167 `authorization.basic.${btoa(`${this.uiServerConfiguration.authentication.username}:${this.uiServerConfiguration.authentication.password}`).replace(/={1,2}$
/, '')}`
169 : `${this.uiServerConfiguration.protocol}${this.uiServerConfiguration.version}
`
170 this.ws = new WebSocket(
171 `${this.uiServerConfiguration.secure === true ? ApplicationProtocol.WSS : ApplicationProtocol.WS}
://${this.uiServerConfiguration.host}:${this.uiServerConfiguration.port}`,
174 this.ws
.onopen
= () => {
176 `WebSocket to UI server '${this.uiServerConfiguration.host}' successfully opened`
179 this.ws
.onmessage
= this.responseHandler
.bind(this)
180 this.ws
.onerror
= errorEvent
=> {
181 useToast().error(`Error in WebSocket to UI server '${this.uiServerConfiguration.host}'`)
183 `Error in WebSocket to UI server '${this.uiServerConfiguration.host}'`,
187 this.ws
.onclose
= () => {
188 useToast().info(`WebSocket to UI server closed`)
192 private async sendRequest(
193 procedureName
: ProcedureName
,
194 payload
: RequestPayload
195 ): Promise
<ResponsePayload
> {
196 return new Promise
<ResponsePayload
>((resolve
, reject
) => {
197 if (this.ws
?.readyState
=== WebSocket
.OPEN
) {
198 const uuid
= randomUUID()
199 const msg
= JSON
.stringify([uuid
, procedureName
, payload
])
200 const sendTimeout
= setTimeout(() => {
201 this.responseHandlers
.delete(uuid
)
202 return reject(new Error(`Send request '${procedureName}' message: connection timeout`))
206 this.responseHandlers
.set(uuid
, { procedureName
, resolve
, reject
})
208 this.responseHandlers
.delete(uuid
)
211 clearTimeout(sendTimeout
)
214 reject(new Error(`Send request '${procedureName}' message: connection closed`))
219 private responseHandler(messageEvent
: MessageEvent
<string>): void {
220 const response
= JSON
.parse(messageEvent
.data
) as ProtocolResponse
222 if (Array.isArray(response
) === false) {
223 throw new Error(`Response not an array: ${JSON.stringify(response, undefined, 2)}`)
226 const [uuid
, responsePayload
] = response
228 if (this.responseHandlers
.has(uuid
) === true) {
229 const { procedureName
, resolve
, reject
} = this.responseHandlers
.get(uuid
)!
230 switch (responsePayload
.status) {
231 case ResponseStatus
.SUCCESS
:
232 resolve(responsePayload
)
234 case ResponseStatus
.FAILURE
:
235 reject(responsePayload
)
240 `Response status for procedure '${procedureName}' not supported: '${responsePayload.status}'`
244 this.responseHandlers
.delete(uuid
)
246 throw new Error(`Not a response to a request: ${JSON.stringify(response, undefined, 2)}`)