Add UUIDv4 id to UI protocol message structure
[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 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;
35 } else {
36 throw new BaseError('UI protocol request is not iterable');
37 }
38 let messageResponse: JsonType;
39 if (this.messageHandlers.has(command)) {
40 try {
41 // Call the message handler to build the message response
42 messageResponse = (await this.messageHandlers.get(command)(payload)) as JsonType;
43 } catch (error) {
44 // Log
45 logger.error(this.uiServer.logPrefix() + ' Handle message error: %j', error);
46 throw error;
47 }
48 } else {
49 // Throw exception
50 throw new BaseError(
51 `${command} is not implemented to handle message payload ${JSON.stringify(
52 payload,
53 null,
54 2
55 )}`
56 );
57 }
58 // Send the message response
59 this.uiServer.sendResponse(this.buildProtocolMessage(messageId, command, messageResponse));
60 }
61
62 protected buildProtocolMessage(
63 messageId: string,
64 command: ProtocolCommand,
65 payload: JsonType
66 ): string {
67 return JSON.stringify([messageId, command, payload]);
68 }
69
70 private handleListChargingStations(): JsonType {
71 return Array.from(this.uiServer.chargingStations);
72 }
73 }