Reputation: 1486
Project is with Node Js and MQTT
a device has subscribed a topic or list of topics initially and started reeving messages published for those topic(s), admin from the dashboard, assigned that device another new topic, client code is running on the device(subscriber) admin has no access to restart it, how dynamically device will update to newly assigned topic? Do we need to restart the device to get updated list of assigned topics?
//subscriber.js
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://test.mosquitto.org')
const mysql = require('mysql');
const subName = 'iPhoneX';
var subscribed = [];
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydb'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
var qry = `SELECT topic_name from sub_table s where s.sub_name='${subName}'`;
connection.query(qry, (err,rows) => {
if(err) throw err;
rows.forEach( (row) => {
console.log(row.topic_name);
subscribed.push(row.topic_name);
});
});
client.on('connect', function () {
subscribed.forEach(element => {
client.subscribe(element);
});
})
client.on('message', function (topic, message) {
console.log(topic, '------>', message.toString());
})
publisher
Publisher is just adding the topic name, and which device is assigned that entry in table and publishing message with topic name
What I want to do
I want to make my subscriber to reconnect/restart to fetch all updated device when new entry is assigned to subscriber?
In current scenario, after addition of new topic when I restart the subscriber code, it works fine, but I don't want to restart it every time.
Upvotes: 0
Views: 776
Reputation: 22
You could just close and reconnect the mqtt connection/subscriber after pushing a new topic to your subscribed
array.
connection.query(qry, (err,rows) => {
if(err) throw err
rows.forEach( (row) => {
console.log(row.topic_name)
subscribed.push(row.topic_name)
})
if (rows.length > 0) {
client.end()
client = mqtt.connect('mqtt://test.mosquitto.org')
}
})
Your client.on('connect', function ()
will do the rest and re-subscribe to every topic in your array after having established the mqtt connection again.
Upvotes: 1