From c4356cf3541ef1f17390b4319a20f60afb061122 Mon Sep 17 00:00:00 2001 From: jimmy Date: Sun, 18 May 2025 21:26:33 +1200 Subject: [PATCH] Switch to web socket --- src/static/main.js | 63 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/src/static/main.js b/src/static/main.js index 7656323..99db040 100644 --- a/src/static/main.js +++ b/src/static/main.js @@ -3,6 +3,69 @@ let brightnessTimeout; let colorTimeout; let color2Timeout; +// Function to update the connection status indicator +function updateConnectionStatus(status) { + if (!connectionStatusElement) { + connectionStatusElement = document.getElementById("connection-status"); + } + if (connectionStatusElement) { + connectionStatusElement.className = ""; // Clear existing classes + connectionStatusElement.classList.add(status); + // Optionally, you could also update text content based on status + // connectionStatusElement.textContent = status.charAt(0).toUpperCase() + status.slice(1); + } +} + +// Function to establish WebSocket connection +function connectWebSocket() { + // Determine the WebSocket URL based on the current location + const wsUrl = `ws://${window.location.host}/ws`; + ws = new WebSocket(wsUrl); + + updateConnectionStatus("connecting"); // Indicate connecting state + + ws.onopen = function (event) { + console.log("WebSocket connection opened:", event); + updateConnectionStatus("open"); // Indicate open state + // Optionally, you could send an initial message here + }; + + ws.onmessage = function (event) { + console.log("WebSocket message received:", event.data); + }; + + ws.onerror = function (event) { + console.error("WebSocket error:", event); + updateConnectionStatus("closed"); // Indicate error state (treat as closed) + }; + + ws.onclose = function (event) { + if (event.wasClean) { + console.log( + `WebSocket connection closed cleanly, code=${event.code}, reason=${event.reason}`, + ); + updateConnectionStatus("closed"); // Indicate closed state + } else { + console.error("WebSocket connection died"); + updateConnectionStatus("closed"); // Indicate closed state + } + // Attempt to reconnect after a delay + setTimeout(connectWebSocket, 1000); + }; +} + +// Function to send data over WebSocket +function sendWebSocketData(data) { + if (ws && ws.readyState === WebSocket.OPEN) { + console.log("Sending data over WebSocket:", data); + ws.send(JSON.stringify(data)); + } else { + console.error("WebSocket is not connected. Cannot send data:", data); + // You might want to queue messages or handle this in a different way + } +} + +// Keep the post and get functions for now, they might still be useful async function post(path, data) { console.log(`POST to ${path}`, data); try {