| 1 | import { |
| 2 | ProtocolCommand, |
| 3 | ProtocolRequest, |
| 4 | ProtocolRequestHandler, |
| 5 | } from '../../../types/UIProtocol'; |
| 6 | |
| 7 | import { AbstractUIServer } from '../AbstractUIServer'; |
| 8 | import BaseError from '../../../exception/BaseError'; |
| 9 | import { JsonType } from '../../../types/JsonType'; |
| 10 | import { RawData } from 'ws'; |
| 11 | import Utils from '../../../utils/Utils'; |
| 12 | import logger from '../../../utils/Logger'; |
| 13 | |
| 14 | export default abstract class AbstractUIService { |
| 15 | protected readonly uiServer: AbstractUIServer; |
| 16 | protected readonly messageHandlers: Map<ProtocolCommand, ProtocolRequestHandler>; |
| 17 | |
| 18 | constructor(uiServer: AbstractUIServer) { |
| 19 | this.uiServer = uiServer; |
| 20 | this.messageHandlers = new Map<ProtocolCommand, ProtocolRequestHandler>([ |
| 21 | [ProtocolCommand.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)], |
| 22 | ]); |
| 23 | } |
| 24 | |
| 25 | public async messageHandler(request: RawData): Promise<void> { |
| 26 | let command: ProtocolCommand; |
| 27 | let payload: JsonType; |
| 28 | const protocolRequest = JSON.parse(request.toString()) as ProtocolRequest; |
| 29 | if (Utils.isIterable(protocolRequest)) { |
| 30 | [command, payload] = protocolRequest; |
| 31 | } else { |
| 32 | throw new BaseError('UI protocol request is not iterable'); |
| 33 | } |
| 34 | let messageResponse: JsonType; |
| 35 | if (this.messageHandlers.has(command)) { |
| 36 | try { |
| 37 | // Call the message handler to build the message response |
| 38 | messageResponse = (await this.messageHandlers.get(command)(payload)) as JsonType; |
| 39 | } catch (error) { |
| 40 | // Log |
| 41 | logger.error(this.uiServer.logPrefix() + ' Handle message error: %j', error); |
| 42 | throw error; |
| 43 | } |
| 44 | } else { |
| 45 | // Throw exception |
| 46 | throw new BaseError( |
| 47 | `${command} is not implemented to handle message payload ${JSON.stringify( |
| 48 | payload, |
| 49 | null, |
| 50 | 2 |
| 51 | )}` |
| 52 | ); |
| 53 | } |
| 54 | // Send the message response |
| 55 | this.uiServer.sendResponse(this.buildProtocolMessage(command, messageResponse)); |
| 56 | } |
| 57 | |
| 58 | protected buildProtocolMessage(command: ProtocolCommand, payload: JsonType): string { |
| 59 | return JSON.stringify([command, payload]); |
| 60 | } |
| 61 | |
| 62 | private handleListChargingStations(): JsonType { |
| 63 | return Array.from(this.uiServer.chargingStations); |
| 64 | } |
| 65 | } |