pubsubclient: Can't connect to Broker

Hi, i cant connect to broker on my raspberry. Broker: Mosquitto 1.4.10

on serial i m getting rc=-2 acording to documentation it is network connection failed. On mosquitto log i m getting New connection from 192.168.1.111 on port 1883 for the first few minutes and then these errors occur:

1474494793: New connection from 192.168.1.111 on port 1883.
1474494802: Client <unknown> has exceeded timeout, disconnecting.
1474494802: Socket error on client <unknown>, disconnecting.
1474494813: New connection from 192.168.1.111 on port 1883.
1474494822: Client <unknown> has exceeded timeout, disconnecting.
1474494822: Socket error on client <unknown>, disconnecting.
1474494833: New connection from 192.168.1.111 on port 1883.
1474494842: Client <unknown> has exceeded timeout, disconnecting.
1474494842: Socket error on client <unknown>, disconnecting.

As you can see networking seems fine and there is some other issue with communication between arduino and rpi. Remote client on my laptop connects to the broker without any problems.

Hardware i m using is: arduino nano with ethernet shield (the one with the sd card slot)

my sketch: basicly copied example with delay between connections rised to 20s:

/*
 Basic MQTT example

 This sketch demonstrates the basic capabilities of the library.
 It connects to an MQTT server then:
  - publishes "hello world" to the topic "outTopic"
  - subscribes to the topic "inTopic", printing out any messages
    it receives. NB - it assumes the received payloads are strings not binary

 It will reconnect to the server if the connection is lost using a blocking
 reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
 achieve the same result without blocking the main loop.

*/

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>


// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xBD, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 111);
IPAddress server(192, 168, 1, 100);

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

EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("arduinoClient1234")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic","hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(20000);
    }
  }
}

void setup()
{
  Serial.begin(57600);

  client.setServer(server, 1883);
  client.setCallback(callback);

  Ethernet.begin(mac, ip);
  // Allow the hardware to sort itself out
  delay(5000);
  Serial.print("waiting 5s");
  client.connect("arduinoClient1234");
  delay(5000);
  if (client.connected()) {
    Serial.print("ok");
  }
  else {
    Serial.print("not ok");
  }

}

void loop()
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  client.publish("outTopic","hello world");
  delay(5000);

}

if u need more information i will be happy to share

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 91 (9 by maintainers)

Most upvoted comments

Hi Averri, I add WiFi.mode(WIFI_STA); above WiFi.begin(ssid, password);. It works.

Yes, I have tested, the WiFi is working fine:

Connecting to MyNet

WiFi connected
IP address:
192.168.1.159
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

The IP 192.168.99.100 is the Docker host IP, where the Mosquitto container is running. I have tested the Mosquitto using mqtt-spy client with success.

Are you able to test with Mosquitto running on Docker? docker run -ti -p 1883:1883 -p 9001:9001 toke/mosquitto

For ESP8266 the solution of the issue is; Add WiFi.mode(WIFI_STA); above WiFi.begin(ssid, password); https://github.com/knolleary/pubsubclient/issues/203#issuecomment-274112911 such as suggested by @rannanda

See #https://github.com/martin-ger/esp_wifi_repeater/issues/44#issuecomment-304994741

What does mean -1 in mqttClient.state?

I have problem with connection and state rc = - 1… What is this?

https://github.com/knolleary/pubsubclient/blob/master/src/PubSubClient.h line 48.

The connection to my MQTT broker on a raspberry worked for months… probably after an upgrade it started to fail, but not always… just most of the time. The solution for me was to move to broker from wireless to wired. Now using the wired-ip it works, on the wireless-ip most of time not!

still have the same problem…Attempting MQTT connection…failed, rc=-2 try again in 5 second. i tried above all advices …but no output

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

const char* ssid = “vivo V1”; const char* password = “qwer1234”; const char* mqtt_server = “192.168.137.72”;

WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; char msg[50]; int value = 0;

void setup_wifi() {

delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

}

void callback(char* topic, byte* payload, unsigned int length) { Serial.print(“Message arrived [”); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); }

void reconnect() { // Loop until we’re reconnected while (!client.connected()) { Serial.print(“Attempting MQTT connection…”); // Attempt to connect if (client.connect(“ESP8266Client”)) { Serial.println(“connected”); // Once connected, publish an announcement… client.publish(“outTopic”, “hello world”); // … and resubscribe client.subscribe(“inTopic”); } else { Serial.print(“failed, rc=”); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } }

void setup() { Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); }

void loop() {

if (!client.connected()) {
   yield(); 
    reconnect();
}
client.loop();

long now = millis();
if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
}

}

Update to the code in my post above. The MQTT reconnect issue is resolved. However, while looking over the serial output, I noticed that from time to time, I would get a WDT software reset. I added a yield() statement right after “while (!client.connected() && attempts < 15) {” and the watch dog timer is now happy. I’m also happy.

Hi,

I solved the issue the same way @carnifex82 did. I replaced WiFiClientSecure by WiFiClient

Hello, I’m running into the same problem and adding WiFi.mode(WIFI_STA); did not solve it for me. Any other ideas?

Hi,

Just tried the above fix but still get:

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

Thanks Stuart