Language: EN

comunicacion-mqtt-nodejs

How to Make MQTT Communications with Node.js

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 where efficient and scalable communication is required, such as in IoT (Internet of Things), real-time monitoring systems, or mobile applications, among others.

Some of its features are:

  • Lightweight and efficient: MQTT uses a simple and small message format, making it suitable for devices with limited resources.
  • Publish/Subscribe Model: Clients can publish messages on a topic and subscribe to topics to receive relevant messages.
  • QoS (Quality of Service): MQTT supports different levels of QoS to ensure message delivery according to importance and required reliability.

Example of MQTT implementation in Node.js

To implement MQTT in Node.js, we will use the mqtt library that 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 will see a basic example of how to create an MQTT server and 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 URL and port

// Event when connected to the broker
client.on('connect', () => {
  console.log('Connected to the MQTT broker');

  // Subscribe to a topic
  client.subscribe('my/topic', (err) => {
    if (!err) {
      console.log('Subscribed to the topic "my/topic"');
    }
  });

  // Publish a message on 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 the topic:', topic);
  console.log('Message content:', message.toString());
});

// Error handling
client.on('error', (err) => {
  console.error('Error in the 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 'my/topic' topic.
  • It publishes a message on the same topic.
  • When a message is received on the subscribed topic, it is displayed on 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 on 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 on "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 on 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. Whenever a message arrives on this topic, it is displayed 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’s an example of how the web page could be,

<!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 the 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);
    }

    // Configure the 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 web MQTT';
      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.
  • Callback functions onConnect, onMessageArrived, and onFailure are defined to handle the connection, received messages, and errors, respectively.
  • When the client connects, it subscribes to the 'my/topic' topic.
  • When a message arrives, it is displayed on the page using the displayMessage function.
  • The “Publish Message” button sends a message to the 'my/topic' topic when clicked.

Remember to adjust the address and port of the MQTT server in new Paho.MQTT.Client() according to your MQTT broker configuration.