Node-Red ESP8266 MQTT Subscribe Example

Here it is shown how to subscribe to MQTT topic using ESP8288 and Node-RED. This tutorial is follow up of the previous tutorial Node-Red ESP8266 MQTT Publish Example where it was shown how to publish MQTT topic with ESP8266 and Node-Red. We will be using ESP8266 NodeMCU wifi module as MQTT client to subscribe to a topic. For the MQTT broker we will be using Mosquitto MQTT application. The node-red is used to build the web application to send message from the MQTT server to the MQTT client to turn on or off a LED connected to the MQTT client which is ESP8266. 

The following diagram illustrates how the MQTT subscribe works with ESP8266(Node MCU) as mqtt client, Mosquitto MQTT broker and using Node-Red to build the IoT application.

MQTT subscribe with ESP8266 NodeMCU, Node-Red

 In order to follow this tutorial you must have installed Mosquito MQTT application and Node-Red. Also you should have dashboard nodes installed in Node-Red. So the following are the steps involved in completing the tutorial.

1. Interface LED with ESP8266(Node MCU)

The first thing to do is to connect a LED with ESP8266. Here the LED is connected to GPIO5(D1) pin of the ESP8266 as shown below.

esp8266 with led

The actual implementation on breadboard is shown below.

ESP8266 LED

2. Programming ESP8266

The next step is to program ESP8266. In the following program, the ESP8266 connection to router is done, the connection to the MQTT server is done, the ESP8266 is setup as MQTT client which listen to subscribed topic from the server.

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Enter your router credentials
const char* ssid = "your_router_wifi_ssid";
const char* password = "your_wifi_password";

// Enter your MQTT broker IP address
const char* mqtt_server = "your_mqtt_broker_IP_address";

// Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);

// LED connected to ESP8862 NodeMCU GPIO5(D1)
const int LED = 5;

// Function to connect ESP8266(NodeMCU) to the router
void wifiConfig(){
  delay(10);
  // We start by connecting to a WiFi network
  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.print("WiFi connected - ESP8266 client IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(String topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // If a message to subscribed is received turn the LED on/off and print message
  if(topic=="switch/led"){
      Serial.print("LED status: ");
      if(messageTemp == "on"){
        digitalWrite(LED, HIGH);
        Serial.print("On");
      }
      else if(messageTemp == "off"){
        digitalWrite(LED, LOW);
        Serial.print("Off");
      }
  }
  Serial.println();
}

// This functions reconnects your ESP8266 to your MQTT broker
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");  
      // Subscribe to a topic
      client.subscribe("switch/led");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

//the LED pin is made up,
//serial communication is activated
//the wifi connection is started
//the MQTT server is setup and started
//callback function to execute subscribe routine
void setup() {
  pinMode(LED, OUTPUT);  
  Serial.begin(115200);
  wifiConfig();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

//The connection is established, if disconnected
void loop() {

  if (!client.connected()) {
    reconnect();
  }
  if(!client.loop())
    client.connect("ESP8266Client");
} 

This code should be uploaded via the Arduino IDE into the ESP8266 NodeMCU. The proper port should also be configured.


 Once successfully uploaded, the serial monitor should show the following messages.

3. Install and launch Mosquitto MQTT application

If you don't have already installed the Mosquitto MQTT application you can download and install from the following link.

https://mosquitto.org

Once downloaded, you should see the mosquitto.exe application in the extracted folder.

mosquitto server

You can start the mosquitto MQTT server(also called MQTT broker) using CLI command:

>mosquitto -v

Mosquitto MQTT broker

Once the MQTT broker is started it will run on localhost port 1883.

 4. Node-Red programming

The node-red flow to subscribe to a topic using MQTT broker and turn on or off the LED via a web user interface is shown below.

node red subscribe flow

In the above diagram, the On/Off node is a switch node available in the dashboard library. The dashboard is not available in default installation of node-red. You must install it using npn or manage pallete in node red. See how to install dashboard library in the tutorial Node Red IoT with Arduino DHT11.The switch/led is a MQTT out node available in the network library. The led node is from the dashboard library but it is not installed in new node-red installation. See the tutorial IR Proximity Sensor IoT Application.

When using dashboard we have to setup tab and group first. These information are required when configuration any dashboard nodes like the switch node and the LED node. To create a new tab and group, first create a new tab and name it Switch.

 Then from the new tab create a new group and name it LED. 


 After this you should have the following layout.


Now double click on the switch node to configure it. The settings for the On/Off switch node is shown below. 

 Next double click on the MQTT out node, the switch/led node and configure it as shown below.

Double click on the led node and configure it as shown below.

The next step is to deploy the application. Click on the deploy and then start button.

After this go to the http://localhost:1880/ui to open the web app dashboard.

Now we can turn on the LED using the switch.

Once the switch is turned on, the LED will turn on the breadboard.

ESP8266 LED on

And you should also see additional message on serial monitor that the message on topic swithc/led was received and that the message received was on and the LED status is on.

So in this way we can use Node-Red and Mosquitto MQTT broker to subscribe to topic with ESP8266 WiFi module. The following video demonstrates this.


The following is the node-red code.


[
    {
        "id": "5368dda7df7be6f0",
        "type": "tab",
        "label": "Flow 2",
        "disabled": false,
        "info": "",
        "env": []
    },
    {
        "id": "bd922026d266afcd",
        "type": "mqtt out",
        "z": "5368dda7df7be6f0",
        "name": "",
        "topic": "switch/led",
        "qos": "1",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "56d8bb395649bc55",
        "x": 500,
        "y": 280,
        "wires": []
    },
    {
        "id": "6c90693dce1c5e1f",
        "type": "ui_switch",
        "z": "5368dda7df7be6f0",
        "name": "",
        "label": "On/Off",
        "tooltip": "",
        "group": "6af2adfd5ce27e94",
        "order": 1,
        "width": 3,
        "height": 1,
        "passthru": true,
        "decouple": "false",
        "topic": "switch/led",
        "topicType": "str",
        "style": "",
        "onvalue": "on",
        "onvalueType": "str",
        "onicon": "",
        "oncolor": "",
        "offvalue": "off",
        "offvalueType": "str",
        "officon": "",
        "offcolor": "",
        "animate": false,
        "className": "",
        "x": 290,
        "y": 280,
        "wires": [
            [
                "bd922026d266afcd",
                "dbf190b9267ff4d8"
            ]
        ]
    },
    {
        "id": "dbf190b9267ff4d8",
        "type": "ui_led",
        "z": "5368dda7df7be6f0",
        "order": 3,
        "group": "6af2adfd5ce27e94",
        "width": 1,
        "height": 1,
        "label": "",
        "labelPlacement": "left",
        "labelAlignment": "left",
        "colorForValue": [
            {
                "color": "#ff0000",
                "value": "on",
                "valueType": "str"
            },
            {
                "color": "#008000",
                "value": "off",
                "valueType": "str"
            }
        ],
        "allowColorForValueInMessage": false,
        "shape": "circle",
        "showGlow": true,
        "name": "",
        "x": 490,
        "y": 220,
        "wires": []
    },
    {
        "id": "148c247d79a7fcf0",
        "type": "ui_spacer",
        "z": "5368dda7df7be6f0",
        "name": "spacer",
        "group": "6af2adfd5ce27e94",
        "order": 2,
        "width": 1,
        "height": 1
    },
    {
        "id": "56d8bb395649bc55",
        "type": "mqtt-broker",
        "name": "",
        "broker": "localhost",
        "port": "1883",
        "clientid": "",
        "autoConnect": true,
        "usetls": false,
        "protocolVersion": "4",
        "keepalive": "60",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthPayload": "",
        "birthMsg": {},
        "closeTopic": "",
        "closeQos": "0",
        "closePayload": "",
        "closeMsg": {},
        "willTopic": "",
        "willQos": "0",
        "willPayload": "",
        "willMsg": {},
        "userProps": "",
        "sessionExpiry": ""
    },
    {
        "id": "6af2adfd5ce27e94",
        "type": "ui_group",
        "name": "LED",
        "tab": "1a1b68ef501148ad",
        "order": 1,
        "disp": false,
        "width": 5,
        "collapse": false,
        "className": ""
    },
    {
        "id": "1a1b68ef501148ad",
        "type": "ui_tab",
        "name": "Switch",
        "icon": "dashboard",
        "order": 1,
        "disabled": false,
        "hidden": false
    }
]


Post a Comment

Previous Post Next Post