On the javascript side I created a check for any possible readystate of the websocket connection with a callback to wait and a open/close for the websocket and put some printouts in the console. That's a bit overkill, but at least it kinda works. It still doesn't lift the mystery of the handlePhysicalButton() loop playing hard to get.
function sendMessage(msg){
// Wait until the state of the socket is not ready and send the message when it is...
waitForSocket(websock, function(){
console.log("sendMsg(): (" + msg + ")");
websock.send(msg);
});
}
// Make the function wait until the connection is made...
function waitForSocket(websock, callback){
setTimeout(
function() {
switch(websock.readyState) {
case 0:
console.log("websock.readyState = " + websock.readyState + " - The connection is not yet open")
console.log("Waiting for connection...")
waitForSocketConnection(websock, callback);
break;
case 1:
console.log("Case 1: websock.readyState = " + websock.readyState + " - The connection is open and ready to communicate")
console.log("Connection is made")
if(callback != null){
callback();
}
break;
case 2:
console.log("websock.readyState = " + websock.readyState + " - The connection is in the process of closing.")
console.log("Waiting for connection...")
waitForSocketConnection(websock, callback);
break;
case 3:
console.log("websock.readyState = " + websock.readyState + " - The connection is closed or couldn't be opened.")
console.log("Restarting Websocket...")
start();
break;
default:
console.log("¯\\_(ツ)_/¯");
}
}, 1000);