knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.79k stars 1.46k forks source link

MQTT Connection failed rc= -1 #927

Open Sava112233 opened 2 years ago

Sava112233 commented 2 years ago

Hello guys, I'm trying to connect my ESP8266 to my MQTT Broker, which runs on my pi. On my pi I'm using Mosquitto v2.0.11 and Node Red v2.2.0.
To try the connection I'm running the example program for the esp. While running I get as result Attempting MQTT connection...failed, rc=-1 try again in 5 seconds

What could be the problem?

Tom618s commented 2 years ago

Estou tendo o mesmo problema, mas no meu caso é na integração com o tasmota, diz a seguinte mesnagem, connection...failed smartnest.cz e a mesmo continuação da mensagem

deBaer commented 2 years ago

I observed some MQTT brokers (don't know which exactly as I'm not operating them myself) send 5 bytes of CONNACK with one byte of payload of 0x00. That leads to your observed behaviour because of

              if (len == 4) {
                if (buffer[3] == 0) {
                    lastInActivity = millis();
                    pingOutstanding = false;
                    _state = MQTT_CONNECTED;
                    return true;
                } else {
                    _state = buffer[3];
                }
            }

The behaviour of these brokers violates the MQTT standard, of course, but as the saying goes: Be conservative in what you send, but liberal in what you receive.

deBaer commented 2 years ago

No, wait, the problem is even earlier, in readPacket:

          if (len == 5) {
            // Invalid remaining length encoding - kill the connection
            _state = MQTT_DISCONNECTED;
            _client->stop();
            return 0;
        }
rksiazek commented 1 year ago

I have just faced the same problem. I'm using dockerized Mosquitto 2.0.14 broker running in local network. Don't know why, but the code that worked well in the past has broken somehow now.

I tried connecting to the broker with computer and phone (Android app) - in both cases everything worked seamlessly.

After some struggling around I dig to the code mentioned by @deBaer in his first post. In my case, the type of the MQTT frame read by ESP was 4 (PUBACK) and the length of the packet was about ~80bytes (!?).

I knew that:

so I decided to make some experiments with WiFiClient to check if there is nothing wrong with the networking layer and I managed to solve my problem.

The solution was flushing and stopping my WiFiClient after making HTTP requests (with dedicated lib) - which took place just after the startup of MCU and a moment before MQTT connection procedure:

    wifiClient.flush();
    wifiClient.stop();

After that, the MQTT client connected to the broker without any problem.

I'm aware that this will not apply to every case, but I think it is right to share that experience.