Search code examples
node.jssocket.iomessagemqtt

Messages not received using node.js MQTT client with socket.io


I am using socket.io, node.js and the node.js MQTT client to connect to a broker running on A-MQ from an HTMLS page. I can successfully connect to the broker and subscribe to the topics I need, but I never get any messages back from the topics even though several are enqueued.

Here is my code:

subscribe.js

var sys = require('sys');
var net = require('net');
var mqtt = require('mqtt');

var io  = require('socket.io').listen(5000);
io.set('origins', '*:*');

var client = mqtt.connect("mqtt:admin:admin@//localhost:1883");

io.sockets.on('connection', function (socket) {
  socket.on('subscribe', function (data) {
    console.log('Subscribing to '+data.topic);
    socket.join(data.topic);
    client.subscribe(data.topic);
  });
});

client.addListener('mqttData', function(topic, payload){
  sys.puts(topic+'='+payload);
  io.sockets.emit('mqtt',{'topic':String(topic),
    'payload':String(payload)});
});

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>IoT Demo</title>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="js/socket.io.js"></script>
<script type="text/javascript">
  var socket = io.connect('http://localhost:5000');
    socket.on('connect', function () {
      socket.on('mqtt', function (msg) {
        var elmarr=msg.topic.split("/");
        var elm=elmarr[3];
        console.log(msg.topic+' '+msg.payload);
        $('#'.concat(elm)).html(msg.payload);
     });
     socket.emit('subscribe',{topic:'customerenter'});
     socket.emit('subscribe',{topic:'customermove'});
     socket.emit('subscribe',{topic:'customerexit'});
    });
</script>
</head>
<body>
<div style="position: absolute; top: 5px; left: 5px;">
</div>
</body>
</html>

When I debug in Chrome,

socket.on('mqtt', function (msg)

is never executed.

Any thoughts?

Thanks, Ted


Solution

  • Assuming you using the Mqtt client from npm (https://www.npmjs.com/package/mqtt) then the mqtt client should have a on 'message' callback set to handle incoming messages, not mqttData listener

    client.on('message', function(topic, message){
      sys.puts(topic+'='+message);
      io.sockets.emit('mqtt',{'topic':String(topic),
        'payload':String(message)});
    });