Created
September 24, 2022 11:03
-
-
Save sarasantos/be179720497958b3798347d7342002f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var gateway = `ws://${window.location.hostname}/ws`; | |
var websocket; | |
window.addEventListener('load', onload); | |
function onload(event) { | |
initWebSocket(); | |
} | |
function initWebSocket() { | |
console.log('Trying to open a WebSocket connection…'); | |
websocket = new WebSocket(gateway); | |
websocket.onopen = onOpen; | |
websocket.onclose = onClose; | |
websocket.onmessage = onMessage; | |
} | |
function onOpen(event) { | |
console.log('Connection opened'); | |
getCurrentValue(); | |
} | |
function onClose(event) { | |
console.log('Connection closed'); | |
setTimeout(initWebSocket, 2000); | |
} | |
function onMessage(event) { | |
console.log(event.data); | |
var sliderValue = event.data; | |
document.getElementById("pwmSlider").value = sliderValue; | |
document.getElementById("textSliderValue").innerHTML = sliderValue; | |
} | |
function getCurrentValue(){ | |
var xhr = new XMLHttpRequest(); | |
xhr.onreadystatechange = function() { | |
if (this.readyState == 4 && this.status == 200) { | |
document.getElementById("pwmSlider").value = this.responseText; | |
document.getElementById("textSliderValue").innerHTML = this.responseText; | |
} | |
}; | |
xhr.open("GET", "/currentValue", true); | |
xhr.send(); | |
} | |
function updateSliderPWM(element) { | |
var sliderValue = document.getElementById("pwmSlider").value; | |
document.getElementById("textSliderValue").innerHTML = sliderValue; | |
console.log(sliderValue); | |
websocket.send(sliderValue); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment