knolleary / pubsubclient

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

can not setup a fixed client ID #973

Open Gendiaaa opened 1 year ago

Gendiaaa commented 1 year ago

Hello all i am trying to give my esp32 client a fixed client id but always fails after running for couple of seconds the error code is MQTT_CONNECT_BAD_CLIENT_ID 2 or sometimes comes MQTT_CONNECT_BAD_CREDENTIALS 4 also -2 happens this was the code for reconnect function

void reconnect() {
  while (!client.connected()) {
    if (client.connect( AIO_USERNAME,mqttUserName, mqttPwd)) {
      Serial.println("MQTT connected");

     client.subscribe(buf1 , MQTTsubQos); // buf1 = AIO_USERNAME/doser/#
    }
    else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 ");
      delay(100);  // wait 5sec and retry
    }

  }

}

after that i changed the function to this

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = AIO_USERNAME;
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqttUserName,mqttPwd)) {
      Serial.println("connected");
      digitalWrite(MQTT_LED , HIGH);
      client.subscribe(buf1,MQTTsubQos);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 2 seconds");
       digitalWrite(MQTT_LED , LOW);
      delay(1000);
    }
  }
}

but really i do not know the reason and sometimes i feel the response between the client and the broker is too much slow also

Gendiaaa commented 1 year ago

No could solve this or explain the reason why ?

Gendiaaa commented 1 year ago

Plz any one help

knolleary commented 1 year ago

Hi @Gendiaaa

I've edited your issue to properly format the code blocks so they are readable.

It is the broker saying you have a bad clientID or username/password. We cannot tell you what is wrong with them as it is the broker that decides what is valid.

All I can say is check you are setting them to valid values.

Gendiaaa commented 1 year ago

My broker is hivemq broker uploaded to amazon aws instance is there are any special setting for the broker that i am missing to set ? I do not know maybe too many request to the broker that could block the client maybe if its the same client name send too many data in short time or trying to reconnect to many times maybe ? I just want if there are any special configuration or parameters to check or edit

knolleary commented 1 year ago

Sorry, I cannot help with broker configuration issues. There are too many brokers out there and they all have their own set of requirements.