Skip to content

Instantly share code, notes, and snippets.

@sarasantos
Created February 19, 2021 16:29
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/5285fdf3dd51373e9b47ec3ecdbfe3a2 to your computer and use it in GitHub Desktop.
Save sarasantos/5285fdf3dd51373e9b47ec3ecdbfe3a2 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();
getCurrentValue1();
getCurrentValue2();
getCurrentValue3();
}
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');
}
function onClose(event) {
console.log('Connection closed');
setTimeout(initWebSocket, 2000);
}
function onMessage(event) {
console.log(event.data);
}
function getCurrentValue1() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pwmSlider1").value = this.responseText;
document.getElementById("textSliderValue1").innerHTML = this.responseText;
}
};
xhr.open("GET", "/currentValue1", true);
xhr.send();
}
function getCurrentValue2() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pwmSlider2").value = this.responseText;
document.getElementById("textSliderValue2").innerHTML = this.responseText;
}
};
xhr.open("GET", "/currentValue2", true);
xhr.send();
}
function getCurrentValue3() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pwmSlider3").value = this.responseText;
document.getElementById("textSliderValue3").innerHTML = this.responseText;
}
};
xhr.open("GET", "/currentValue3", true);
xhr.send();
}
function updateSliderPWM() {
var sliderValue1 = document.getElementById("pwmSlider1").value;
document.getElementById("textSliderValue1").innerHTML = sliderValue1;
console.log(sliderValue1);
websocket.send("1s"+sliderValue1.toString());
var sliderValue2 = document.getElementById("pwmSlider2").value;
document.getElementById("textSliderValue2").innerHTML = sliderValue2;
console.log(sliderValue2);
websocket.send("2s"+sliderValue2.toString());
var sliderValue3 = document.getElementById("pwmSlider3").value;
document.getElementById("textSliderValue3").innerHTML = sliderValue3;
console.log(sliderValue3);
websocket.send("3s"+sliderValue3.toString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment