Commit | Line | Data |
---|---|---|
a10297ba | 1 | import { ProtocolCommand, ProtocolRequestHandler } from '../../types/UIProtocol'; |
4198ad5c JB |
2 | |
3 | import BaseError from '../../exception/BaseError'; | |
d1888640 | 4 | import { JsonType } from '../../types/JsonType'; |
4198ad5c | 5 | import UIWebSocketServer from '../UIWebSocketServer'; |
9f2e3130 | 6 | import logger from '../../utils/Logger'; |
4198ad5c JB |
7 | |
8 | export default abstract class AbstractUIService { | |
4198ad5c JB |
9 | protected readonly uiWebSocketServer: UIWebSocketServer; |
10 | protected readonly messageHandlers: Map<ProtocolCommand, ProtocolRequestHandler>; | |
11 | ||
12 | constructor(uiWebSocketServer: UIWebSocketServer) { | |
4198ad5c | 13 | this.uiWebSocketServer = uiWebSocketServer; |
4198ad5c JB |
14 | this.messageHandlers = new Map<ProtocolCommand, ProtocolRequestHandler>([ |
15 | [ProtocolCommand.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)], | |
16 | ]); | |
17 | } | |
18 | ||
d1888640 JB |
19 | public async handleMessage(command: ProtocolCommand, payload: JsonType): Promise<void> { |
20 | let messageResponse: JsonType; | |
4198ad5c JB |
21 | if (this.messageHandlers.has(command)) { |
22 | try { | |
23 | // Call the method to build the message response | |
d1888640 | 24 | messageResponse = await this.messageHandlers.get(command)(payload) as JsonType; |
4198ad5c JB |
25 | } catch (error) { |
26 | // Log | |
9f2e3130 | 27 | logger.error(this.uiWebSocketServer.logPrefix() + ' Handle message error: %j', error); |
4198ad5c JB |
28 | throw error; |
29 | } | |
30 | } else { | |
31 | // Throw exception | |
32 | throw new BaseError(`${command} is not implemented to handle message payload ${JSON.stringify(payload, null, 2)}`); | |
33 | } | |
34 | // Send the built message response | |
35 | this.uiWebSocketServer.broadcastToClients(this.buildProtocolMessage(command, messageResponse)); | |
36 | } | |
37 | ||
38 | protected buildProtocolMessage( | |
39 | command: ProtocolCommand, | |
d1888640 | 40 | payload: JsonType, |
4198ad5c JB |
41 | ): string { |
42 | return JSON.stringify([command, payload]); | |
43 | } | |
44 | ||
f16356b9 | 45 | private handleListChargingStations(): Set<string> { |
de9136ae | 46 | return this.uiWebSocketServer.chargingStations; |
4198ad5c JB |
47 | } |
48 | } |