Step-by-step guide to restarting an MQTT subscriber using Node.js

Working on a Node Js and MQTT Project

In this project, a device initially subscribes to a topic or list of topics and starts receiving messages published for those specific topic(s). An admin from the dashboard then assigns that device another new topic. The client code is running on the device (subscriber) and the admin does not have access to restart it. How can the device dynamically update to the newly assigned topic without needing a restart? Is it necessary to restart the device in order to receive the 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}'`;

// Query database for subscribed topics
connection.query(qry, (err,rows) => {
  if(err) throw err;  
  rows.forEach( (row) => {      
      console.log(row.topic_name);
      subscribed.push(row.topic_name);
    });
  });

// Subscribe to retrieved topics
client.on('connect', function () {
  subscribed.forEach(element => {
    client.subscribe(element);
  });  
})

// Upon message receipt, log details
client.on('message', function (topic, message) {
  console.log(topic, '------>', message.toString());
})

Publisher Setup

The publisher simply adds the topic name and assigns the entry to the respective device in the table before publishing a message with the specified topic name.

Objective

I aim to enable my subscriber to reconnect/restart seamlessly in order to fetch all updated devices when a new entry is assigned to the subscriber. Currently, after adding a new topic, restarting the subscriber code resolves the issue, but I am looking for a solution that does not involve restarting the code every time.

Answer №1

If you want to add a new topic to your subscribed array, you can simply close and reconnect the mqtt connection/subscriber.

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')
  }
  })

After re-establishing the mqtt connection, your client.on('connect', function () will automatically resubscribe to all topics in your array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve a collection of users along with their most recent two entries using TypeORM and SQL

What is the best approach to retrieve a list of users with their last two visited locations using SQL query? user-table id name xxx a xyx b zzz e visitedlocation-table id startDate userID location 1. 1/2/21 xxx USA 2. 1/3/21 ...

Is there a way to specifically search for partial values in the MySQL database?

I have a SQL database with various paths stored: +-----------------------------------------+ | path | +-----------------------------------------+ | monkey/bear/elephant/tiger/lion | | monkey/bear/elephant/panda ...

What sets Firebase apart from Express in terms of its core functionalities?

Currently, I am delving into the realm of writing an API using Express and MongoDB while incorporating Angular for routes and views. I have been contemplating whether Firebase and AngularFire could potentially eliminate the need for Express altogether, mak ...

Getting an ETIMEDOUT error while trying to install a package using npm or yarn

In my Arch Linux system, I recently cleared out the npm cache along with other caches. Now, whenever I try to run npm ping or install something using npm or yarn, I encounter the following error: npm notice PING http://registry.npmjs.org/ npm ERR! code ET ...

Having trouble locating module '@mdx-js/mdx' in Gatsby forest

Since the most recent update today, I've been encountering this error. There is no MDX being used in my project at all.. When running npm run develop, this issue arises. Does anyone have any insights on this? internal/modules/cjs/loader.js:979 thro ...

Redis data retrieval is successful on the second attempt

I am utilizing a Redis database along with express routing to create an API. My stack includes node.js and ioredis as well. The process involves connecting to Redis, fetching keys related to a specific date, and then retrieving the data associated with th ...

Ways to halt the expressjs server

After deploying my express and nextjs based app on EC2, I encountered an issue where the server automatically starts Nginx and node with different process IDs after I attempt to stop it by killing the process. This is happening even without using tools lik ...

Methods for establishing communication between a React server and a Node server using private IP addresses

I currently have three EC2 Instances on AWS React Server Instance Node Server Instance MongoDB Server Instance My goal is to establish a connection between my React Server and Node Server using the Private IP address. For security purposes, I do not want ...

Is being unfazed by work a common occurrence?

After completing a complex cycle that processes data from the database and writes it to an array, I encounter a situation where the array processing function is triggered before the array is fully populated. This forces me to use setTimeout() for proper ti ...

Implementing a new archival capability on my website

I'm implementing a feature on my website that allows users to archive posts as needed. The site is developed using MERN stack and a RESTful API. Initially, I considered updating the Post model with an 'archived' property like: { archived: ...

Encounter an error when reading a stream with a maximum timeout value set

I have encountered a challenge while trying to read and process large CSV files. Due to a rate limit in processing, I need to introduce a 1-minute delay between each request. Initially, I attempted to use set timeout, but discovered that there is a limitat ...

Node.js Token-Based Authorization with Role-Based Access Control

I've searched extensively with no luck. Does anyone know of a method or an npm package that enables users to send a token granting Role-based access control, such as Administrator privileges, on a website? ...

I am curious as to why Helmet is preventing access to YouTube videos in my Express application that utilizes an embedded YouTube player

In developing my Express app, I allowed users to post YouTube videos embedded with iframe elements in the relevant view using the YouTube embedded player. However, upon attempting to deploy the app, I encountered an issue after adding Helmet with its recom ...

In the discord.js library, the reactionCollector feature does not cease even when the stop() method is invoked

I'm currently developing a bot using discord.js and facing an issue. My objective is to create a reaction collector that collects the reactions of users who want to participate in a tournament when triggered by the command "tournament prepare". Later, ...

Iterating through the startPrivateConversation method in Botkit for a multitude of users

In order to send an update to all my users, I created a new bot controller in a separate js file. To achieve this successfully, I needed to implement a notification function inside the controller's rtm_open function. The goal was to iterate through th ...

Accessing the path to an imported file in Node.js

Currently, I am working on a parser and encountering imports such as ../modules/greeting.js. Additionally, I have an absolute path to the file from where I performed the import: C:\Desktop\Folder\src\scripts\main.js. I am seeking ...

Setting the value for an input field using Jade/Pug

input(type="text", name="Q1VolTarget", value="#{value.Q1TargetVolume}") td #{value.Q1TargetGP} This code is currently displaying #{value.Q1TargetVolume} as text instead of retrieving its actual value. https://i.stack.imgur.com/ee4Cj ...

Encountering a connection error while running a Node.js Selenium test case on Chrome. The specific error message received is: "Error: ECONNREFUSED - Connection refused to 127.0

When attempting to run a test case on a Selenium Node.js server, an error was encountered: Error: ECONNREFUSED connect ECONNREFUSED. The test case script is as follows: var assert = require('assert'), test = require('selenium-webdriver ...

Update specific fields in a MySQL database using Express.js only if they are passed as parameters

After spending several days trying to set up a REST API, I found a helpful tutorial that explained the basics of sending requests and receiving responses. The only issue is that the tutorial uses MongoDB and Mongoose, while I'm working with MySQL. Due ...

What is the method to halt a middleware chain?

What is the correct way to terminate a middleware chain when an error occurs? In my code, I have: if (someProblem) { res.status(statuscode).json({message: 'oops'}); return; } However, the middleware in the chain continu ...