diff --git a/src/static/main.js b/src/static/main.js index 73d7374..da7c0a9 100644 --- a/src/static/main.js +++ b/src/static/main.js @@ -2,155 +2,213 @@ let delayTimeout; let brightnessTimeout; let colorTimeout; let color2Timeout; -let socket; +let ws; // Variable to hold the WebSocket connection +let connectionStatusElement; // Variable to hold the connection status element -const host = window.location.host; +// 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); + } +} -async function post(path, data) { - console.log(`POST to ${path}`, data); - try { - const response = await fetch(path, { - method: "POST", - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(data) // Convert data to JSON string - }); - if (!response.ok) { - throw new Error(`HTTP error! Status: ${response.status}`); - } - } catch (error) { - console.error('Error during POST request:', error); +// 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 { + const response = await fetch(path, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(data), + }); + if (!response.ok) { + throw new Error(`HTTP error! Status: ${response.status}`); + } + } catch (error) { + console.error("Error during POST request:", error); + } } async function get(path) { - try { - const response = await fetch(path); - if (!response.ok) { - throw new Error(`HTTP error! Status: ${response.status}`); - } - return await response.json(); // Assuming you are expecting JSON response - } catch (error) { - console.error('Error during GET request:', error); + try { + const response = await fetch(path); + if (!response.ok) { + throw new Error(`HTTP error! Status: ${response.status}`); } + return await response.json(); + } catch (error) { + console.error("Error during GET request:", error); + } } async function updateColor(event) { - event.preventDefault(); - clearTimeout(colorTimeout); - colorTimeout = setTimeout(async function() { - const color = document.getElementById('color').value; - await post("/color", { color }); // Send as JSON - }, 500); + event.preventDefault(); + clearTimeout(colorTimeout); + colorTimeout = setTimeout(function () { + const color = document.getElementById("color").value; + sendWebSocketData({ color1: color }); + }, 500); } async function updateColor2(event) { - event.preventDefault(); - clearTimeout(color2Timeout); - color2Timeout = setTimeout(async function() { - const color = document.getElementById('color2').value; - await post("/color2", { color }); // Send as JSON - }, 500); + event.preventDefault(); + clearTimeout(color2Timeout); + color2Timeout = setTimeout(function () { + const color = document.getElementById("color2").value; + sendWebSocketData({ color2: color }); + }, 500); } async function updatePattern(pattern) { - await post("/pattern", { pattern }); // Send as JSON - //socket.send(JSON.stringify({"selected_pattern":pattern})) - + sendWebSocketData({ pattern: pattern }); } async function updateBrightness(event) { - event.preventDefault(); - clearTimeout(brightnessTimeout); - brightnessTimeout = setTimeout(async function() { - const brightness = document.getElementById('brightness').value; - //await post('/brightness', { brightness }); // Send as JSON - }, 500); + event.preventDefault(); + clearTimeout(brightnessTimeout); + brightnessTimeout = setTimeout(function () { + const brightness = document.getElementById("brightness").value; + sendWebSocketData({ brightness: brightness }); + }, 500); } async function updateDelay(event) { - event.preventDefault(); - clearTimeout(delayTimeout); - delayTimeout = setTimeout(async function() { - const delay = document.getElementById('delay').value; - await post('/delay', { delay }); // Send as JSON - }, 500); + event.preventDefault(); + clearTimeout(delayTimeout); + delayTimeout = setTimeout(function () { + const delay = document.getElementById("delay").value; + sendWebSocketData({ delay: delay }); + }, 500); } async function updateNumLeds(event) { - event.preventDefault(); - const numLeds = document.getElementById('num_leds').value; - await post('/num_leds', { num_leds: numLeds }); // Send as JSON + event.preventDefault(); + const numLeds = document.getElementById("num_leds").value; + sendWebSocketData({ num_leds: parseInt(numLeds) }); } -async function updateWifi(event) { - event.preventDefault(); - const ssid = document.getElementById('ssid').value; - const password = document.getElementById('password').value; - const ip = document.getElementById('ip').value; - const gateway = document.getElementById('gateway').value; - - const wifiSettings = { ssid, password, ip, gateway }; // Create JSON object - console.log(wifiSettings); - const response = await post('/wifi_settings', wifiSettings); // Send as JSON - if (response === 500) { - alert("Failed to connect to Wi-Fi"); - } +async function updateName(event) { + event.preventDefault(); + const name = document.getElementById("name").value; + sendWebSocketData({ name: name }); } function createPatternButtons(patterns) { - const container = document.getElementById('pattern_buttons'); - container.innerHTML = ''; // Clear previous buttons + const container = document.getElementById("pattern_buttons"); + container.innerHTML = ""; // Clear previous buttons - patterns.forEach(pattern => { - const button = document.createElement('button'); - button.type = 'button'; // Use 'button' instead of 'submit' - button.textContent = pattern; - button.value = pattern; - button.addEventListener('click', async function(event) { - event.preventDefault(); - await updatePattern(pattern); - }); - container.appendChild(button); + patterns.forEach((pattern) => { + const button = document.createElement("button"); + button.type = "button"; + button.textContent = pattern; + button.value = pattern; + button.addEventListener("click", async function (event) { + event.preventDefault(); + await updatePattern(pattern); }); + container.appendChild(button); + }); } -document.addEventListener('DOMContentLoaded', async function() { - document.getElementById('color').addEventListener('input', updateColor); - document.getElementById('color2').addEventListener('input', updateColor2); - document.getElementById('delay').addEventListener('input', updateDelay); - document.getElementById('brightness').addEventListener('input', updateBrightness); - document.getElementById('num_leds_form').addEventListener('submit', updateNumLeds); - document.getElementById('wifi_form').addEventListener('submit', updateWifi); - document.getElementById('delay').addEventListener('touchend', updateDelay); - document.getElementById('brightness').addEventListener('touchend', updateBrightness); +document.addEventListener("DOMContentLoaded", async function () { + // Get the connection status element once the DOM is ready + connectionStatusElement = document.getElementById("connection-status"); - document.querySelectorAll(".pattern_button").forEach(button => { - console.log(button.value); - button.addEventListener('click', async event => { - event.preventDefault(); - await updatePattern(button.value); - }); - }); + // Establish WebSocket connection on page load + connectWebSocket(); - socket = new WebSocket(`ws://${host}/settings`) - - + document.getElementById("color").addEventListener("input", updateColor); + document.getElementById("color2").addEventListener("input", updateColor2); + document.getElementById("delay").addEventListener("input", updateDelay); + document + .getElementById("brightness") + .addEventListener("input", updateBrightness); + document + .getElementById("num_leds_form") + .addEventListener("submit", updateNumLeds); + document.getElementById("name_form").addEventListener("submit", updateName); + document.getElementById("delay").addEventListener("touchend", updateDelay); + document + .getElementById("brightness") + .addEventListener("touchend", updateBrightness); + document.querySelectorAll(".pattern_button").forEach((button) => { + console.log(button.value); + button.addEventListener("click", async (event) => { + event.preventDefault(); + await updatePattern(button.value); + }); + }); }); // Function to toggle the display of the settings menu function selectSettings() { - const settingsMenu = document.getElementById('settings_menu'); - controls = document.getElementById('controls'); - settingsMenu.style.display = 'block'; - controls.style.display = 'none'; + const settingsMenu = document.getElementById("settings_menu"); + controls = document.getElementById("controls"); + settingsMenu.style.display = "block"; + controls.style.display = "none"; } function selectControls() { - const settingsMenu = document.getElementById('settings_menu'); - controls = document.getElementById('controls'); - settingsMenu.style.display = 'none'; - controls.style.display = 'block'; + const settingsMenu = document.getElementById("settings_menu"); + controls = document.getElementById("controls"); + settingsMenu.style.display = "none"; + controls.style.display = "block"; }