From f07e3f323fba92675de1a6f80fb597f7966dcb2c Mon Sep 17 00:00:00 2001 From: Stepan Henek Date: Thu, 5 May 2022 14:15:46 +0200 Subject: [PATCH] fixup! WIP: Using socket.io for websocket handling --- src/common/WiFiSettings/ResetWiFiSettings.js | 2 +- src/webSockets/WebSockets.js | 30 ++++++++++---------- src/webSockets/hooks.js | 2 +- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/common/WiFiSettings/ResetWiFiSettings.js b/src/common/WiFiSettings/ResetWiFiSettings.js index 6973a5b..98a6a12 100644 --- a/src/common/WiFiSettings/ResetWiFiSettings.js +++ b/src/common/WiFiSettings/ResetWiFiSettings.js @@ -25,7 +25,7 @@ export function ResetWiFiSettings({ ws, endpoint }) { useEffect(() => { const module = "wifi"; - ws.subscribe(module).bind(module, "reset", () => { + ws.bind(module, "reset", () => { // eslint-disable-next-line no-restricted-globals setTimeout(() => location.reload(), 1000); }); diff --git a/src/webSockets/WebSockets.js b/src/webSockets/WebSockets.js index 4914d3a..f819ab8 100644 --- a/src/webSockets/WebSockets.js +++ b/src/webSockets/WebSockets.js @@ -11,12 +11,21 @@ const { io } = require("socket.io-client"); export class WebSockets { constructor() { - this.socket = io("/notifications"); - this.socket.on("disconnect", (reason) => {}); - this.socket.on("notification", (notification) => { - // TODO call dispatch + this.socket = io("/notifications", { + path: "/reforis/reforis-ws", + }); + this.connection = null; + this.socket.on("disconnect", (reason) => { + this.connection = null; + console.log(`SocketIO disconnected (${reason})`); + }); + this.socket.on("notification", (message) => { + this.dispatch(message); + }); + this.socket.on("connect", (connection) => { + this.connection = connection; + console.log(`SocketIO connected.`); }); - this.socket.on("connect", (socket) => {}); // callbacks[module][action] this.callbacks = {}; @@ -42,27 +51,18 @@ export class WebSockets { } if (Object.keys(this.callbacks[module]).length === 0) { - this.unsubscribe(module); delete this.callbacks[module]; } return this; } - send(action, params) { - // TODO may not be required - const payload = JSON.stringify({ action, params }); - this.waitForConnection(() => { - this.ws.send(payload); - }); - return this; - } - dispatch(json) { if (!json.module) return; let chain; try { + console.log(`Handling: ${json}`); chain = this.callbacks[json.module][json.action]; } catch (error) { if (error instanceof TypeError) { diff --git a/src/webSockets/hooks.js b/src/webSockets/hooks.js index fcaa4f8..d15c24d 100644 --- a/src/webSockets/hooks.js +++ b/src/webSockets/hooks.js @@ -32,7 +32,7 @@ export function useWSForisModule( setData(message.data); } - ws.subscribe(module).bind(module, action, callback); + ws.bind(module, action, callback); return () => { ws.unbind(module, action, callback);