node js setinterval not working with mqtt client on connect

1.7k Views Asked by At

I have the below code to publish to a MQTT broker every 3 seconds, but it is not working:

var mqtt    = require('mqtt');
var client  = mqtt.connect('mqtt://test.mosquitto.org');
var topic   = 'test-topic';   

client.on('connect', function () {
    client.subscribe(topic);

    setInterval(function() {
        client.publish(topic, Date.now().toString());
        console.log('hello');
    }, 3000);
});

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

I can see the hello message being printed out every 3 seconds, but not my mqtt published date messages.

If I remove the setInterval function and use client.publish(...) instead, it only publishes once and exit.

Update

after removing the client.end(), it is working as expected.

2

There are 2 best solutions below

0
On

I think that Settawat Janpuk answer is the one you are looking for.

However, you could also use a module that make you publish on mqtt every x millis in a declarative way:

const mqttNow = require('mqtt-now');

const options = {
  host: 'localhost',
  interval: 500,
  actions: [
    {
      topic: 'public',
      message: 'messaggio'
    },
    {
      topic: 'random',
      message: () => ( 'random ' + Math.random() )
    }
  ]
}

mqttNow.publish(options);
0
On

In client.on('message') you need to remove client.end() because mqtt is finished when it receives the first message.