UI Protocol: Expose ATG status and use array for all list
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIWebSocketServer.ts
index 8e11b66da55e09c5b89dea39a998ed0135a3789d..c4829dcc29d9362d024fde7644c2df8355405218 100644 (file)
@@ -1,8 +1,10 @@
 import type { IncomingMessage } from 'http';
 
-import WebSocket from 'ws';
+import WebSocket, { RawData } from 'ws';
 
+import BaseError from '../../exception/BaseError';
 import type { ServerOptions } from '../../types/ConfigurationData';
+import type { ProtocolRequest, ProtocolResponse } from '../../types/UIProtocol';
 import { WebSocketCloseEventStatusCode } from '../../types/WebSocket';
 import Configuration from '../../utils/Configuration';
 import logger from '../../utils/Logger';
@@ -20,8 +22,8 @@ export default class UIWebSocketServer extends AbstractUIServer {
   }
 
   public start(): void {
-    this.server.on('connection', (socket: WebSocket, request: IncomingMessage): void => {
-      const [protocol, version] = UIServiceUtils.getProtocolAndVersion(socket.protocol);
+    this.server.on('connection', (ws: WebSocket, request: IncomingMessage): void => {
+      const [protocol, version] = UIServiceUtils.getProtocolAndVersion(ws.protocol);
       if (UIServiceUtils.isProtocolAndVersionSupported(protocol, version) === false) {
         logger.error(
           `${this.logPrefix(
@@ -29,24 +31,31 @@ export default class UIWebSocketServer extends AbstractUIServer {
             'start.server.onconnection'
           )} Unsupported UI protocol version: '${protocol}${version}'`
         );
-        socket.close(WebSocketCloseEventStatusCode.CLOSE_PROTOCOL_ERROR);
+        ws.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', (rawData) => {
+      ws.on('message', (rawData) => {
+        const [messageId, procedureName, payload] = this.validateRawDataRequest(rawData);
         this.uiServices
           .get(version)
-          .requestHandler(rawData)
+          .requestHandler(this.buildProtocolRequest(messageId, procedureName, payload))
           .catch(() => {
             /* Error caught by AbstractUIService */
           });
       });
-      socket.on('error', (error) => {
-        logger.error(
-          `${this.logPrefix(moduleName, 'start.socket.onerror')} Error on WebSocket:`,
-          error
+      ws.on('error', (error) => {
+        logger.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error);
+      });
+      ws.on('close', (code, reason) => {
+        logger.debug(
+          `${this.logPrefix(
+            moduleName,
+            'start.ws.onclose'
+          )} WebSocket closed: '${Utils.getWebSocketCloseEventStatusString(
+            code
+          )}' - '${reason.toString()}'`
         );
       });
     });
@@ -56,13 +65,13 @@ export default class UIWebSocketServer extends AbstractUIServer {
     this.chargingStations.clear();
   }
 
-  public sendRequest(request: string): void {
-    this.broadcastToClients(request);
+  public sendRequest(request: ProtocolRequest): void {
+    this.broadcastToClients(JSON.stringify(request));
   }
 
-  public sendResponse(response: string): void {
+  public sendResponse(response: ProtocolResponse): void {
     // TODO: send response only to the client that sent the request
-    this.broadcastToClients(response);
+    this.broadcastToClients(JSON.stringify(response));
   }
 
   public logPrefix(modName?: string, methodName?: string, prefixSuffix?: string): string {
@@ -81,4 +90,25 @@ export default class UIWebSocketServer extends AbstractUIServer {
       }
     }
   }
+
+  private validateRawDataRequest(rawData: RawData): ProtocolRequest {
+    // logger.debug(
+    //   `${this.logPrefix(
+    //     moduleName,
+    //     'validateRawDataRequest'
+    //   )} Raw data received in string format: ${rawData.toString()}`
+    // );
+
+    const request = JSON.parse(rawData.toString()) as ProtocolRequest;
+
+    if (Array.isArray(request) === false) {
+      throw new BaseError('UI protocol request is not an array');
+    }
+
+    if (request.length !== 3) {
+      throw new BaseError('UI protocol request is malformed');
+    }
+
+    return request;
+  }
 }