Poll and get MQTT messages from AJAX in browser

最后都变了- 提交于 2021-01-28 05:06:09

问题


Beginner here.

Ok, I'm trying to accomplish a simple data flow:

MQTT-Data-source ---> MQTT Broker ---> NodeJS-MQTT-Client ---> AJAX-on-web-browser (polling-every-3-seconds)

  • I want to be able to get the MQTT message and show it in the AJAX component in browser side.
  • Secondly, on console.log(mqttMessage);, how do i clear previous messages? Because on console I can see all previous data as well as the new data adding up.

I'm using mqtt.js for my nodejs mqtt support on Express.

//Server.js
var mqtt            = require('mqtt');
...
...

var getData = function() {
    mqttClient.subscribe(mqttTopic);

    mqttClient.on('message', function(topic, message) {
        mqttMessage = message.toString();
        console.log(mqttMessage);
    })

    return mqttMessage;
}

app.get('/pollData', function(req, res) {
    res.send(getData());
});

And on a simple html page, I've got:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
    $(document).ready(
        function() {
            setInterval(function() {
                    $.get('/pollData', function(res) {
                        $('#data').text(res);
                });
            }, 3000);
        }
    );
</script>

回答1:


This is a REALLY bad pattern, you should just use the Paho MQTT Javascript client and subscribe to the topic directly from the web page.

But if you really want to do it this way then the following is the right way to do it.

//Server.js
var mqtt            = require('mqtt');
...
...

var mqttMessage;

mqttClient.subscribe(mqttTopic);

mqttClient.on('message', function(topic, message) {
    mqttMessage = message.toString();
    console.log(mqttMessage);
})


app.get('/pollData', function(req, res) {
    if (mqttMessage) {
        res.send(mqttMessage);
    } else {
        res.status(404).send();
    }
});

This is because you don't read a value from a MQTT topic, you have to wait until somethings is published on that topic, then the broker will forward it to all subscribers. So in the code above you set up the connection, subscribe, then when a message is published it is stored in the mqttMessage variable, then if it's not undefined it can be returned by the REST end point.



来源:https://stackoverflow.com/questions/46341080/poll-and-get-mqtt-messages-from-ajax-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!