Track version is UI service instance
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / AbstractUIService.ts
1 import { RawData } from 'ws';
2
3 import BaseError from '../../../exception/BaseError';
4 import { JsonType } from '../../../types/JsonType';
5 import {
6 ProtocolCommand,
7 ProtocolRequest,
8 ProtocolRequestHandler,
9 ProtocolVersion,
10 } from '../../../types/UIProtocol';
11 import logger from '../../../utils/Logger';
12 import Utils from '../../../utils/Utils';
13 import { AbstractUIServer } from '../AbstractUIServer';
14
15 export default abstract class AbstractUIService {
16 protected readonly version: ProtocolVersion;
17 protected readonly uiServer: AbstractUIServer;
18 protected readonly messageHandlers: Map<ProtocolCommand, ProtocolRequestHandler>;
19
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)],
25 ]);
26 }
27
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 }
37 let messageResponse: JsonType;
38 if (this.messageHandlers.has(command)) {
39 try {
40 // Call the message handler to build the message response
41 messageResponse = (await this.messageHandlers.get(command)(payload)) as JsonType;
42 } catch (error) {
43 // Log
44 logger.error(this.uiServer.logPrefix() + ' Handle message error: %j', error);
45 throw error;
46 }
47 } else {
48 // Throw exception
49 throw new BaseError(
50 `${command} is not implemented to handle message payload ${JSON.stringify(
51 payload,
52 null,
53 2
54 )}`
55 );
56 }
57 // Send the message response
58 this.uiServer.sendResponse(this.buildProtocolMessage(command, messageResponse));
59 }
60
61 protected buildProtocolMessage(command: ProtocolCommand, payload: JsonType): string {
62 return JSON.stringify([command, payload]);
63 }
64
65 private handleListChargingStations(): JsonType {
66 return Array.from(this.uiServer.chargingStations);
67 }
68 }