Skip to content

Instantly share code, notes, and snippets.

@smching
Last active June 25, 2022 08:09
Show Gist options
  • Save smching/3582d2fbae417fc919e23b4e61c036d1 to your computer and use it in GitHub Desktop.
Save smching/3582d2fbae417fc919e23b4e61c036d1 to your computer and use it in GitHub Desktop.
Node.js application: Subscribe to all topics of a MQTT broker
var mqtt = require('mqtt');
var Topic = '#'; //subscribe to all topics
var Broker_URL = 'mqtt://192.168.1.123';
var options = {
clientId: 'MyMQTT',
port: 1883,
keepalive : 60
};
var client = mqtt.connect(Broker_URL, options);
client.on('connect', mqtt_connect);
client.on('reconnect', mqtt_reconnect);
client.on('error', mqtt_error);
client.on('message', mqtt_messsageReceived);
client.on('close', mqtt_close);
function mqtt_connect()
{
console.log("Connecting MQTT");
client.subscribe(Topic, mqtt_subscribe);
}
function mqtt_subscribe(err, granted)
{
console.log("Subscribed to " + Topic);
if (err) {console.log(err);}
}
function mqtt_reconnect(err)
{
console.log("Reconnect MQTT");
if (err) {console.log(err);}
client = mqtt.connect(Broker_URL, options);
}
function mqtt_error(err)
{
console.log("Error!");
if (err) {console.log(err);}
}
function after_publish()
{
//do nothing
}
function mqtt_messsageReceived(topic, message, packet)
{
console.log('Topic=' + topic + ' Message=' + message);
}
function mqtt_close()
{
console.log("Close MQTT");
}
@molinto
Copy link

molinto commented Aug 14, 2019

Whats granted for please?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment