我可以动态更改paho websocked中的订阅主题吗?

时间:2017-10-24 10:24:04

标签: jquery websocket mqtt paho

我使用paho web socket javascript接收来自所有主题的MQTT消息。我能够从运行时订阅的消息中获取消息,但我需要使用选择框动态更改主题并仅接收来自所选主题的消息。

我尝试了几种解决方案并进行了全面搜索,但没有成功。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Mosquitto Websockets</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta charset="utf-8">
    <script src="mqttws31.js" type="text/javascript"></script>
    <script src="jquery.min.js" type="text/javascript"></script>
    <script src="config.js" type="text/javascript"></script>

    <script type="text/javascript">
    var mqtt;
    var reconnectTimeout = 2000;
    var selectedtopic='#';
    function MQTTconnect(selectedtopic) {
    if (typeof path == "undefined") {
        path = '/mqtt';
    }
    mqtt = new Paho.MQTT.Client(
            host,
            port,
            path,
            "web_" + parseInt(Math.random() * 100, 10)
    );
        var options = {
            timeout: 3,
            useSSL: useTLS,
            cleanSession: cleansession,
            onSuccess: onConnect,
            onFailure: function (message) {
                $('#status').val("Connection failed: " + message.errorMessage + "Retrying");
                setTimeout(MQTTconnect, reconnectTimeout);
            }
        };

        mqtt.onConnectionLost = onConnectionLost;
        mqtt.onMessageArrived = onMessageArrived;

        if (username != null) {
            options.userName = username;
            options.password = password;
        }
        console.log("Host="+ host + ", port=" + port + ", path=" + path + " TLS = " + useTLS + " username=" + username + " password=" + password);
        mqtt.connect(options);
    }

    function onConnect() {
        $('#status').val('Connected to ' + host + ':' + port + path);
        // Connection succeeded; subscribe to our topic
        console.log("subscribed to "+selectedtopic);
        mqtt.subscribe(selectedtopic, {qos: 0});
        $('#topic').val(selectedtopic);
    }

    function onConnectionLost(response) {
        setTimeout(MQTTconnect, reconnectTimeout);
        $('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");

    };

    function onMessageArrived(message) {

        var topic = message.destinationName;
        var payload = message.payloadString;

        $('#ws').prepend('<li>' + topic + ' = ' + payload + '</li>');
    };


    $(document).ready(function() {
        MQTTconnect(selectedtopic);
        $('#topic').change(function()
        {
            selectedtopic = $(this).val();
            console.log("change "+selectedtopic);
        })
    });

    </script>
  </head>
  <body>
    <h1>Things</h1>
    <div>
        <div>Location 
            <select id="topic">
                <option value="#">All</option>
                <option value="emergency-room/#">Emergency room</option>
                <option value="ward/#">Ward</option>
            </select>
            Status: <input type='text' id='status' size="80" disabled /></div>

            <ul id='ws' style="font-family: 'Courier New', Courier, monospace;"></ul>
    </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:2)

Paho Javascript客户端同时具有subscribeunsubscribe方法,可让您更改应用于传入邮件的主题过滤器。

这样的事情应该有效:

$(document).ready(function() {
    MQTTconnect(selectedtopic);
    $('#topic').change(function()
    {
        mqtt.unsubscribe(selectedtopic);
        selectedtopic = $(this).val();
        mqtt.subscribe(selectedtopic);
        console.log("change "+selectedtopic);
    })
});