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 // TODO: Move the shared service code to AbstractUIService
16 this.messageHandlers
= new Map
<ProtocolCommand
, ProtocolRequestHandler
>([
17 [ProtocolCommand
.LIST_CHARGING_STATIONS
, this.handleListChargingStations
.bind(this)],
21 public async handleMessage(command
: ProtocolCommand
, payload
: Record
<string, unknown
>): Promise
<void> {
22 let messageResponse
: Record
<string, unknown
>;
23 if (this.messageHandlers
.has(command
)) {
25 // Call the method to build the message response
26 messageResponse
= await this.messageHandlers
.get(command
)(payload
) as Record
<string, unknown
>;
29 logger
.error(this.uiWebSocketServer
.logPrefix() + ' Handle message error: %j', error
);
34 throw new BaseError(`${command} is not implemented to handle message payload ${JSON.stringify(payload, null, 2)}`);
36 // Send the built message response
37 this.uiWebSocketServer
.broadcastToClients(this.buildProtocolMessage(command
, messageResponse
));
40 protected buildProtocolMessage(
41 command
: ProtocolCommand
,
42 payload
: Record
<string, unknown
>,
44 return JSON
.stringify([command
, payload
]);
47 protected handleListChargingStations(): Set
<string> {
48 return this.chargingStations
;