Skip to content

Instantly share code, notes, and snippets.

@sarasantos
Created September 24, 2022 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarasantos/be179720497958b3798347d7342002f5 to your computer and use it in GitHub Desktop.
Save sarasantos/be179720497958b3798347d7342002f5 to your computer and use it in GitHub Desktop.
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