MQTT实时提供给Node JS中的html页面

时间:2016-03-23 06:52:08

标签: javascript jquery node.js websocket mqtt

我的路线mqtt.js包含以下内容: -

client.on('connect', function () {
    client.subscribe('shmindia');
    client.publish('shmindia', new Date());
    console.log("********************** MQTT STARTED *********************");
});

client.on('message', function (topic, message) {
    // message is Buffer 
    m = message;
    console.log(message);
   // client.end();
});

client.on('close', function () {
    console.log(" disconected");
});

router.get('/', function (req, res) {
    /*Render the index.hbs and pass the View Model*/
    var vm = {
        title: 'MQTT',
        message: [new Date(), m]
    }
    console.log(vm.message);
    res.render('mqtt/index', vm);
});

router.get('/getsensordata', function (req, res) {
    var vm = {
    data:m
    };
    res.send(vm);
});

module.exports = router;

index.hbs包含以下代码: -

<div id='container' style="width:100%; height:400px;">

</div>
<script>
    var chart;
    function requestData() {
        $.ajax({
            url: 'http://localhost:1998/mqtt/getsensordata',
            success: function (point) {
                var series = chart.series[0],
                  shift = series.data.length > 20;
                chart.series[0].addPoint(point, true, shift);
                setTimeout(requestData, 1000);
            },
            cache: false
        });
    }
    $(document).ready(function () {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                defaultSeriesType: 'spline',
                events: {
                    load: requestData
                }
            }
    });
</script>

所以,在这发生的事情是,索引文件,数据请求,然后,从服务器检索一些数据。
我期待的是当MQTT客户端发布消息时,数据应该转到index.hbs
我怎样才能实现这一点? 编辑1:我可以使用websockets,但我想隐藏到MQTT服务器的链接,登录详细信息。

1 个答案:

答案 0 :(得分:1)

不要使用AJAX来获取更新,当邮件传递到服务器时,使用纯websockets将更新从服务器端推送到客户端。

使用服务器端的express-ws模块,如下所示:

var expressWs = require('express-ws')(app); //app = express app 

expressWs.app.ws('/sensordata', function(ws, req){});
var aWss = expressWs.getWss('/sensordata');

client.on('connect', function () {
    client.subscribe('shmindia');
    client.publish('shmindia', new Date());
    console.log("********************** MQTT STARTED *********************");
});


client.on('message', function (topic, message) {
    // message is Buffer 
    m = message;
    aWss.clients.forEach(function (client) {
        client.send(m);
    });
    console.log(message);
   // client.end();
});

在网页上:

<script>
   var ws = new Websocket('ws://localhost:1998/sensordata');
   ws.onmessage = function(message){
     var series = chart.series[0],
     shift = series.data.length > 20;
     chart.series[0].addPoint(message, true, shift);
   } 
</script>