-
-
Save sarasantos/a62734b3e64adfce1e7da1f55ad75f22 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'); | |
websocket.send("states"); | |
} | |
function onClose(event) { | |
console.log('Connection closed'); | |
setTimeout(initWebSocket, 2000); | |
} | |
function onMessage(event) { | |
var myObj = JSON.parse(event.data); | |
console.log(myObj); | |
for (i in myObj.gpios){ | |
var output = myObj.gpios[i].output; | |
var state = myObj.gpios[i].state; | |
console.log(output); | |
console.log(state); | |
if (state == "1"){ | |
document.getElementById(output).checked = true; | |
} | |
else{ | |
document.getElementById(output).checked = false; | |
} | |
} | |
console.log(event.data); | |
} | |
// Send Requests to Control GPIOs | |
function toggleCheckbox (element) { | |
console.log(element.id); | |
websocket.send(element.id); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment