function handleRequest(id, url) { var button = document.getElementById(id); var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { button.classList.remove("pure-button-primary"); button.classList.add("success"); button.innerHTML = (id === 'tc_on') ? "Enabled!" : "Disabled!"; button.style.backgroundColor = "green"; setTimeout(function () { button.classList.remove("success"); button.classList.add("pure-button-primary"); button.innerHTML = (id === 'tc_on') ? "ON" : "OFF"; button.style.backgroundColor = ""; }, 2000); console.log('Data successfully sent to server!'); } else { button.classList.remove("pure-button-primary"); button.classList.add("error"); button.innerHTML = "Error!"; button.style.backgroundColor = ""; setTimeout(function () { button.classList.remove("error"); button.classList.add("pure-button-primary"); button.innerHTML = (id === 'tc_on') ? "ON" : "OFF"; button.style.backgroundColor = ""; }, 2000); showToast('Error while sending data to server.', 'error'); console.log('Error while sending data to server.'); } } }; xhr.send(); } function addButtonClickListener(id, url) { var link = document.getElementById(id); link.addEventListener('click', function (event) { event.preventDefault(); handleRequest(id, url); document.getElementById(id).classList.add('pure-button-primary'); document.getElementById(id === 'tc_on' ? 'tc_off' : 'tc_on').classList.remove('pure-button-primary'); }); } addButtonClickListener('tc_on', 'http://{{IP_ADDRESS}}/?tc=true'); addButtonClickListener('tc_off', 'http://{{IP_ADDRESS}}/?tc=false'); let timeoutId; function sendSliderValue(x) { x = x - 1; clearTimeout(timeoutId); timeoutId = setTimeout(() => { var value = document.getElementById(`bri${x}`).value; var trans = document.getElementById('transition').value; if (isNaN(trans) || parseInt(trans) != trans) { showToast("Error the transition is not a valid integer number.", "error"); return false; } var url = `http://{{IP_ADDRESS}}/?bri${x}=${value}&transition=`+parseInt(trans); fetch(url).then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } }).catch(error => { showToast(`Error sending slider value to ${url}: ${error}`, 'error'); console.error(`Error sending slider value to ${url}: ${error}`); }); }, 500); } function rgb2Hex(r, g, b) { var hex = "#" + ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1); return hex; }