Hi i want to set the mqtt-topic to a specific value when a specific checkbox is checked. See my code here: my code I think I need a submit-button to send a value to my HTML document. However, I have no idea. I have to set the topic before the script is executed. The topic is stored in the variable options (js-part).

form-part

    <form>  
    <div id="measurement" style="float:left">
    <label for="measurement"><b>Measurement-Type:</b><br />
        <input type="checkbox" id="temperature" name="temperature">temperature<br />
        <input type="checkbox" id="moisture" name="moisture">moisture<br />
        <input type="checkbox" id="conductivity" name="conductivity">conductivity<br />
        <input type="checkbox" id="light_intensity" name="light_intensity">light_intensity<br />
        <input type="checkbox" id="pressure" name="pressure">pressure<br />
        <input type="checkbox" id="ppm" name="ppm">ppm<br />
        <input type="checkbox" id="intensity" name="intensity">intensity<br />
        <input type="checkbox" id="um" name="um">um<br />
    </label>
    </div>
    <div id="set" style="float:left">
        <input type="submit" onclick="topic();" />
    </div>
</form> 

script-part

var topic = '';

function topic() {
    //if id="temperature" set var topic to "//////temperature"
    if (document.getElementById("temperature").checked == true) {
      document.getElementById("temperature").checked;
      topic = "//////temperature"
    }

var options = {
    timeout: 3,
    userName: "user",
    password: "pw",
    onSuccess: function () {
        console.log("mqtt broker connected");

        //here is the topic variable
        client.subscribe(topic, {qos: 0});
        },
        onFailure: function (message) {
            console.log("Connection failed: " + message.errorMessage);
    }
};

i dont know, i think this code here is not useful, but I have to put one here

1 Answers

0
swmcdonnell On

1) First, you're missing a curly brace to end the function topic(). I'm assuming you don't want the options variable inside the topic function.

function topic() {
    //if id="temperature" set var topic to "//////temperature"
    if (document.getElementById("temperature").checked == true) {
      document.getElementById("temperature").checked;
      topic = "//////temperature"
    }
}  // <<- ADD THIS HERE

2) What you don't show are the statements where you connect to the MQTT server and where the client object gets created. The functions you embedded in the options variable are callbacks for those statements. It's important because of the sequence of events. Depending on when you connect, topic might or might not be defined. It's not clear from your code. For example, where are:

client = new Paho.MQTT.Client(MQTT_ADDRESS, MQTT_PORT, MQTT_CLIENT_ID);
client.connect(options);

3) You might also want to check the value of topic before you subscribe in case it's empty:

if (topic !== '') client.subscribe(topic);

Hope this helps.