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.
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: