1 import { ProtocolCommand
, ProtocolRequest
, ProtocolRequestHandler
} from
'../../types/UIProtocol';
3 import BaseError from
'../../exception/BaseError';
4 import { JsonType
} from
'../../types/JsonType';
5 import { RawData
} from
'ws';
6 import UIWebSocketServer from
'../UIWebSocketServer';
7 import Utils from
'../../utils/Utils';
8 import logger from
'../../utils/Logger';
10 export default abstract class AbstractUIService
{
11 protected readonly uiWebSocketServer
: UIWebSocketServer
;
12 protected readonly messageHandlers
: Map
<ProtocolCommand
, ProtocolRequestHandler
>;
14 constructor(uiWebSocketServer
: UIWebSocketServer
) {
15 this.uiWebSocketServer
= uiWebSocketServer
;
16 this.messageHandlers
= new Map
<ProtocolCommand
, ProtocolRequestHandler
>([
17 [ProtocolCommand
.LIST_CHARGING_STATIONS
, this.handleListChargingStations
.bind(this)],
21 public async messageHandler(request
: RawData
): Promise
<void> {
22 let command
: ProtocolCommand
;
23 let payload
: JsonType
;
24 const protocolRequest
= JSON
.parse(request
.toString()) as ProtocolRequest
;
25 if (Utils
.isIterable(protocolRequest
)) {
26 [command
, payload
] = protocolRequest
;
28 throw new BaseError('UI protocol request is not iterable');
30 let messageResponse
: JsonType
;
31 if (this.messageHandlers
.has(command
)) {
33 // Call the message handler to build the message response
34 messageResponse
= (await this.messageHandlers
.get(command
)(payload
)) as JsonType
;
37 logger
.error(this.uiWebSocketServer
.logPrefix() + ' Handle message error: %j', error
);
43 `${command} is not implemented to handle message payload ${JSON.stringify(
50 // Send the message response
51 this.uiWebSocketServer
.sendResponse(this.buildProtocolMessage(command
, messageResponse
));
54 protected buildProtocolMessage(command
: ProtocolCommand
, payload
: JsonType
): string {
55 return JSON
.stringify([command
, payload
]);
58 private handleListChargingStations(): JsonType
{
59 return Array.from(this.uiWebSocketServer
.chargingStations
);