Last active
June 25, 2022 08:09
-
-
Save smching/3582d2fbae417fc919e23b4e61c036d1 to your computer and use it in GitHub Desktop.
Node.js application: Subscribe to all topics of a MQTT broker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Whats granted for please?