Add initial code for WebSocket server to pilot remotely the simulator
authorJérôme Benoit <jerome.benoit@sap.com>
Mon, 29 Nov 2021 14:38:58 +0000 (15:38 +0100)
committerJérôme Benoit <jerome.benoit@sap.com>
Mon, 29 Nov 2021 14:38:58 +0000 (15:38 +0100)
Signed-off-by: Jérôme Benoit <jerome.benoit@piment-noir.org>
src/charging-station/WebSocketServer.ts [new file with mode: 0644]

diff --git a/src/charging-station/WebSocketServer.ts b/src/charging-station/WebSocketServer.ts
new file mode 100644 (file)
index 0000000..b0660bd
--- /dev/null
@@ -0,0 +1,45 @@
+import { IncomingMessage } from 'http';
+import WebSocket from 'ws';
+import logger from '../utils/Logger';
+
+enum WebSocketServerCommand {
+  START_TRANSACTION = 'startTransaction',
+  STOP_TRANSACTION = 'stopTransaction',
+  UNKNOWN = 'unknown',
+}
+
+type WebSocketServerRequest = [WebSocketServerCommand, Record<string, unknown>];
+
+export default class WebSocketServer extends WebSocket.Server {
+  public constructor(options?: WebSocket.ServerOptions, callback?: () => void) {
+    // Create the WebSocket Server
+    super(options, callback);
+  }
+
+  public broadcastToClients(message: Record<string, unknown>): void {
+    for (const client of this.clients) {
+      if (client?.readyState === WebSocket.OPEN) {
+        client.send(message);
+      }
+    }
+  }
+
+  public start(): void {
+    // this.on('connection', (socket: WebSocket, request: IncomingMessage): void => {
+    //   // Check connection validity
+    // });
+    this.on('message', (messageData) => {
+      let [command, payload]: WebSocketServerRequest = [WebSocketServerCommand.UNKNOWN, {}];
+      // FIXME: check for iterable object
+      [command, payload] = JSON.parse(messageData.toString()) as WebSocketServerRequest;
+      switch (command) {
+        case WebSocketServerCommand.START_TRANSACTION:
+          break;
+        case WebSocketServerCommand.STOP_TRANSACTION:
+          break;
+        default:
+          logger.warn(`Unknown command: ${command}`);
+      }
+    });
+  }
+}