MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol based on the publish/subscribe model, designed for devices with limited bandwidth and unstable connections.
It is ideal for applications that require efficient and scalable communication, such as IoT (Internet of Things), real-time monitoring systems, or mobile applications, among others.
Some of its characteristics are:
- Lightweight and efficient: MQTT uses a simple, small-sized message format, making it suitable for resource-constrained devices.
- Publish/Subscribe Model: Clients can publish messages to a topic and subscribe to topics to receive relevant messages.
- QoS (Quality of Service): MQTT supports different QoS levels to guarantee message delivery according to the required importance and reliability.
Example of MQTT Implementation in Node.js
To implement MQTT in Node.js, we will use the mqtt library which provides all the necessary tools to create MQTT clients and servers.
First, we need to install the mqtt library in our Node.js project:
npm install mqtt
Next, we’ll see a basic example of how to create an MQTT server and how to connect clients to send and receive messages.
Creating an MQTT Client
import mqtt from 'mqtt';
// Connecting to the MQTT broker
const client = mqtt.connect('mqtt://localhost:1883'); // Change to your broker's URL and port
// Event when connected to the broker
client.on('connect', () => {
console.log('Connected to MQTT broker');
// Subscribe to a topic
client.subscribe('my/topic', (err) => {
if (!err) {
console.log('Subscribed to topic "my/topic"');
}
});
// Publish a message to a topic
client.publish('my/topic', 'Hello from the MQTT client');
});
// Event when a message is received on the subscribed topic
client.on('message', (topic, message) => {
console.log('Message received on topic:', topic);
console.log('Message content:', message.toString());
});
// Error handling
client.on('error', (err) => {
console.error('Error in MQTT client:', err);
});
In this example:
- It connects to the MQTT broker at
mqtt://localhost:1883. Make sure to change this to the URL and port of the MQTT broker you are connecting to. - Once connected, it subscribes to the topic
'my/topic'. - Publishes a message to the same topic.
- When a message is received on the subscribed topic, it displays it in the console.
MQTT Client (Publisher Only)
If you are only interested in publishing messages, here is a simplified example of a client that publishes messages to the temperature topic.
import mqtt from 'mqtt';
const client = mqtt.connect('mqtt://localhost:1883');
client.on('connect', () => {
console.log('Connection established');
setInterval(() => {
const temperature = Math.floor(Math.random() * 50); // Generate random temperature
client.publish('temperature', temperature.toString());
console.log(`Message published to "temperature": ${temperature}`);
}, 5000); // Publish every 5 seconds
});
client.on('error', (error) => {
console.error('Connection error:', error);
});
In this example, we create an MQTT client that connects to the local server on port 1883. Then, we publish random temperature messages to the temperature topic every 5 seconds.
MQTT Client (Subscriber Only)
On the other hand, if you are only interested in subscribing to a topic, here is a simplified example that subscribes to the temperature topic to receive and display messages.
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://localhost:1883');
client.on('connect', () => {
console.log('Connection established');
client.subscribe('temperature');
});
client.on('message', (topic, message) => {
console.log(`Message received on ${topic}: ${message.toString()}°C`);
});
This client connects to the same MQTT server and subscribes to the temperature topic. Every time a message arrives on this topic, it displays it in the console along with the received temperature.
Web MQTT Client
Let’s see how we could make a Web client with HTML, JavaScript, and the Paho MQTT library to communicate via MQTT in the browser.
First, make sure to include the Paho MQTT library in your web page. You can do this by including the following script in your HTML,
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.2.2/mqttws31.min.js"></script>
Then, here is an example of what the web page could look like,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web MQTT Client</title>
</head>
<body>
<h1>Web MQTT Client</h1>
<div id="messages"></div>
<script src="./paho-mqtt.min.js" integrity="sha512-Y5n0fbohPllOQ21fTwM/h9sQQ/1a1h5KhweGhu2zwD8lAoJnTgVa7NIrFa1bRDIMQHixtyuRV2ubIx+qWbGdDA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
// Create an MQTT client
const client = new Paho.Client('localhost', 1833, 'web_client');
// Function to display messages on the page
function displayMessage(topic, message) {
const messagesDiv = document.getElementById('messages');
const messageElement = document.createElement('p');
messageElement.textContent = `Topic: ${topic}, Message: ${message}`;
messagesDiv.appendChild(messageElement);
}
// Callback when the client connects
function onConnect() {
console.log('Connected to MQTT broker from the web');
client.subscribe('my/topic');
}
// Callback when a message arrives
function onMessageArrived(message) {
console.log('Message received:', message.destinationName, message.payloadString);
displayMessage(message.destinationName, message.payloadString);
}
// Callback when there is an error
function onFailure(message) {
console.error('Connection error:', message.errorMessage);
}
// Set up callbacks
client.onConnectionLost = onFailure;
client.onMessageArrived = onMessageArrived;
// Connect to the broker
client.connect({ onSuccess: onConnect });
// Publish a message when a button is clicked (just as an example)
function publishMessage() {
const message = 'Hello from the MQTT web';
const topic = 'my/topic';
const messageObj = new Paho.Message(message);
messageObj.destinationName = topic;
client.send(messageObj);
}
</script>
<!-- Example button to publish a message -->
<button onclick="publishMessage()">Publish Message</button>
</body>
</html>
In this example:
- An MQTT client is created using
new Paho.MQTT.Client(), specifying the server address and port. - The callback functions
onConnect,onMessageArrived, andonFailureare defined to handle connection, received messages, and errors respectively. - When the client connects, it subscribes to the topic
'my/topic'. - When a message arrives, it is displayed on the page using the
displayMessagefunction. - The “Publish Message” button sends a message to the topic
'my/topic'when clicked.
Remember to adjust the MQTT server address and port in new Paho.MQTT.Client() according to your MQTT broker’s configuration.
Download the Code
All the code from this post is available for download on Github
