How to Use MQTT in Node-RED

Navigate to:

Traditional communication methods struggle to ensure efficient, reliable, real-time data exchange within IoT systems, leading to suboptimal performance, data loss, and overall inefficiency. Conventional protocols cannot meet the demands of low bandwidth, intermittent connectivity, and the need for instant response. Paired with the visual elegance of Node-RED, MQTT transforms into a formidable solution that effortlessly bridges the gap between devices, applications, and data sources.

This post will dissect the intricacies of MQTT within the context of Node-RED by delving into its core features, implementation strategies, and real-world applications.

What Is MQTT?

MQTT is a streamlined and effective messaging protocol meticulously crafted for use within resource-restricted settings. It especially shines when remote devices grapple with constraints like restricted processing capabilities, limited memory, and constrained network bandwidth.

MQTT operates on the client-server model, where clients (devices or applications) communicate with a central server, the MQTT broker. Clients can publish messages to topics on the broker or subscribe to topics to receive messages from other clients. The broker routes messages between clients based on the topic structure.

Critical concepts in MQTT include the following:

  • Topics: Topics are hierarchical strings that messages are associated with. Clients can publish messages to specific topics and subscribe to topics to receive messages. For example, a weather station might publish temperature data to a topic like “sensors/weather/temperature.”

  • Quality of service (QoS): MQTT offers different levels of message delivery assurance through its QoS levels. QoS 0 (at most once), QoS 1 (at least once), and QoS 2 (exactly once).

  • Retained messages: A retained message is a message that the broker stores and delivers to new subscribers immediately upon subscription. This is useful for providing the latest information to new clients that connect.

  • Last will and testament (LWT): Clients can specify a “last will” message that the broker will send to a specified topic if the client unexpectedly disconnects. This can notify others when a device goes offline suddenly.

  • Session persistence: MQTT supports both clean sessions and persistent sessions. In a persistent session, the broker remembers the state of subscriptions and queued messages for a client even if it disconnects and reconnects later.

What Is Node-RED?

Node-RED is an open-source visual programming tool that allows users to create flows by wiring together various nodes to perform tasks visually and intuitively. Node-RED is often used in industrial prototyping, the internet of things (IoT), automation projects to connect devices, APIs, and online services.

Some of the key features and concepts of Node-RED include the following:

  • Nodes for different functions, such as input, output, processing, and more.

  • Flow-based programming, which enables you to build applications by creating visual flows. Create a flow by dragging and dropping nodes onto the canvas and connecting them to define their applications’ logic.

  • Message passing, which allows nodes to communicate with each other by passing messages along the wires that connect them. These messages can contain data or commands that trigger specific actions.

MQTT Nodes

In Node-RED, MQTT nodes facilitate communication using the MQTT protocol. These nodes allow you to interact with MQTT brokers, publish messages to MQTT topics, and subscribe to MQTT topics to receive messages. Node-RED provides several MQTT nodes you can use in your flows.

Here are some of the common MQTT nodes:

  • MQTT-broker node: This node represents an MQTT broker connection. It configures the connection details to an MQTT broker, such as the broker’s address, port, and credentials. Once configured, other MQTT nodes in the flow can reference this broker configuration.

  • MQTT-in node (MQTT input): The MQTT-in node subscribes to MQTT topics and receives messages from the broker. When a message is published to a subscribed topic, the MQTT-in node triggers and passes the received message to the following nodes in the flow for further processing.

  • MQTT-out node (MQTT output): The MQTT-out node publishes messages to MQTT topics. You can configure the topic and payload of the message you want to publish. The message can be static or dynamically generated based on data from other nodes in the flow.

How to Connect and Use MQTT in Node-RED

To help you understand how to use MQTT in Node-RED, we’ll simulate a flow where we’re tracking data emitted by a humidity sensor.

To connect to an MQTT in Node-RED, you’ll need a broker. A broker is an intermediary for the messages sent by the publishing client and the consumer or subscriber client. For our case, we’ll use the Eclipse Mosquitto broker, but you can use other brokers like HiveMQ, Cloud MQTT or EMQX.

Make sure you have a broker installed and are running it. By default, the broker runs on port 1883 or 8883 for TLS, so you’ll enter your broker’s URL or IP address in the server field. If you’re running your broker locally, the server address will be localhost.

broker installed

Configuring MQTT Publish Node

Drag and drop an MQTT-out node from the Node-RED palette onto the canvas.

Double-click the MQTT-out node to open its configuration dialog.

In the configuration dialog, click the pencil icon next to the Server field to create a new broker configuration.

Edit the MQTT broker settings by adding the broker’s address in the server field, port, and any authentication credentials if required.

Click Done to save the broker settings.

Edit-mqtt-out-node

In the configuration dialog, configure the following fields:

  • Topic: Enter the MQTT topic to which you want to publish messages. We’ll add sensors/humidity as the topic.

  • QoS: Choose the desired QoS level for message delivery (0, 1, or 2).

  • Retain: Choose whether to retain the published message on the broker (true or false).

  • Name: Optionally, give your node a meaningful name.

Click Done to save the configuration.

Configuring MQTT Subscribe Node

Drag and drop an MQTT-in node from the Node-RED palette onto the canvas.

Double-click the MQTT-in node to open its configuration dialog.

Edit-mqtt-node

In the configuration dialog, configure the following fields:

  • Server: Since we already configured our broker in MQTT-in node, it should be pre populated. If not, you can repeat the steps by clicking the pencil icon.

  • Action: You can subscribe to a single topic or have a dynamic subscription. With a dynamic subscription, you can extract the desired MQTT topic from the message’s payload using a function node or other processing nodes. Since we know the topic we want, we’ll subscribe to a single topic.

  • Topic: Enter the MQTT topic you want to subscribe to (sensors/humidity).

  • QoS: Choose the desired QoS level for message delivery (0, 1, or 2).

  • Name: Optionally, give your node a meaningful name.

Click Done to save the configuration.

Click Done to save configuration

Drag and drop an inject node from the palette onto the canvas. Connect the inject node to a function node that will generate random values and connect to the MQTT-out node. You can set the inject node to repeat after a set interval, like ten seconds.

// Generate a random humidity value between 0 and 100
var randomHumidity = Math.random() * 15;

// Create the message object with the random humidity value
var msg = {
    payload: randomHumidity,
    topic: "sensors/humidity"
};

// Return the message object
return msg;

Connect the output of the MQTT-in node to the debug node in your flow to pass the message payload to the debug tab to the right of the Node-RED editor.

Deploy your flow by clicking the Deploy button in the upper-right corner of the Node-RED interface.

With these configurations in place, the MQTT-out node will publish messages to the specified topic, and the MQTT-in node will subscribe to the specified topic to receive messages from the MQTT broker. Ensure that the topic configurations in the MQTT-out and MQTT-in nodes match to establish proper communication.

Applications of Node-RED & MQTT

Node-RED combined with MQTT opens up many practical applications, especially in IoT, automation, and real-time data processing. Here are some practical applications where Node-RED and MQTT can be used effectively:

Home automation

You can connect various IoT devices like lights, thermostats, door sensors, and motion detectors using MQTT. Node-RED flows can control and coordinate these devices based on sensor inputs, schedules, or user-defined rules.

Industrial IoT (IIoT)

Using MQTT, Node-RED can connect to industrial sensors, programmable logic controllers (PLCs), and machinery in industrial settings. This enables real-time monitoring, data analysis, and remote control of industrial processes.

Environmental monitoring

MQTT can transmit data from environmental sensors (temperature, humidity, air quality, etc.) to a central server. Node-RED can process this data to trigger alerts, visualize trends, and perform automated actions based on environmental changes.

Energy management

Node-RED can help monitor energy consumption by interfacing with smart meters and sensors through MQTT. It can track energy usage patterns, optimize energy distribution, and trigger actions to reduce energy consumption during peak times.

Agriculture

MQTT-connected sensors in fields can monitor soil moisture, temperature, and other variables. Node-RED can process this data to optimize irrigation schedules, automate control of greenhouse environments, and enhance crop management.

Security and surveillance

MQTT can transmit data from security cameras, motion detectors, and access control systems to Node-RED. Node-RED can trigger alarms, automate responses, and display real-time video feeds.

Wrapping Up

The power of MQTT truly comes to life when combined with Node-RED, an intuitive visual programming tool, and InfluxDB, a robust time series database. Take the first step toward transforming your communication and industrial prototyping landscape by getting InfluxDB.

Additional resources

This post was written by Mercy Kibet. Mercy is a full-stack developer with a knack for learning and writing about new and intriguing tech stacks.