Track version is UI service instance
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / AbstractUIService.ts
CommitLineData
8114d10e
JB
1import { RawData } from 'ws';
2
3import BaseError from '../../../exception/BaseError';
4import { JsonType } from '../../../types/JsonType';
675fa8e3
JB
5import {
6 ProtocolCommand,
7 ProtocolRequest,
8 ProtocolRequestHandler,
33cea517 9 ProtocolVersion,
675fa8e3 10} from '../../../types/UIProtocol';
675fa8e3 11import logger from '../../../utils/Logger';
8114d10e
JB
12import Utils from '../../../utils/Utils';
13import { AbstractUIServer } from '../AbstractUIServer';
4198ad5c
JB
14
15export default abstract class AbstractUIService {
33cea517 16 protected readonly version: ProtocolVersion;
fe94fce0 17 protected readonly uiServer: AbstractUIServer;
4198ad5c
JB
18 protected readonly messageHandlers: Map<ProtocolCommand, ProtocolRequestHandler>;
19
33cea517
JB
20 constructor(uiServer: AbstractUIServer, version: ProtocolVersion) {
21 this.version = version;
675fa8e3 22 this.uiServer = uiServer;
4198ad5c
JB
23 this.messageHandlers = new Map<ProtocolCommand, ProtocolRequestHandler>([
24 [ProtocolCommand.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
25 ]);
26 }
27
178ac666
JB
28 public async messageHandler(request: RawData): Promise<void> {
29 let command: ProtocolCommand;
30 let payload: JsonType;
31 const protocolRequest = JSON.parse(request.toString()) as ProtocolRequest;
32 if (Utils.isIterable(protocolRequest)) {
33 [command, payload] = protocolRequest;
34 } else {
35 throw new BaseError('UI protocol request is not iterable');
36 }
5cc4b63b 37 let messageResponse: JsonType;
4198ad5c
JB
38 if (this.messageHandlers.has(command)) {
39 try {
178ac666 40 // Call the message handler to build the message response
5cc4b63b 41 messageResponse = (await this.messageHandlers.get(command)(payload)) as JsonType;
4198ad5c
JB
42 } catch (error) {
43 // Log
675fa8e3 44 logger.error(this.uiServer.logPrefix() + ' Handle message error: %j', error);
4198ad5c
JB
45 throw error;
46 }
47 } else {
48 // Throw exception
e7aeea18
JB
49 throw new BaseError(
50 `${command} is not implemented to handle message payload ${JSON.stringify(
51 payload,
52 null,
53 2
54 )}`
55 );
4198ad5c 56 }
178ac666 57 // Send the message response
675fa8e3 58 this.uiServer.sendResponse(this.buildProtocolMessage(command, messageResponse));
4198ad5c
JB
59 }
60
5cc4b63b 61 protected buildProtocolMessage(command: ProtocolCommand, payload: JsonType): string {
4198ad5c
JB
62 return JSON.stringify([command, payload]);
63 }
64
178ac666 65 private handleListChargingStations(): JsonType {
675fa8e3 66 return Array.from(this.uiServer.chargingStations);
4198ad5c
JB
67 }
68}