Skip to main content
2 of 4
edited tags
SagiZiv
  • 201
  • 1
  • 8

MQTT connection fails when using String objects

On my ESP32 I am trying to connect to my HomeAssistant server using ArduinoHA library.

I can easily connect when hard-coding the credentials: mqtt.begin("server", "username", "password");

But I recently tried to move the credentials to a config file that I read on setup:

typedef struct {
  String url;
  String username;
  String password;
} Credentials;


Credentials creds = readCredentials(credsFile);
mqtt.begin(creds.url.c_str(), creds.username.c_str(), creds.password.c_str());

The connection fails and the MQTT state returns -2 (StateConnectionFailed).

I tried comparing the read values to the hard-coded values:

  Serial.println(strcmp("192.168.1.45", creds.url.c_str()));
  Serial.println(strcmp("username", creds.username.c_str()));
  Serial.println(strcmp("passwird", creds.password.c_str()));

But it all returns 0 (i.e., its the same string).

Out of curiosity I tried it without reading the config file, and got same result:

  String url = "192.168.1.45";
  String username = "username";
  String password = "password";
  mqtt.begin(url.c_str(), username.c_str(), password.c_str());

So, does anyone know why the connection fails when using String object? Is there something I am missing?

SagiZiv
  • 201
  • 1
  • 8