1 import { RawData
} from
'ws';
3 import BaseError from
'../../../exception/BaseError';
4 import { JsonType
} from
'../../../types/JsonType';
8 ProtocolRequestHandler
,
10 } from
'../../../types/UIProtocol';
11 import logger from
'../../../utils/Logger';
12 import Utils from
'../../../utils/Utils';
13 import { AbstractUIServer
} from
'../AbstractUIServer';
15 export default abstract class AbstractUIService
{
16 protected readonly version
: ProtocolVersion
;
17 protected readonly uiServer
: AbstractUIServer
;
18 protected readonly messageHandlers
: Map
<ProtocolCommand
, ProtocolRequestHandler
>;
20 constructor(uiServer
: AbstractUIServer
, version
: ProtocolVersion
) {
21 this.version
= version
;
22 this.uiServer
= uiServer
;
23 this.messageHandlers
= new Map
<ProtocolCommand
, ProtocolRequestHandler
>([
24 [ProtocolCommand
.LIST_CHARGING_STATIONS
, this.handleListChargingStations
.bind(this)],
28 public async messageHandler(request
: RawData
): Promise
<void> {
29 let messageId
: string;
30 let command
: ProtocolCommand
;
31 let payload
: JsonType
;
32 const protocolRequest
= JSON
.parse(request
.toString()) as ProtocolRequest
;
33 if (Utils
.isIterable(protocolRequest
)) {
34 [messageId
, command
, payload
] = protocolRequest
;
36 throw new BaseError('UI protocol request is not iterable');
38 // TODO: should probably be moved to the ws verify clients callback
39 if (protocolRequest
.length
!== 3) {
40 throw new BaseError('UI protocol request is malformed');
42 let messageResponse
: JsonType
;
43 if (this.messageHandlers
.has(command
)) {
45 // Call the message handler to build the message response
46 messageResponse
= (await this.messageHandlers
.get(command
)(payload
)) as JsonType
;
49 logger
.error(this.uiServer
.logPrefix() + ' Handle message error: %j', error
);
55 `${command} is not implemented to handle message payload ${JSON.stringify(
62 // Send the message response
63 this.uiServer
.sendResponse(this.buildProtocolMessage(messageId
, command
, messageResponse
));
66 protected buildProtocolMessage(
68 command
: ProtocolCommand
,
71 return JSON
.stringify([messageId
, command
, payload
]);
74 private handleListChargingStations(): JsonType
{
75 return Array.from(this.uiServer
.chargingStations
);