MakerGram Logo

    MakerGram

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Popular
    • Tags
    • Users
    • Groups

    Can't connect NodeMCU with MQTT

    Arduino
    2
    7
    25
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • S
      sivanath last edited by

      I can't establish a connection with my NodeMCU and MQTT server.
      I am getting an error of:

      Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
      
      

      Every topic name, nodes and other variables are assigned from the given video: Referred video

      Below is the code:

      
      #include <ESP8266WiFi.h>
      #include <PubSubClient.h>
      
      // Change the credentials below, so your ESP8266 connects to your router
      const char* ssid = "Wifi";
      const char* password = "Wifi123";
      
      // Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
      const char* mqtt_server = "192.168.1.38";
      
      // Initializes the espClient. You should change the espClient name if you have multiple ESPs running in your home automation system
      WiFiClient espClient22;
      PubSubClient client(espClient22);
      
      
      // Lamp - LED - GPIO 4 = D2 on ESP-12E NodeMCU board
      const int led = 4;
      
      
      //Connect your NodeMCU to your router
      void setup_wifi() {
        delay(10);
        
        Serial.println();
       
        Serial.print("Connecting to ");
        Serial.println(ssid);
        WiFi.mode(WIFI_STA);
        WiFi.begin(ssid, password);
        while (WiFi.status() != WL_CONNECTED) {
          delay(100);
          Serial.print(".");
        }
        Serial.println("");
        Serial.print("WiFi connected - NodeMCU IP address: ");
        Serial.println(WiFi.localIP());
      }
      
      // This functions is executed when some device publishes a message to a topic that your NodeMCU is subscribed to
      
      void callback(String topic, byte* message, unsigned int length) {
        Serial.print("Message arrived on topic: ");
        Serial.print(topic);
        Serial.print(". Message: ");
        String messageInfo;
        
        for (int i = 0; i < length; i++) {
          Serial.print((char)message[i]);
          messageInfo += (char)message[i];
        }
        Serial.println();
      
        // If a message is received on the topic room/lamp, you check if the message is either on or off. Turns the lamp GPIO according to the message
        if(topic=="room/light"){
            Serial.print("Changing Room Light to ");
            if(messageInfo == "on"){
              digitalWrite(led, HIGH);
              Serial.print("On");
            }
            else if(messageInfo == "off"){
              digitalWrite(led, LOW);
              Serial.print("Off");
            }
        }
        Serial.println();
      }
      
      // This functions reconnects your ESP8266 to your MQTT broker
      // Change the function below if you want to subscribe to more topics with your ESP8266 
      void reconnect() {
        // Loop until we're reconnected
        while (!client.connected()) {
          Serial.print("Attempting MQTT connection...");
          
          
          if (client.connect("ESP8266Client22")) {
            Serial.println("connected");  
            // Subscribe or resubscribe to a topic
            // You can subscribe to more topics (to control more LEDs in this example)
            client.subscribe("room/light");
          } else {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
          }
        }
      }
      
      // The setup function sets your ESP GPIOs to Outputs, starts the serial communication at a baud rate of 115200
      // Sets your mqtt broker and sets the callback function
      // The callback function is what receives messages and actually controls the LEDs
      void setup() {
        pinMode(led, OUTPUT);
        Serial.begin(115200);
        setup_wifi();
        client.setServer(mqtt_server, 1883);
        client.setCallback(callback);
      
      }
      
      // For this project, you don't need to change anything in the loop function. Basically it ensures that the NodeMCU is connected to MQTT broker
      void loop() {
      
        if (!client.connected()) {
          reconnect();
        }
        if(!client.loop())
          client.connect("ESP8266Client22");
      
        }
      

      deployed.png

      mqtt node.png

      switch node.png

      1 Reply Last reply Reply Quote 1
      • salmanfaris
        salmanfaris last edited by

        Hi 👋,

        Where did you installed the MQTT broker (server) and is it running background when your run the nodeRED application and is it installed on the same machine as nodeRED installed?

        S 1 Reply Last reply Reply Quote 0
        • S
          sivanath @salmanfaris last edited by

          @salmanfaris It is running locally on my computer. Yes, and is running in the background.
          cmd.png

          salmanfaris 1 Reply Last reply Reply Quote 0
          • salmanfaris
            salmanfaris @sivanath last edited by

            @sivanath Before connecting via NodeRED , Could you try to create MQTT Subscribe and Publish client using the CLI and see it can transfer message payload with the same broker name?

            S 1 Reply Last reply Reply Quote 0
            • S
              sivanath @salmanfaris last edited by

              @salmanfaris Yes, I had tried that before and it was working fine. Infact, everything works perfectly when I connect with the online mqtt server, test.mosquitto.org. So, there's some problem with the local installation, while using my local IP. But I can't find that problem. I had also re-installed the mqtt, but still the same issue.

              salmanfaris 1 Reply Last reply Reply Quote 0
              • salmanfaris
                salmanfaris @sivanath last edited by

                @sivanath Does the local pub and sub is working over CLI?

                S 1 Reply Last reply Reply Quote 0
                • S
                  sivanath @salmanfaris last edited by

                  @salmanfaris It was working in CLI, but now it's showing multiple usages at the portmultiple usage.png

                  1 Reply Last reply Reply Quote 0
                  • First post
                    Last post

                  Recent Posts

                  • S

                    @salmanfaris It was working in CLI, but now it's showing multiple usages at the portmultiple usage.png

                    • read more
                  • @sivanath Does the local pub and sub is working over CLI?

                    • read more
                  • S

                    @salmanfaris Yes, I had tried that before and it was working fine. Infact, everything works perfectly when I connect with the online mqtt server, test.mosquitto.org. So, there's some problem with the local installation, while using my local IP. But I can't find that problem. I had also re-installed the mqtt, but still the same issue.

                    • read more
                  • @sivanath Before connecting via NodeRED , Could you try to create MQTT Subscribe and Publish client using the CLI and see it can transfer message payload with the same broker name?

                    • read more
                  • S

                    @salmanfaris It is running locally on my computer. Yes, and is running in the background.
                    cmd.png

                    • read more
                  By MakerGram | A XiStart Initiative | Built with ♥ NodeBB
                  Copyright © 2021 MakerGram, All rights reserved.
                  Privacy Policy | Terms & Conditions | Disclaimer | Code of Conduct