Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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