[SOLVED] MQTT not connecting to nodemcu

There is no openhab2 folder at /var/log

I have one

openhab@openhab:~$ cd /var/log/openhab2
openhab@openhab:/var/log/openhab2$ ls -l
total 14616
-rw-r--r-- 1 openhab openhab     4235 Apr 29 08:34 audit.log
-rw-r--r-- 1 openhab openhab 13074242 May 15 07:48 events.log
-rw-r--r-- 1 openhab openhab  1872149 May 15 07:47 openhab.log
-rwxr-xr-x 1 openhab openhab        0 May 15 02:10 Readme.txt
openhab@openhab:/var/log/openhab2$ 

I suspect something went wrong when you installed OH. Remove it and install in again.

okay

I got this log

2018-05-15 12:32:04.893 [INFO ] [.dashboard.internal.DashboardService] - Started dashboard at http://192.168.43.102:8080
2018-05-15 12:32:04.903 [INFO ] [.dashboard.internal.DashboardService] - Started dashboard at https://192.168.43.102:8443
2018-05-15 12:32:10.528 [INFO ] [thome.model.lsp.internal.ModelServer] - Started Language Server Protocol (LSP) service on port 5007
2018-05-15 12:33:15.926 [INFO ] [er.internal.HomeBuilderDashboardTile] - Started Home Builder at /homebuilder
2018-05-15 12:33:15.976 [INFO ] [arthome.ui.paper.internal.PaperUIApp] - Started Paper UI at /paperui
2018-05-15 12:33:16.033 [INFO ] [panel.internal.HABPanelDashboardTile] - Started HABPanel at /habpanel
2018-05-15 12:33:16.213 [INFO ] [basic.internal.servlet.WebAppServlet] - Started Basic UI at /basicui/app
2018-05-15 12:36:27.512 [INFO ] [el.core.internal.ModelRepositoryImpl] - Loading model 'default.items'
2018-05-15 12:36:41.770 [INFO ] [penhab.io.transport.mqtt.MqttService] - MQTT Service initialization completed.
2018-05-15 12:36:41.772 [INFO ] [t.mqtt.internal.MqttBrokerConnection] - Starting MQTT broker connection 'broker'
2018-05-15 12:36:41.854 [ERROR] [penhab.io.transport.mqtt.MqttService] - Error starting broker connection
org.eclipse.paho.client.mqttv3.MqttException: Unable to connect to server
	at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:79) [208:org.openhab.io.transport.mqtt:1.11.0]
	at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650) [208:org.openhab.io.transport.mqtt:1.11.0]
	at java.lang.Thread.run(Thread.java:748) [?:?]
Caused by: java.net.ConnectException: Connection refused (Connection refused)
	at java.net.PlainSocketImpl.socketConnect(Native Method) ~[?:?]
	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[?:?]
	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[?:?]
	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[?:?]
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[?:?]
	at java.net.Socket.connect(Socket.java:589) ~[?:?]
	at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:70) ~[?:?]
	... 2 more
2018-05-15 12:36:41.896 [ERROR] [org.apache.felix.configadmin        ] - Cannot use configuration org.openhab.mqtt for [org.openhab.core.scriptengine.action.ActionService, org.osgi.service.cm.ManagedService, id=326, bundle=209/mvn:org.openhab.action/org.openhab.action.mqtt/1.11.0]: No visibility to configuration bound to mvn:org.openhab.io/org.openhab.io.transport.mqtt/1.11.0
2018-05-15 12:36:47.614 [INFO ] [el.core.internal.ModelRepositoryImpl] - Loading model 'default.sitemap'

It shows error starting broker connection

org.eclipse.paho.client.mqttv3.MqttException: Unable to connect to server
	at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:79) [208:org.openhab.io.transport.mqtt:1.11.0]
	at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650) [208:org.openhab.io.transport.mqtt:1.11.0]
	at java.lang.Thread.run(Thread.java:748) [?:?]
Caused by: java.net.ConnectException: Connection refused (Connection refused)```

Connection refused

Did you put an MQTT username and password in you nodeMCU code?

Try commenting out the broker.user and broker.pwd lines in your mqtt.cfg file
And tail your log so you can see what’s happening in real time

Yes, When I see in the serial monitor my nodemcu is connecting to the MQTT

same error

I tried commenting user and Password. changed broker name to mymqtt

You didn’t need to change the broker name. Now that you have done that, you also need to change it in your item:

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

Does it work?
Do you see anything in your console on the mqtt client?
What does the log show?

Yes I changed it in items also. But no result. Same error

Do you see anything in your console on the mqtt client?
What does the log show?
What username and passworrd did you set up for your broker?

Show me your mosquitto.conf
nano /etc/mosquitto/conf.d/default.conf

listener 1883 localhost

allow_anonymous false
password_file /etc/mosquitto/passwd

Nothing in my mqtt console

log shows same error starting broker connection

Change it to

port 1883

allow_anonymous true
password_file /etc/mosquitto/passwd

stop and start mosquitto

Yes, Now I am getting massages on my console. I changed the first line, but not the second line. Changing second line caused the same connection problem, leaving it as it is solved the problem.

will test on nodemcu

Now the problem comes with nodemcu. I connected a relay to GPIO0 and passing the command to this by topic light (Don’t be confused). Used onboard LED to indicate the wifi connection status. On start, the node is connecting to MQTT, and disconnecting after sometime itself or immediately after I toggle openhab switch between on and off with this message and reconnecting my wifi

Attempting MQTT connection...	MQTT Connected
Attempting MQTT connection...	MQTT Connected
Attempting MQTT connection...	MQTT Connected
Attemptin
Soft WDT reset

ctx: cont 
sp: 3ffefaf0 end: 3ffefd60 offset: 01b0

>>>stack>>>
3ffefca0:  3ffeecec 00000001 3ffe8bf9 402046d0  
3ffefcb0:  00000020 00000009 3ffe88f8 402046d0  
3ffefcc0:  3ffeed0c 0000000f 3ffeed0c 3ffeed38  
3ffefcd0:  3ffeed0c 3ffeeadc 3ffeed0c 40203cc9  
3ffefce0:  3ffe88ef 3ffeeadc 3ffefd1c 40100690  
3ffefcf0:  3ffeed0c 3ffeeadc 3ffeea08 40203cdc  
3ffefd00:  3ffeed0c 3ffeeadc 3ffeea08 40202231  
3ffefd10:  00000000 00000000 00000000 00000000  
3ffefd20:  00000000 00000000 2fe83a2c 3ffe2503  
3ffefd30:  3fffdad0 00000000 3ffeed30 4020230a  
3ffefd40:  feefeffe feefeffe feefeffe 40204248  
3ffefd50:  feefeffe feefeffe 3ffeed40 40100710  
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16 
tail 8
chksum 0x2d
csum 0x2d
v614f7c32
~ld
Connecting to ajay
.................................

My nodemcu is here,

#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;
}

It’s a power issue. You are now trying to power a relay with your nodemcu. Sometimes they struggle. Power the relay from your power supply or from the raw power pin of you nodemcu.

Disregard the code changes above. I’ll delete them

I tried powering my relay with another power supply by connecting nodemcu and relay to common ground. But the problem still exists

Disconnect your relay, does the problem persist?
Have you got a multimeter?
Can you check that PIN 2 toggle when you action the switch on openHAB?