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