Move cache related helper to the right class
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIWebSocketServer.ts
CommitLineData
675fa8e3 1import { Protocol, ProtocolVersion } from '../../types/UIProtocol';
66271092 2import WebSocket, { OPEN, Server } from 'ws';
4198ad5c 3
fe94fce0 4import { AbstractUIServer } from './AbstractUIServer';
675fa8e3 5import Configuration from '../../utils/Configuration';
4198ad5c 6import { IncomingMessage } from 'http';
66271092 7import { ServerOptions } from '../../types/ConfigurationData';
675fa8e3
JB
8import UIServiceFactory from './ui-services/UIServiceFactory';
9import Utils from '../../utils/Utils';
10import logger from '../../utils/Logger';
4198ad5c 11
fe94fce0 12export default class UIWebSocketServer extends AbstractUIServer {
b153c0fd 13 public constructor(options?: ServerOptions) {
fe94fce0 14 super();
d200b695 15 this.server = new Server(options ?? Configuration.getUIServer().options);
4198ad5c
JB
16 }
17
18 public start(): void {
d200b695 19 this.server.on('connection', (socket: WebSocket, request: IncomingMessage): void => {
4198ad5c 20 const protocolIndex = socket.protocol.indexOf(Protocol.UI);
e7aeea18
JB
21 const version = socket.protocol.substring(
22 protocolIndex + Protocol.UI.length
23 ) as ProtocolVersion;
de9136ae 24 if (!this.uiServices.has(version)) {
178ac666 25 this.uiServices.set(version, UIServiceFactory.getUIServiceImplementation(version, this));
4198ad5c
JB
26 }
27 // FIXME: check connection validity
28 socket.on('message', (messageData) => {
e7aeea18
JB
29 this.uiServices
30 .get(version)
178ac666 31 .messageHandler(messageData)
e7aeea18 32 .catch(() => {
178ac666 33 logger.error(`${this.logPrefix()} Error while handling message data: %j`, messageData);
e7aeea18 34 });
4198ad5c
JB
35 });
36 socket.on('error', (error) => {
9f2e3130 37 logger.error(`${this.logPrefix()} Error on WebSocket: %j`, error);
4198ad5c
JB
38 });
39 });
40 }
41
42 public stop(): void {
d200b695 43 this.server.close();
4198ad5c
JB
44 }
45
178ac666
JB
46 public sendResponse(message: string): void {
47 this.broadcastToClients(message);
48 }
49
4198ad5c 50 public logPrefix(): string {
410a760d 51 return Utils.logPrefix(' UI WebSocket Server:');
4198ad5c 52 }
178ac666
JB
53
54 private broadcastToClients(message: string): void {
d200b695 55 for (const client of (this.server as Server).clients) {
178ac666
JB
56 if (client?.readyState === OPEN) {
57 client.send(message);
58 }
59 }
60 }
4198ad5c 61}