1 import { ProtocolCommand
, ProtocolRequestHandler
} from
'../../types/UIProtocol';
3 import BaseError from
'../../exception/BaseError';
4 import UIWebSocketServer from
'../UIWebSocketServer';
5 import logger from
'../../utils/Logger';
7 export default abstract class AbstractUIService
{
8 public readonly chargingStations
: Set
<string>;
9 protected readonly uiWebSocketServer
: UIWebSocketServer
;
10 protected readonly messageHandlers
: Map
<ProtocolCommand
, ProtocolRequestHandler
>;
12 constructor(uiWebSocketServer
: UIWebSocketServer
) {
13 this.chargingStations
= new Set
<string>();
14 this.uiWebSocketServer
= uiWebSocketServer
;
15 this.messageHandlers
= new Map
<ProtocolCommand
, ProtocolRequestHandler
>([
16 [ProtocolCommand
.LIST_CHARGING_STATIONS
, this.handleListChargingStations
.bind(this)],
20 public async handleMessage(command
: ProtocolCommand
, payload
: Record
<string, unknown
>): Promise
<void> {
21 let messageResponse
: Record
<string, unknown
>;
22 if (this.messageHandlers
.has(command
)) {
24 // Call the method to build the message response
25 messageResponse
= await this.messageHandlers
.get(command
)(payload
) as Record
<string, unknown
>;
28 logger
.error(this.uiWebSocketServer
.logPrefix() + ' Handle message error: %j', error
);
33 throw new BaseError(`${command} is not implemented to handle message payload ${JSON.stringify(payload, null, 2)}`);
35 // Send the built message response
36 this.uiWebSocketServer
.broadcastToClients(this.buildProtocolMessage(command
, messageResponse
));
39 protected buildProtocolMessage(
40 command
: ProtocolCommand
,
41 payload
: Record
<string, unknown
>,
43 return JSON
.stringify([command
, payload
]);
46 protected handleListChargingStations(): Set
<string> {
47 return this.chargingStations
;