Connecting Nodejs Backend with ESP32 via MQTT : A Step-by-Step Guide
MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol ideal for the Internet of Things (IoT) due to its low bandwidth and fast, reliable communication. When combined with the ESP32 microcontroller, MQTT enables a wide range of applications requiring real-time updates.
This guide provides a clear, step-by-step process for connecting a Node.js backend with an ESP32 microcontroller using an MQTT broker. The example demonstrates how to set up a local Node.js server that communicates with an ESP32, sending and receiving data via MQTT. This setup is perfect for IoT applications, where devices need to exchange information seamlessly.
What You Need
- ESP32 Microcontroller
- MicroUSB to USB cable
Setting Up the MQTT Broker
We will use Mosquitto, a popular MQTT broker, for this example. You can set up Mosquitto locally or use a public broker like [test.mosquitto.org](https://test.mosquitto.org). Here are the steps to set up Mosquitto on your local machine.
Install Mosquitto
On Windows
1. Download the Mosquitto installer from the [Mosquitto website](https://mosquitto.org/download/).
2. Run the installer and follow the on-screen instructions.
On macOS
brew install mosquitto
Start the Mosquitto Broker
After installing Mosquitto, start the broker with the following command on the terminal
mosquitto
Node.js Backend Setup
Install Dependencies
Create a new directory for your project and initialize a new Node.js project
mkdir node-esp32-mqtt
cd node-esp32-mqtt
npm init -y
npm install mqtt express body-parser
Create ‘server.js’ File
Create a ‘server.js’ file with the following content
const mqtt = require('mqtt');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const httpPort = 3000;
const mqttClient = mqtt.connect({ host: 'test.mosquitto.org', port: 1883 });
app.use(bodyParser.json());
mqttClient.on('connect', () => {
console.log('Connected to MQTT broker');
mqttClient.subscribe('refrigerator/sensor1/temp');
setInterval(() => {
publishHardcodedData();
}, 1000);
});
mqttClient.on('message', (topic, message) => {
console.log('Received message on topic', topic, ':', message.toString());
});
// Function to publish hardcoded data
function publishHardcodedData() {
const hardcodedData = { "threshold": 25 };
mqttClient.publish('refrigerator/config', JSON.stringify(hardcodedData), (err) => {
if (err) {
console.error('Failed to publish hardcoded data', err);
} else {
console.log('Hardcoded data published successfully');
}
});
}
// Start the server
app.listen(httpPort, () => {
console.log(`Server is running on http://localhost:${httpPort}`);
});
This code sets up an MQTT client that connects to the MQTT broker and subscribes to all topics under ‘refrigerator/’. It also creates an HTTP endpoint ‘/publish’ to publish messages to specified MQTT topics.
ESP32 Setup
Next, we’ll set up the ESP32 to communicate with the MQTT broker.
Install Arduino Libraries
Ensure you have the following libraries installed in your Arduino IDE,
- WiFi
- PubSubClient
- ArduinoJson
ESP32 Code
Create a new sketch in the Arduino IDE and add the following code,
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqtt_server = "test.mosquitto.org";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (unsigned int i = 0; i < length; i++) {
Serial.print((char)message[i]);
}
Serial.println();
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX); // Add a unique identifier to the client ID
if (client.connect(clientId.c_str())) {
Serial.println("connected");
client.subscribe("refrigerator/config");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Publish temperature data
StaticJsonDocument<200> doc;
doc["temperature"] = random(20, 30);
char buffer[256];
serializeJson(doc, buffer);
client.publish("refrigerator/sensor1/temp", buffer);
delay(10000);
}
This code connects the ESP32 to the Wi-Fi network and the MQTT broker. It subscribes to the ‘refrigerator/config’ topic and publishes random temperature data to the ‘refrigerator/sensor1/temp’ topic every 10 seconds.
Running the Setup
Start the Node.js Server
Run the Node.js server by executing
node server.js
Your server should start and connect to the MQTT broker, displaying “Connected to MQTT broker” in the console.
Upload the Code to ESP32
Upload the ESP32 code to your ESP32 using the Arduino IDE. Open the Serial Monitor to check the connection status and messages being sent/received.
Happy Coding! Now you can play around.
For any projects involving MQTT, feel free to contact us; we can design and implement a custom system for your needs.
Protonest for more details.
Protonest specializes in transforming IoT ideas into reality. We offer prototyping services from concept to completion. Our commitment ensures that your visionary IoT concepts become tangible, innovative, and advanced prototypes.
Website: https://www.protonest.co/
Email: udara@protonest.co
If you enjoyed this article and would like to show some support, consider buying me a coffee on Ko-Fi.
Your support not only helps me keep creating content like this but also fuels me! ☕️📚
Thank you for being an amazing reader!
Here’s my Ko-Fi link: https://ko-fi.com/udarakumarasena
Cheers!