| 1 | import { |
| 2 | ApplicationProtocol, |
| 3 | AuthenticationType, |
| 4 | type ConfigurationData, |
| 5 | ProcedureName, |
| 6 | type ProtocolResponse, |
| 7 | type RequestPayload, |
| 8 | type ResponsePayload, |
| 9 | ResponseStatus |
| 10 | } from '@/types' |
| 11 | |
| 12 | type ResponseHandler = { |
| 13 | procedureName: ProcedureName |
| 14 | resolve: (value: ResponsePayload | PromiseLike<ResponsePayload>) => void |
| 15 | reject: (reason?: unknown) => void |
| 16 | } |
| 17 | |
| 18 | export class UIClient { |
| 19 | private static instance: UIClient | null = null |
| 20 | |
| 21 | private ws!: WebSocket |
| 22 | private responseHandlers: Map<string, ResponseHandler> |
| 23 | |
| 24 | private constructor(private configuration: ConfigurationData) { |
| 25 | this.openWS() |
| 26 | this.responseHandlers = new Map<string, ResponseHandler>() |
| 27 | } |
| 28 | |
| 29 | public static getInstance(configuration: ConfigurationData) { |
| 30 | if (UIClient.instance === null) { |
| 31 | UIClient.instance = new UIClient(configuration) |
| 32 | } |
| 33 | return UIClient.instance |
| 34 | } |
| 35 | |
| 36 | public registerWSonOpenListener(listener: (event: Event) => void) { |
| 37 | this.ws.addEventListener('open', listener) |
| 38 | } |
| 39 | |
| 40 | public async startSimulator(): Promise<ResponsePayload> { |
| 41 | return this.sendRequest(ProcedureName.START_SIMULATOR, {}) |
| 42 | } |
| 43 | |
| 44 | public async stopSimulator(): Promise<ResponsePayload> { |
| 45 | return this.sendRequest(ProcedureName.STOP_SIMULATOR, {}) |
| 46 | } |
| 47 | |
| 48 | public async deleteChargingStation(hashId: string): Promise<ResponsePayload> { |
| 49 | return this.sendRequest(ProcedureName.DELETE_CHARGING_STATIONS, { hashIds: [hashId] }) |
| 50 | } |
| 51 | |
| 52 | public async listChargingStations(): Promise<ResponsePayload> { |
| 53 | return this.sendRequest(ProcedureName.LIST_CHARGING_STATIONS, {}) |
| 54 | } |
| 55 | |
| 56 | public async startChargingStation(hashId: string): Promise<ResponsePayload> { |
| 57 | return this.sendRequest(ProcedureName.START_CHARGING_STATION, { hashIds: [hashId] }) |
| 58 | } |
| 59 | |
| 60 | public async stopChargingStation(hashId: string): Promise<ResponsePayload> { |
| 61 | return this.sendRequest(ProcedureName.STOP_CHARGING_STATION, { hashIds: [hashId] }) |
| 62 | } |
| 63 | |
| 64 | public async openConnection(hashId: string): Promise<ResponsePayload> { |
| 65 | return this.sendRequest(ProcedureName.OPEN_CONNECTION, { |
| 66 | hashIds: [hashId] |
| 67 | }) |
| 68 | } |
| 69 | |
| 70 | public async closeConnection(hashId: string): Promise<ResponsePayload> { |
| 71 | return this.sendRequest(ProcedureName.CLOSE_CONNECTION, { |
| 72 | hashIds: [hashId] |
| 73 | }) |
| 74 | } |
| 75 | |
| 76 | public async startTransaction( |
| 77 | hashId: string, |
| 78 | connectorId: number, |
| 79 | idTag: string | undefined |
| 80 | ): Promise<ResponsePayload> { |
| 81 | return this.sendRequest(ProcedureName.START_TRANSACTION, { |
| 82 | hashIds: [hashId], |
| 83 | connectorId, |
| 84 | idTag |
| 85 | }) |
| 86 | } |
| 87 | |
| 88 | public async stopTransaction( |
| 89 | hashId: string, |
| 90 | transactionId: number | undefined |
| 91 | ): Promise<ResponsePayload> { |
| 92 | return this.sendRequest(ProcedureName.STOP_TRANSACTION, { |
| 93 | hashIds: [hashId], |
| 94 | transactionId |
| 95 | }) |
| 96 | } |
| 97 | |
| 98 | public async startAutomaticTransactionGenerator( |
| 99 | hashId: string, |
| 100 | connectorId: number |
| 101 | ): Promise<ResponsePayload> { |
| 102 | return this.sendRequest(ProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR, { |
| 103 | hashIds: [hashId], |
| 104 | connectorIds: [connectorId] |
| 105 | }) |
| 106 | } |
| 107 | |
| 108 | public async stopAutomaticTransactionGenerator( |
| 109 | hashId: string, |
| 110 | connectorId: number |
| 111 | ): Promise<ResponsePayload> { |
| 112 | return this.sendRequest(ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR, { |
| 113 | hashIds: [hashId], |
| 114 | connectorIds: [connectorId] |
| 115 | }) |
| 116 | } |
| 117 | |
| 118 | public openWS(): void { |
| 119 | const protocols = |
| 120 | this.configuration.uiServer.authentication?.enabled === true && |
| 121 | this.configuration.uiServer.authentication?.type === AuthenticationType.PROTOCOL_BASIC_AUTH |
| 122 | ? [ |
| 123 | `${this.configuration.uiServer.protocol}${this.configuration.uiServer.version}`, |
| 124 | `authorization.basic.${btoa(`${this.configuration.uiServer.authentication.username}:${this.configuration.uiServer.authentication.password}`).replace(/={1,2}$/, '')}` |
| 125 | ] |
| 126 | : `${this.configuration.uiServer.protocol}${this.configuration.uiServer.version}` |
| 127 | this.ws = new WebSocket( |
| 128 | `${this.configuration.uiServer.secure === true ? ApplicationProtocol.WSS : ApplicationProtocol.WS}://${this.configuration.uiServer.host}:${this.configuration.uiServer.port}`, |
| 129 | protocols |
| 130 | ) |
| 131 | this.ws.onopen = openEvent => { |
| 132 | console.info('WebSocket opened', openEvent) |
| 133 | } |
| 134 | this.ws.onmessage = this.responseHandler.bind(this) |
| 135 | this.ws.onerror = errorEvent => { |
| 136 | console.error('WebSocket error: ', errorEvent) |
| 137 | } |
| 138 | this.ws.onclose = closeEvent => { |
| 139 | console.info('WebSocket closed: ', closeEvent) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | private async sendRequest( |
| 144 | procedureName: ProcedureName, |
| 145 | payload: RequestPayload |
| 146 | ): Promise<ResponsePayload> { |
| 147 | return new Promise<ResponsePayload>((resolve, reject) => { |
| 148 | if (this.ws.readyState === WebSocket.OPEN) { |
| 149 | const uuid = crypto.randomUUID() |
| 150 | const msg = JSON.stringify([uuid, procedureName, payload]) |
| 151 | const sendTimeout = setTimeout(() => { |
| 152 | this.responseHandlers.delete(uuid) |
| 153 | return reject(new Error(`Send request '${procedureName}' message: connection timeout`)) |
| 154 | }, 60000) |
| 155 | try { |
| 156 | this.ws.send(msg) |
| 157 | this.responseHandlers.set(uuid, { procedureName, resolve, reject }) |
| 158 | } catch (error) { |
| 159 | this.responseHandlers.delete(uuid) |
| 160 | reject(error) |
| 161 | } finally { |
| 162 | clearTimeout(sendTimeout) |
| 163 | } |
| 164 | } else { |
| 165 | reject(new Error(`Send request '${procedureName}' message: connection closed`)) |
| 166 | } |
| 167 | }) |
| 168 | } |
| 169 | |
| 170 | private responseHandler(messageEvent: MessageEvent<string>): void { |
| 171 | const response = JSON.parse(messageEvent.data) as ProtocolResponse |
| 172 | |
| 173 | if (Array.isArray(response) === false) { |
| 174 | throw new Error(`Response not an array: ${JSON.stringify(response, undefined, 2)}`) |
| 175 | } |
| 176 | |
| 177 | const [uuid, responsePayload] = response |
| 178 | |
| 179 | if (this.responseHandlers.has(uuid) === true) { |
| 180 | const { procedureName, resolve, reject } = this.responseHandlers.get(uuid)! |
| 181 | switch (responsePayload.status) { |
| 182 | case ResponseStatus.SUCCESS: |
| 183 | resolve(responsePayload) |
| 184 | break |
| 185 | case ResponseStatus.FAILURE: |
| 186 | reject(responsePayload) |
| 187 | break |
| 188 | default: |
| 189 | console.error( |
| 190 | `Response status for procedure '${procedureName}' not supported: '${responsePayload.status}'` |
| 191 | ) |
| 192 | } |
| 193 | this.responseHandlers.delete(uuid) |
| 194 | } else { |
| 195 | throw new Error(`Not a response to a request: ${JSON.stringify(response, undefined, 2)}`) |
| 196 | } |
| 197 | } |
| 198 | } |