Search code examples
javascripthtmlmqttpaho

Paho MQTT client keeps disconnecting on page load


I am pretty sure this is just an organizational issue, but I am having problems finding anyone who is experiencing the same thing that I am.

I have a website which will have multiple pages that will be using an MQTT client to publish and subscribe to topics. Seeing as I don't want to have to the initialization process for every HTML doc, I created controller.js:

var mqtt;
var reconnectTimeout = 2000;
var host = 'mqtt.eclipseprojects.io/mqtt';
var port = 80;

function onFailure(message) {
    console.log("bruh daed");
    setTimeout(MQTTconnect, reconnectTimeout);
}

function onConnect() {
    connected_flag = 1;
    mqtt.subscribe("#"); // At this point I am hoping to get messages from anything
    console.log(mqtt.isConnected());
    console.log("Connected");
}

function onConnectionLost() {
    alert("Connection Lost!!!");
}

function onMessageArrived() {
    console.log(msg);
    out_msg = "Message received " + msg.payloadString + "<br>";
    out_msg = out_msg + "Message received Topic " + msg.destinationName;
    console.log(out_msg);
}

function MQTTconnect() {

    mqtt = new Paho.MQTT.Client(host, port, "byu_ssdd" + parseInt(Math.random() * 100, 10));

    var options = {
        onSuccess: onConnect,
        onFailure: onFailure,
        keepAliveInterval: 100
    };

    mqtt.onConnectionLost = onConnectionLost;
    mqtt.onMessageArrived = onMessageArrived;
    mqtt.connect(options);
    return false;
}

function send_message_info(info) {
    var topic = "byu_ssdd/commands";
    message = new Paho.MQTT.Message(info);
    message.destinationName = topic;
    console.log(mqtt);
    if (mqtt.isConnected()) {
        mqtt.send(message);
        console.log(message);
    }
    else {
        mqtt.connect();
        console.log("I am not connected!!!");
    }

    alert("Message sent!");
    return false;
}

function test() {
    alert("Reached!");
}

MQTTconnect();

I include this script in my HTML file like so:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta name="description" content="" />
    <meta name="author" content="" />
    <title>Demos</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
    <script type="text/javascript" src="js/controller.js"></script>
    <!-- Favicon-->
    <link rel="icon" type="image/x-icon" href="assets/favicon.ico" />
    <!-- Bootstrap icons-->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" rel="stylesheet" />
    <!-- Core theme CSS (includes Bootstrap)-->
    <link href="css/styles.css" rel="stylesheet" />
</head>

<body style="background-color: antiquewhite;">

    <!-- Header-->
    <header class="bg-dark py-5 sev">
        <div class="container px-4 px-lg-5 my-5">
            <div class="text-center text-white">
                <h1 class="display-4 fw-bolder" style="color: rgb(255, 0, 0); text-shadow: 1px 0px 5px #ff000070;">Display</h1>
            </div>
        </div>
    </header>
    <!-- Section-->
    <section class="py-5">
        <div class="container px-4 px-lg-5 mt-5">
            <div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center">


                <div class="col mb-5">
                    <a href="#" style="text-decoration: none;">
                        <div onclick="send_message_info('banana')" class="card d-flex h-150 d-flex align-items-center justify-content-center"
                            style="background-image: url('assets/demos.png'); background-repeat: no-repeat; background-position: center; background-size: 50%; background-color: black;">
                            <h2 class="fw-bolder" style="padding: 20px; color: antiquewhite;">Demos</h2>
                        </div>
                    </a>
                </div>
                <div class="col mb-5">
                    <a href="games.html" style="text-decoration: none;">
                        <div class="card d-flex h-150 d-flex align-items-center justify-content-center"
                            style="background-image: url('assets/game.jpg'); background-repeat: no-repeat; background-position: center; background-size:220%; background-color: black;">
                            <h2 class="fw-bolder" style="padding: 20px; color: antiquewhite;">Games</h2>
                        </div>
                    </a>
                </div>
            </div>
    </section>
    <!-- Bootstrap core JS-->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Core theme JS-->
    <script src="js/scripts.js"></script>
</body>

</html>

I have been playing around with the idea that maybe its where I have MQTTConnect() in controller.js and have tried various ways to include it in different places, but to no avail.

The current behavior is that if I click on the div with the id of demos as the page is loading, I can click on a div and have its send a message correctly, but within the period of like a second, I get the alert that I have been disconnected from the broker. What am I doing wrong here?


Solution

  • Your problem is here:

    function onMessageArrived() {
        console.log(msg);
        out_msg = "Message received " + msg.payloadString + "<br>";
        out_msg = out_msg + "Message received Topic " + msg.destinationName;
        console.log(out_msg);
    }
    

    msg is not defined so onMessageArrived will throw an error which leads to the disconnect. The fix is pretty simple:

    function onMessageArrived(msg) {
        console.log(msg);
        out_msg = "Message received " + msg.payloadString + "<br>";
        out_msg = out_msg + "Message received Topic " + msg.destinationName;
        console.log(out_msg);
    }
    

    Note that you would have found this yourself if you output the error:

    function onConnectionLost(err) {
        console.log("Connection Lost!!!", err);
    }
    

    Here is a working fiddle (have made a few changes to get it working as a fiddle and changed the topic as subscribing to # on the test broker tends to overload things!).