README.md: formatting fixes
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIWebSocketServer.ts
index da476895d5f87dc3476797efd011e389808ade66..8e11b66da55e09c5b89dea39a998ed0135a3789d 100644 (file)
@@ -1,59 +1,82 @@
-import { Protocol, ProtocolVersion } from '../../types/UIProtocol';
-import WebSocket, { OPEN, Server } from 'ws';
+import type { IncomingMessage } from 'http';
 
-import { AbstractUIServer } from './AbstractUIServer';
+import WebSocket from 'ws';
+
+import type { ServerOptions } from '../../types/ConfigurationData';
+import { WebSocketCloseEventStatusCode } from '../../types/WebSocket';
 import Configuration from '../../utils/Configuration';
-import { IncomingMessage } from 'http';
-import { ServerOptions } from '../../types/ConfigurationData';
-import UIServiceFactory from './ui-services/UIServiceFactory';
-import Utils from '../../utils/Utils';
 import logger from '../../utils/Logger';
+import Utils from '../../utils/Utils';
+import { AbstractUIServer } from './AbstractUIServer';
+import UIServiceFactory from './ui-services/UIServiceFactory';
+import { UIServiceUtils } from './ui-services/UIServiceUtils';
+
+const moduleName = 'UIWebSocketServer';
 
 export default class UIWebSocketServer extends AbstractUIServer {
-  public constructor(options?: ServerOptions, callback?: () => void) {
+  public constructor(options?: ServerOptions) {
     super();
-    this.uiServer = new Server(options ?? Configuration.getUIServer().options, callback);
+    this.server = new WebSocket.Server(options ?? Configuration.getUIServer().options);
   }
 
   public start(): void {
-    this.uiServer.on('connection', (socket: WebSocket, request: IncomingMessage): void => {
-      const protocolIndex = socket.protocol.indexOf(Protocol.UI);
-      const version = socket.protocol.substring(
-        protocolIndex + Protocol.UI.length
-      ) as ProtocolVersion;
+    this.server.on('connection', (socket: WebSocket, request: IncomingMessage): void => {
+      const [protocol, version] = UIServiceUtils.getProtocolAndVersion(socket.protocol);
+      if (UIServiceUtils.isProtocolAndVersionSupported(protocol, version) === false) {
+        logger.error(
+          `${this.logPrefix(
+            moduleName,
+            'start.server.onconnection'
+          )} Unsupported UI protocol version: '${protocol}${version}'`
+        );
+        socket.close(WebSocketCloseEventStatusCode.CLOSE_PROTOCOL_ERROR);
+      }
       if (!this.uiServices.has(version)) {
         this.uiServices.set(version, UIServiceFactory.getUIServiceImplementation(version, this));
       }
       // FIXME: check connection validity
-      socket.on('message', (messageData) => {
+      socket.on('message', (rawData) => {
         this.uiServices
           .get(version)
-          .messageHandler(messageData)
+          .requestHandler(rawData)
           .catch(() => {
-            logger.error(`${this.logPrefix()} Error while handling message data: %j`, messageData);
+            /* Error caught by AbstractUIService */
           });
       });
       socket.on('error', (error) => {
-        logger.error(`${this.logPrefix()} Error on WebSocket: %j`, error);
+        logger.error(
+          `${this.logPrefix(moduleName, 'start.socket.onerror')} Error on WebSocket:`,
+          error
+        );
       });
     });
   }
 
   public stop(): void {
-    this.uiServer.close();
+    this.chargingStations.clear();
+  }
+
+  public sendRequest(request: string): void {
+    this.broadcastToClients(request);
   }
 
-  public sendResponse(message: string): void {
-    this.broadcastToClients(message);
+  public sendResponse(response: string): void {
+    // TODO: send response only to the client that sent the request
+    this.broadcastToClients(response);
   }
 
-  public logPrefix(): string {
-    return Utils.logPrefix(' UI WebSocket Server:');
+  public logPrefix(modName?: string, methodName?: string, prefixSuffix?: string): string {
+    const logMsgPrefix = prefixSuffix
+      ? `UI WebSocket Server ${prefixSuffix}`
+      : 'UI WebSocket Server';
+    const logMsg =
+      modName && methodName ? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`;
+    return Utils.logPrefix(logMsg);
   }
 
   private broadcastToClients(message: string): void {
-    for (const client of (this.uiServer as Server).clients) {
-      if (client?.readyState === OPEN) {
+    for (const client of (this.server as WebSocket.Server).clients) {
+      if (client?.readyState === WebSocket.OPEN) {
         client.send(message);
       }
     }