1 import { RawData
} from
'ws';
3 import BaseError from
'../../../exception/BaseError';
4 import { JsonType
} from
'../../../types/JsonType';
8 ProtocolRequestHandler
,
9 } from
'../../../types/UIProtocol';
10 import logger from
'../../../utils/Logger';
11 import Utils from
'../../../utils/Utils';
12 import { AbstractUIServer
} from
'../AbstractUIServer';
14 export default abstract class AbstractUIService
{
15 protected readonly uiServer
: AbstractUIServer
;
16 protected readonly messageHandlers
: Map
<ProtocolCommand
, ProtocolRequestHandler
>;
18 constructor(uiServer
: AbstractUIServer
) {
19 this.uiServer
= uiServer
;
20 this.messageHandlers
= new Map
<ProtocolCommand
, ProtocolRequestHandler
>([
21 [ProtocolCommand
.LIST_CHARGING_STATIONS
, this.handleListChargingStations
.bind(this)],
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
;
32 throw new BaseError('UI protocol request is not iterable');
34 let messageResponse
: JsonType
;
35 if (this.messageHandlers
.has(command
)) {
37 // Call the message handler to build the message response
38 messageResponse
= (await this.messageHandlers
.get(command
)(payload
)) as JsonType
;
41 logger
.error(this.uiServer
.logPrefix() + ' Handle message error: %j', error
);
47 `${command} is not implemented to handle message payload ${JSON.stringify(
54 // Send the message response
55 this.uiServer
.sendResponse(this.buildProtocolMessage(command
, messageResponse
));
58 protected buildProtocolMessage(command
: ProtocolCommand
, payload
: JsonType
): string {
59 return JSON
.stringify([command
, payload
]);
62 private handleListChargingStations(): JsonType
{
63 return Array.from(this.uiServer
.chargingStations
);