better connection handling in mqtt

master
vuko 2020-11-27 16:13:35 +01:00
parent ac106890ac
commit 7e2a3efe16
1 changed files with 38 additions and 13 deletions

View File

@ -61,7 +61,7 @@
<h1 id="up" style="cursor:pointer">light your space <strong style="color:var(--color-c-3)">up</strong></h1>
</header>
<div style="margin-left:auto;margin-right:auto;width:480px">
<svg width="480px" viewBox="-2 -2 18 16" >
<svg width="480px" viewBox="-1 -1 16 14" >
<g
id="layer1">
<g id="walls" >
@ -162,6 +162,7 @@
</g>
</svg>
<p id="status" style="font-family:DejaVu Sans,sans-serif;color:var(--color-p-4)">MQTT: connecting</p>
</div>
<script src="static/paho-mqtt.js"></script>
<script>
@ -176,13 +177,12 @@
config_request.send(null);
}
var onConfig = function(config) {
var lights = [];
for (i = 1; i <= 8; i++) {
id = "l" + i;
element = document.getElementById(id);
element.classList = ["light-disabled"];
lights[i] = {
"element": element,
"id" : id,
@ -192,8 +192,15 @@
}
}
function disable_lights(){
for ( i in lights ) {
lights[i].element.classList = ["light-disabled"];
}
}
disable_lights()
var name = "web-client-" + Math.round(Math.random() * 100000);
var client = new Paho.MQTT.Client(config.mqtt_server, Number(config.mqtt_port), "/", name);
var client = new Paho.MQTT.Client(config.mqtt_server, Number(config.mqtt_port), "", name);
client.onMessageArrived = function(message) {
for ( i in lights ) {
@ -209,6 +216,7 @@
};
function onConnect(){
document.getElementById("status").innerText = "MQTT: connected";
for ( i in lights ) {
light = lights[i];
if ( "mqtt_path" in light ) {
@ -218,7 +226,7 @@
return function(){
var toggle_request = new XMLHttpRequest();
toggle_request.open("POST", "/light/" + light.id + "/on/toggle", true);
toggle_request.setRequestHeader('Content-Type', 'application/json');
toggle_request.setRequestHeader("Content-Type", "application/json");
toggle_request.send(JSON.stringify(true));
};
}(light);
@ -229,21 +237,38 @@
light = lights[i];
var on_request = new XMLHttpRequest();
on_request.open("POST", "/light/" + light.id + "/on/set", true);
on_request.setRequestHeader('Content-Type', 'application/json');
on_request.setRequestHeader("Content-Type", "application/json");
on_request.send(JSON.stringify(true));
};
};
}(lights);
};
client.connect({
onSuccess: onConnect,
userName: "light",
password: "MG4Dhp6vCZjgbTzJ",
onFailure: function(response) {
client.onConnectionLost = function (code, message){
console.log("MQTT: connection lost");
console.log(code);
console.log(message);
document.getElementById("status").innerText = "MQTT: reconnecting";
disable_lights();
};
function onFailure(response) {
console.log("Failed to connect to MQTT server");
console.log(response);
}
});
mqtt_connect()
}
function mqtt_connect() {
client.connect({
onSuccess: onConnect,
userName: config.mqtt_username,
password: config.mqtt_password,
reconnect: true,
onFailure: onFailure,
});
};
mqtt_connect();
};
</script>
</html>