3fe7bbb2da06b9a30e8251ba4c6b80968bc45d61
[e-mobility-charging-stations-simulator.git] / src / charging-station / WebSocketServer.ts
1 import { ProtocolCommand, ProtocolRequest, ProtocolVersion } from '../types/UIProtocol';
2
3 import AbstractUIService from './WebSocketServices/ui/AbstractUIService';
4 import { IncomingMessage } from 'http';
5 import UIService from './WebSocketServices/ui/0.0.1/UIService';
6 import Utils from '../utils/Utils';
7 import WebSocket from 'ws';
8 import logger from '../utils/Logger';
9
10 export default class WebSocketServer extends WebSocket.Server {
11 private webSocketServerService: AbstractUIService;
12
13 public constructor(options?: WebSocket.ServerOptions, callback?: () => void) {
14 // Create the WebSocket Server
15 super(options, callback);
16 // FIXME: version the instantiation
17 this.webSocketServerService = new UIService(this);
18 }
19
20 public broadcastToClients(message: Record<string, unknown>): void {
21 for (const client of this.clients) {
22 if (client?.readyState === WebSocket.OPEN) {
23 client.send(message);
24 }
25 }
26 }
27
28 public start(): void {
29 // eslint-disable-next-line @typescript-eslint/no-this-alias
30 const self = this;
31 this.on('connection', (socket: WebSocket, request: IncomingMessage): void => {
32 // Check connection validity
33 });
34 this.on('message', (messageData) => {
35 let [version, command, payload]: ProtocolRequest = [ProtocolVersion['0.0.1'], ProtocolCommand.UNKNOWN, {}];
36 // FIXME: check for iterable object
37 [version, command, payload] = JSON.parse(messageData.toString()) as ProtocolRequest;
38 switch (version) {
39 case ProtocolVersion['0.0.1']:
40 self.webSocketServerService.handleMessage(command, payload).catch(() => { });
41 break;
42 default:
43 logger.error(`${this.logPrefix()} Unknown protocol version: ${version}`);
44 }
45 });
46 }
47
48 public stop(): void {
49 this.close();
50 }
51
52 public logPrefix(): string {
53 return Utils.logPrefix('WebSocket Server:');
54 }
55 }