[SOLVED] MQTT not connecting to nodemcu

Yes disconnecting the relay also giving the same result. I will check this with multimeter

No, the multi-meter is not showing any toggle.

Does the nodeMCU connects and then stay connected until you send an mqtt message or does it lose connection before that?
Check you mosquitto log to see what happens when the nodeMCU tries to connect and then disconnects
Google mosquitto log

1526378010: New connection from 192.168.43.162 on port 1883.
1526378010: Socket error on client <unknown>, disconnecting.
1526378010: New connection from 192.168.43.162 on port 1883.
1526378010: Socket error on client <unknown>, disconnecting.
1526378010: New connection from 192.168.43.162 on port 1883.
1526378030: Socket error on client <unknown>, disconnecting.
1526378030: New connection from 192.168.43.162 on port 1883.
1526378051: Socket error on client <unknown>, disconnecting.
1526378947: Socket error on client mosqsub|28643-ajay-Leno, disconnecting.
1526379025: Saving in-memory database to /var/lib/mosquitto/mosquitto.db.

Currently I am tailing the log will update

No. Its is disconnecting even though openhab switch is not toggled

There is something wrong in your nodemcu code
It is trying to connect to the broker without a clientID
Can you publish your code again

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


//EDIT THESE LINES TO MATCH YOUR SETUP
const char* ssid = "ajay";
const char* password = "*********";
const char* mqttServer = "192.168.43.102";
const int mqttPort = 1883;
const char* mqttUser = "ajay";
const char* mqttPassword = "*************";

//LED on ESP8266 GPIO2
const int lightPin = 2;
const int relay = 0;

char* lightTopic = "light";


WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int length);
PubSubClient client(mqttServer, mqttPort, callback, wifiClient);

void setup() {
  //initialize the light as an output and set to LOW (off)
  pinMode(lightPin, OUTPUT);
  digitalWrite(lightPin, LOW);
  pinMode(relay, OUTPUT);
  digitalWrite(relay, HIGH);

  //start the serial line for debugging
  Serial.begin(115200);
  delay(100);


  //start wifi subsystem
  WiFi.begin(ssid, password);
  //attempt to connect to the WIFI network and then connect to the MQTT server
  reconnect();

  //wait a bit before starting the main loop
      delay(2000);
}



void loop(){

  //reconnect if connection is lost
  if (!client.connected() && WiFi.status() == 3) {reconnect();}

  //maintain MQTT connection
  client.loop();

  //MUST delay to allow ESP8266 WIFI functions to run
  delay(10); 
}


void callback(char* topic, byte* payload, unsigned int length) {

  //convert topic to string to make it easier to work with
  String topicStr = topic; 

  //Print out some debugging info
  Serial.println("Callback update.");
  Serial.print("Topic: ");
  Serial.println(topicStr);

  //turn the light on if the payload is '1' and publish to the MQTT server a confirmation message
  if(payload[0] == '1'){
    digitalWrite(relay, HIGH);
    client.publish("confirm", "Light On");

  }

  //turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
  else if (payload[0] == '0'){
    digitalWrite(relay, LOW);
    client.publish("confirm", "Light Off");
  }

}




void reconnect() {

  //attempt to connect to the wifi if connection is lost
  if(WiFi.status() != WL_CONNECTED){
    //debug printing
    Serial.print("Connecting to ");
    Serial.println(ssid);

    //loop while we wait for connection
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
      digitalWrite(lightPin, LOW);
      delay(500);
      digitalWrite(lightPin, HIGH);
    
    }

    //print out some more debug once connected
    Serial.println("");
    Serial.println("WiFi connected");  
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    
  }

  //make sure we are connected to WIFI before attemping to reconnect to MQTT
  if(WiFi.status() == WL_CONNECTED){

    digitalWrite(lightPin, LOW);
  // Loop until we're reconnected to the MQTT server
    while (!client.connected()) {
      Serial.print("Attempting MQTT connection...");

      // Generate client name based on MAC address and last 8 bits of microsecond counter
      String clientName;
      clientName += "esp8266-";
      uint8_t mac[6];
      WiFi.macAddress(mac);
      clientName += macToStr(mac);

      //if connected, subscribe to the topic(s) we want to be notified about
      if (client.connect((char*) clientName.c_str()), mqttUser, mqttPassword) {
        Serial.println("\tMQTT Connected");
        client.subscribe(lightTopic);
      }

      //otherwise print failed for debugging
      else{Serial.println("\tFailed."); abort();}
    }
  }
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);

    if (i < 5){
      result += ':';
    }
  }

  return result;
}

I came across this [Solved] Very frequent MQTT disconnects

does it make any sense with my problem?

Yes something problem in my coding, because in log it is continuously disconnecting and terminating the code at last and trying to start from the setup

No

Change this:

      String clientName = "esp8266-";
      uint8_t mac[6];
      WiFi.macAddress(mac);
      clientName += macToStr(mac);
      Serial.print("Client ID : ");
      Serial.println(clientName);

      //if connected, subscribe to the topic(s) we want to be notified about
      if (client.connect(clientName.c_str(), mqttUser, mqttPassword)) {
        Serial.println("\tMQTT Connected");
        client.subscribe(lightTopic);
      }

Eureka
 It’s working. Thanks @vzorglub. For spending this much of time in setting my device to work. You have given me a splendid support and solved all the problems. Thank you once again.

Now, you can make it better:

Install the MAP transformation

Your item:

Switch Light "Light" {mqtt=">[mymqtt:light:command:ON:1],>[mymqtt:light:command:OFF:0]"}

Change it to:

Switch Light "Light" {mqtt=">[mymqtt:light:command:*:MAP(onoff.map)]"}

In the conf/transform folder create a file called onoff.map with the following content:

-=Undef
NULL=NULL
ON=1
OFF=0

Now every time you send a command ON of OFF, openHAB with automatically transform it into 1 or 0 for your nodeMCU

Also be consistent with your topic.
I have for example the items:
LivingRoom_TVLight
LivingRoom_DeskLight

the mqtt topics are:
House/LivingRoom/TVLight
House/LivingRoomDeskLight
House/LivingRoom/ThermostatTarget
Garden/Gate
LargeBedroom/Window/Battery

Get it?

Yes I got it. Thanks for the suggestion and help.

How to code different devices in nodemcu? For Eg.LivingRoom_TVLight
LivingRoom_DeskLight

You need your nodemcu to subscribe to different topics
LivingRoom_TVLight is an openhab item
The topic would be LivingRoom/TVLight

I wrote different topics like this in code


char* lightTopic = "room1/light";
char* fanTopic = "room1/fan";
char* tvTopic = "room1/tv";

How the node mcu know which topic is related to which device? How to write it in here

void callback(char* topic, byte* payload, unsigned int length) {

  //convert topic to string to make it easier to work with
  String topicStr = topic; 

  //Print out some debugging info
  Serial.println("Callback update.");
  Serial.print("Topic: ");
  Serial.println(topicStr);

  //turn the light on if the payload is '1' and publish to the MQTT server a confirmation message
  if(payload[0] == '1'){
    digitalWrite(relay1, HIGH);
    client.publish("confirm", "Light On");

  }

  //turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
  else if (payload[0] == '0'){
    digitalWrite(relay1, LOW);
    client.publish("confirm", "Light Off");
  }

}

This is basic coding

You have a line clients.subscribe
Add 2 more with your other topics
In the call back function
If this topic then

If that topic then


All due respect ajay, but I can’t do your coding for you. Have a go yourself, try things. If it doesn’t work, try again. When you get really stuck then come back but don’t start asking " Do my code" at the first hurdle.

1 Like

Sorry @vzorglub. I have been trying to get this thing working since a month. So when I got this working, out of anxiety to get this work at the quickest I asked to find the solution to it. But what you said is right, I have to learn and try.

We got the basics working together. You need to read the docs again and again.
For the nodemcu read the existing code. Understand it. It’s not that hard. Then you’ll be able to add bits to it
Good luck. Break things and enjoy most of all