From: Jérôme Benoit Date: Mon, 29 Nov 2021 14:38:58 +0000 (+0100) Subject: Add initial code for WebSocket server to pilot remotely the simulator X-Git-Tag: v1.1.36~17 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=2a78593f6f1952483a6a9e3f510b4fe21f1a9dfd;p=e-mobility-charging-stations-simulator.git Add initial code for WebSocket server to pilot remotely the simulator Signed-off-by: Jérôme Benoit --- diff --git a/src/charging-station/WebSocketServer.ts b/src/charging-station/WebSocketServer.ts new file mode 100644 index 00000000..b0660bd8 --- /dev/null +++ b/src/charging-station/WebSocketServer.ts @@ -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]; + +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): 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}`); + } + }); + } +}