Problem connecting to CloudMqtt with variables

1

Friends I have the following code in html, where I connect to CloudMqtt, the problem is that I am passing the user, password, port and host through the code. I am trying to make a form for the user to enter such data but I can not get it to work, I tried to do it through document.getElementsByName or by Id, but it does not work, I do not know what I could be doing wrong. In fact the code as it is below works, if I change it for the assigned variables it stops doing it, I get the following:

  

index22.html: 77 Uncaught ReferenceError: ls is not defined       at index22.html: 77,

which corresponds to

var client = new Paho.MQTT.Client(ls, lss, clientId);  

by doing, for example, an alert with the variables alert (js + "" + jss); He shows them to me, but he does not make the connection, he throws the previous error. Thank you in advance.

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

<head>
  <meta charset="UTF-8">
  <title>Dashboard MQTT</title>
  <link rel="shortcut icon" type="image/x-icon" href="Imagenes/iot.png">
  <script src='https://api.cloudmqtt.com/js/mqttws31.js' type='text/javascript'>
  </script>
  <!-- https://api.cloudmqtt.com/sso/js/mqttws31.js -->
</head>

<body>

  <header>

  </header>
  <br/>
  <h1>WEBSOCKET</h1><br />

  <div class="table">
    <form action="" method="post">
      <h2>Ingrese los datos</h2>
      <label for="host">Host:</label>
      <input type="text" id="host" name="host"><br/>
      <label for="puerto">Puerto:</label>
      <input type="text" id="puerto" name="puerto"><br/>
      <input type="submit" onclick="leerdatosformulario()" value="ENVIAR">
    </form>
  </div>
  <script>
    function leerdatosformulario() {
      ls = document.getElementById("host").value;
      lss = document.getElementById("puerto").value;
    }

    usuario = 'Prueba';
    contrasena = '123';
    puerto = 33848;
    host = 'm12.cloudmqtt.com';

    function onConnect() {
      // Once a connection has been made, make a subscription and send a message.
      console.log("Conexion realizada con el servidor");
      client.subscribe("#");
      console.log("Conectado como " + usuario + " a través del puerto 8083");
    }

    // called when the client loses its connection
    function onConnectionLost(responseObject) {
      if (responseObject.errorCode !== 0) {
        console.log("onConnectionLost:", responseObject.errorMessage);
        setTimeout(function() {
          client.connect()
        }, 5000);
      }
    }

    // called when a message arrives
    function onMessageArrived(message) {

      var topico = document.getElementsByName("topico-pub")[0].value;
      if (message.destinationName == '/' + usuario + '/' + topico) { //acá coloco el topic
        document.getElementById("mensaje-pub").textContent = message.payloadString;
        console.log("Mensaje recibido:" + '/' + usuario + '/' + topico + " : " + message.payloadString);
      }
    }

    function onFailure(invocationContext, errorCode, errorMessage) {
      var errDiv = document.getElementById("error");
      errDiv.textContent = "Could not connect to WebSocket server, most likely you're behind a firewall that doesn't allow outgoing connections to port 33848";
      errDiv.style.display = "block";
    }

    var clientId = "ws" + Math.random();
    // Create a client instance
    var client = new Paho.MQTT.Client(ls, lss, clientId);

    // set callback handlers
    client.onConnectionLost = onConnectionLost;
    client.onMessageArrived = onMessageArrived;

    // connect the client
    client.connect({
      useSSL: true,
      userName: usuario,
      password: contrasena,
      onSuccess: onConnect,
      onFailure: onFailure
    });
  </script>

</body>

</html>
    
asked by HAROLD LEONARDO HOYOS CARRILLO 07.02.2018 в 23:10
source

2 answers

0

Friend in username and password because you do not have the assigned variables, otherwise the function where you capture if you are returning values. test with a console.log (ls); to see if you are capturing that variable of your code

    
answered by 07.02.2018 в 23:17
0

The problem is that the connection is made when the page is loaded, but the values that you use for the connection are not read until the button is clicked (in the function leerdatosformulario ). You should restructure the code (move the connection into a function and only call when the values are filled).

Basically the solution is to move everything after the function onFailure (outside the functions) and put it at the end of the function leerdatosformulario() . In this way the variables will be instantiated when the connection is made.

This code should work for you:

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

<head>
  <meta charset="UTF-8">
  <title>Dashboard MQTT</title>
  <link rel="shortcut icon" type="image/x-icon" href="Imagenes/iot.png">
  <script src='https://api.cloudmqtt.com/js/mqttws31.js' type='text/javascript'>
  </script>
  <!-- https://api.cloudmqtt.com/sso/js/mqttws31.js -->
</head>

<body>

  <header>

  </header>
  <br/>
  <h1>WEBSOCKET</h1><br />

  <div class="table">
    <form action="" method="post">
      <h2>Ingrese los datos</h2>
      <label for="host">Host:</label>
      <input type="text" id="host" name="host"><br/>
      <label for="puerto">Puerto:</label>
      <input type="text" id="puerto" name="puerto"><br/>
      <input type="submit" onclick="leerdatosformulario()" value="ENVIAR">
    </form>
  </div>
  <script>
    usuario = 'Prueba';
    contrasena = '123';
    puerto = 33848;
    host = 'm12.cloudmqtt.com';

    function leerdatosformulario() {
      ls = document.getElementById("host").value;
      lss = document.getElementById("puerto").value;

      var clientId = "ws" + Math.random();
      // Create a client instance
      var client = new Paho.MQTT.Client(ls, parseInt(lss), clientId);

      // set callback handlers
      client.onConnectionLost = onConnectionLost;
      client.onMessageArrived = onMessageArrived;

      // connect the client
      client.connect({
        useSSL: true,
        userName: usuario,
        password: contrasena,
        onSuccess: onConnect,
        onFailure: onFailure
      });
    }

    function onConnect() {
      // Once a connection has been made, make a subscription and send a message.
      console.log("Conexion realizada con el servidor");
      client.subscribe("#");
      console.log("Conectado como " + usuario + " a través del puerto 8083");
    }

    // called when the client loses its connection
    function onConnectionLost(responseObject) {
      if (responseObject.errorCode !== 0) {
        console.log("onConnectionLost:", responseObject.errorMessage);
        setTimeout(function() {
          client.connect()
        }, 5000);
      }
    }

    // called when a message arrives
    function onMessageArrived(message) {

      var topico = document.getElementsByName("topico-pub")[0].value;
      if (message.destinationName == '/' + usuario + '/' + topico) { //acá coloco el topic
        document.getElementById("mensaje-pub").textContent = message.payloadString;
        console.log("Mensaje recibido:" + '/' + usuario + '/' + topico + " : " + message.payloadString);
      }
    }

    function onFailure(invocationContext, errorCode, errorMessage) {
      var errDiv = document.getElementById("error");
      errDiv.textContent = "Could not connect to WebSocket server, most likely you're behind a firewall that doesn't allow outgoing connections to port 33848";
      errDiv.style.display = "block";
    }
  </script>

</body>

</html>
    
answered by 08.02.2018 в 00:04