Reconnect to MQTT broker automatically

master
0xee 2019-11-09 09:10:06 +01:00
parent 2d40ab72ff
commit 4e6b2307dd
2 changed files with 142 additions and 129 deletions

View File

@ -1,148 +1,163 @@
// Called after form input is processed
function startConnect(brokerUri) {
// Generate a random client ID
clientId = "clientId-" + parseInt(Math.random() * 100);
document.getElementById("wrapper").classList.add("wrapper-error");
document.getElementById("wrapper").classList.remove("wrapper-ok");
// Called after form input is processed
function startConnect() {
// Generate a random client ID
clientId = "clientId-" + parseInt(Math.random() * 1000000);
document.getElementById("wrapper").classList.add("wrapper-error");
document.getElementById("wrapper").classList.remove("wrapper-ok");
// Print output for the user in the messages div
document.getElementById("messages").innerHTML +=
'<span>Connecting to: ' + brokerUri+ '</span><br/>';
document.getElementById("messages").innerHTML +=
'<span>Using the following client value: ' + clientId + '</span><br/>';
// Print output for the user in the messages div
log('Connecting to: ' + window.brokerUri + ', client ID: ' + clientId);
// Initialize new Paho client connection
client = new Paho.MQTT.Client(brokerUri, clientId=clientId);
// Initialize new Paho client connection
client = new Paho.MQTT.Client(window.brokerUri, clientId=clientId);
// Set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// Set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// Connect the client, if successful, call onConnect function
client.connect({
onSuccess: onConnect,
});
}
// Connect the client, if successful, call onConnect function
client.connect({
onSuccess: onConnect,
});
// Called when the client connects
function onConnect() {
document.getElementById("wrapper").classList.remove("wrapper-error");
document.getElementById("wrapper").classList.add("wrapper-ok");
var subWidgets = document.getElementsByClassName("subscriber");
var topics = new Set()
for (var i = 0; i < subWidgets.length; i++) {
var c = subWidgets.item(i);
var topic = c.getAttribute('data-sub-topic');
topics.add(topic);
c.classList.add('widget-unset');
}
for (let topic of topics)
{
client.subscribe(topic);
}
// Subscribe to the requested topic
}
connectionCheckTimeout = setTimeout(checkConnection, 1000);
}
// Called when the client loses its connection
function onConnectionLost(responseObject) {
document.getElementById("wrapper").classList.remove("wrapper-ok");
document.getElementById("wrapper").classList.add("wrapper-error");
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost: " + responseObject.errorMessage);
}
}
function log(msg) {
console.log(msg);
//document.getElementById("messages").innerHTML += '<span>' + msg + '</span><br/>';
}
function getByPath(obj, path) {
var current=obj;
path.split('.').forEach(function(p){ current = current[p]; });
return current;
}
function checkConnection(){
clearTimeout(connectionCheckTimeout);
if (!client.isConnected()) {
//log("Error connecting to broker");
startConnect();
}
}
// Called when a message arrives
function onMessageArrived(message) {
var views = document.getElementsByClassName(message.destinationName + "-value");
for (var i = 0 ; i < views.length; i++) {
var view = views.item(i);
if (view.classList.contains("update-policy-replace-content")) {
view.innerHTML = message.payloadString;
} else if(view.classList.contains("update-policy-append-content")) {
view.innerHTML += message.payloadString + "<br/>";
view.scrollTop = view.scrollHeight;
} else if(view.classList.contains("update-policy-add-row")) {
var now = (new Date()).toLocaleTimeString();
view.innerHTML = "<tr><td>"+ now + "</td><td>" +message.payloadString + "</td></tr>" + view.innerHTML;
} else if(view.classList.contains("update-policy-update-value")) {
jsonPath = view.getAttribute('data-value-path');
if (jsonPath) {
view.value = getByPath(JSON.parse(message.payloadString),
jsonPath);
} else {
view.value = message.payloadString;
}
view.onchange();
}
}
// Called when the client connects
function onConnect() {
clearTimeout(connectionCheckTimeout);
document.getElementById("wrapper").classList.remove("wrapper-error");
document.getElementById("wrapper").classList.add("wrapper-ok");
var subWidgets = document.getElementsByClassName("subscriber");
var topics = new Set()
for (var i = 0; i < subWidgets.length; i++) {
var c = subWidgets.item(i);
var topic = c.getAttribute('data-sub-topic');
topics.add(topic);
c.classList.add('widget-unset');
}
for (let topic of topics)
{
client.subscribe(topic);
}
// Subscribe to the requested topic
}
var widgets = document.querySelectorAll("[data-sub-topic='" + message.destinationName + "']");
for (var i = 0 ; i < widgets.length; i++) {
widgets.item(i).classList.remove("widget-unset");
}
// Called when the client loses its connection
function onConnectionLost(responseObject) {
document.getElementById("wrapper").classList.remove("wrapper-ok");
document.getElementById("wrapper").classList.add("wrapper-error");
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost: " + responseObject.errorMessage);
}
startConnect();
}
}
function getByPath(obj, path) {
var current=obj;
path.split('.').forEach(function(p){ current = current[p]; });
return current;
}
// Called when the disconnection button is pressed
function startDisconnect() {
client.disconnect();
document.getElementById("messages").innerHTML += '<span>Disconnected</span><br/>';
updateScroll(); // Scroll to bottom of window
}
// Called when a message arrives
function onMessageArrived(message) {
var views = document.getElementsByClassName(message.destinationName + "-value");
for (var i = 0 ; i < views.length; i++) {
var view = views.item(i);
if (view.classList.contains("update-policy-replace-content")) {
view.innerHTML = message.payloadString;
} else if(view.classList.contains("update-policy-append-content")) {
view.innerHTML += message.payloadString + "<br/>";
view.scrollTop = view.scrollHeight;
} else if(view.classList.contains("update-policy-add-row")) {
var now = (new Date()).toLocaleTimeString();
view.innerHTML = "<tr><td>"+ now + "</td><td>" +message.payloadString + "</td></tr>" + view.innerHTML;
} else if(view.classList.contains("update-policy-update-value")) {
jsonPath = view.getAttribute('data-value-path');
if (jsonPath) {
view.value = getByPath(JSON.parse(message.payloadString),
jsonPath);
} else {
view.value = message.payloadString;
}
view.onchange();
}
}
// Updates #messages div to auto-scroll
function updateScroll() {
var element = document.getElementById("messages");
element.scrollTop = element.scrollHeight;
}
var widgets = document.querySelectorAll("[data-sub-topic='" + message.destinationName + "']");
for (var i = 0 ; i < widgets.length; i++) {
widgets.item(i).classList.remove("widget-unset");
}
function publish(topic, value) {
var message = new Paho.MQTT.Message(value);
message.destinationName = topic;
client.send(message);
}
}
function updateContents(id, value) {
elem = document.getElementById(id);
elem.innerHTML = value;
}
// Called when the disconnection button is pressed
function startDisconnect() {
client.disconnect();
document.getElementById("messages").innerHTML += '<span>Disconnected</span><br/>';
updateScroll(); // Scroll to bottom of window
}
function init(brokerUri) {
startConnect(brokerUri);
// Updates #messages div to auto-scroll
function updateScroll() {
var element = document.getElementById("messages");
element.scrollTop = element.scrollHeight;
}
var sliders = document.getElementsByClassName("slider");
function publish(topic, value) {
var message = new Paho.MQTT.Message(value);
message.destinationName = topic;
client.send(message);
}
for (var i = 0 ; i < sliders.length; i++) {
var slider = sliders.item(i);
slider.onchange = function() {
document.getElementById(this.id + "-textual").innerHTML =
this.value;
};
slider.oninput = function() {
this.onchange()
var topic = this.getAttribute('data-pub-topic');
publish(topic, this.value);
};
}
function updateContents(id, value) {
elem = document.getElementById(id);
elem.innerHTML = value;
}
var logDeletes = document.getElementsByClassName("log-delete");
function init(brokerUri) {
window.brokerUri = brokerUri
startConnect();
for (var i = 0 ; i < logDeletes.length; i++) {
var elem = logDeletes.item(i);
elem.onclick = function() {
console.log(this.id);
table = document.getElementById(this.id + "-content");
console.log(table.id);
table.innerHTML = "";
};
}
var sliders = document.getElementsByClassName("slider");
for (var i = 0 ; i < sliders.length; i++) {
var slider = sliders.item(i);
slider.onchange = function() {
document.getElementById(this.id + "-textual").innerHTML =
this.value;
};
slider.oninput = function() {
this.onchange()
var topic = this.getAttribute('data-pub-topic');
publish(topic, this.value);
};
}
var logDeletes = document.getElementsByClassName("log-delete");
for (var i = 0 ; i < logDeletes.length; i++) {
var elem = logDeletes.item(i);
elem.onclick = function() {
console.log(this.id);
table = document.getElementById(this.id + "-content");
console.log(table.id);
table.innerHTML = "";
};
}
}
}

View File

@ -26,8 +26,6 @@
</div>
<br/>
<div id="messages"></div>
<input type="button" onclick="startConnect()" value="Connect">
<input type="button" onclick="startDisconnect()" value="Disconnect">
</div>
<br/>
</div>