PubSubClient connect() falla con rc=2 cuando construyo el ID de cliente a partir de objetos String
Traducido del English por IA ·
Caso raro. ESP32, Arduino core 2.0.14, PubSubClient 2.8. Esto conecta bien siempre:
mqtt.connect("barn-01", "my_access_token", "");
Pero quiero que el ID de cliente salga de la MAC para poder flashear el mismo sketch en cinco placas, y el token viene de una estructura de ajustes. Así que hice esto:
const char* clientId = (String("barn-") + WiFi.macAddress()).c_str();
const char* token = settings.token.c_str();
mqtt.setServer(host.c_str(), 8883);
if (!mqtt.connect(clientId, token, "")) {
Serial.println(mqtt.state());
}
Ahora imprime 2 sin parar. Mismo token, mismo host. Me estoy volviendo loco. ¿Son los dos puntos de la dirección MAC?
Weird one. ESP32, Arduino core 2.0.14, PubSubClient 2.8. This connects fine every time:
mqtt.connect("barn-01", "my_access_token", "");
But I want the client ID to come from the MAC so I can flash the same sketch to five boards, and the token comes from a settings struct. So I did this:
const char* clientId = (String("barn-") + WiFi.macAddress()).c_str();
const char* token = settings.token.c_str();
mqtt.setServer(host.c_str(), 8883);
if (!mqtt.connect(clientId, token, "")) {
Serial.println(mqtt.state());
}
Now it prints 2 forever. Same token, same host. I’m going slightly mad. Is it the colons in the MAC address?
Traducido del English por IA ·
Tenía algo parecido, añadí un delay(500) antes de connect y desapareció.
I had something like this, added a delay(500) before connect and it went away.
Traducido del English por IA ·
¿Puedes imprimir lo que contiene realmente clientId justo antes de connect?
Can you print what clientId actually contains right before connect?
Traducido del English por IA ·
rc=2 es «client ID rejected» (ID de cliente rechazado). Los dos puntos están permitidos en los ID de cliente de Hermetry (letras, dígitos y . _ : -, de 1 a 64 caracteres), así que no es el formato MAC. Algo más está entrando en el ID.
rc=2 is «client ID rejected». Colons are allowed in Hermetry client IDs (letters, digits and . _ : -, 1 to 64 chars), so it’s not the MAC format. Something else is getting into the ID.
Traducido del English por IA ·
Lo imprimí, y son datos basura:
clientId=[□□?□barn-]
a veces vacío, a veces corrupto. El retardo no cambió nada.
Printed it, and it’s garbage:
clientId=[□□?□barn-]
sometimes empty, sometimes junk. The delay didn’t change anything.
Traducido del English por IA ·
El String desaparece antes de que lo uses. (String("barn-") + WiFi.macAddress()) crea un temporal que se destruye al final de esa línea, así que clientId apunta a memoria liberada. Lo que haga el heap después acaba en tu ID de cliente. Me pasó con una placa de sensores hace años y perdí un día entero.Lo mismo con setServer(host.c_str(), ...): PubSubClient guarda el puntero, no una copia, así que si host es un String local en setup() tendrás fallos extraños de reconexión más tarde.Usa buffers que vivan tanto como el cliente:
static char clientId[32];
static char brokerHost[64];
void setupMqtt() {
uint8_t mac[6];
WiFi.macAddress(mac);
snprintf(clientId, sizeof(clientId), "barn-%02x%02x%02x", mac[3], mac[4], mac[5]);
strlcpy(brokerHost, settings.host.c_str(), sizeof(brokerHost));
mqtt.setServer(brokerHost, 8883);
}
// later
mqtt.connect(clientId, settings.token.c_str(), "");
settings.token.c_str() está bien dentro de la llamada siempre que settings sea global.
The String is gone before you use it. (String("barn-") + WiFi.macAddress()) makes a temporary that’s destroyed at the end of that line, so clientId points into freed memory. Whatever the heap does next ends up in your client ID. Bit me on a sensor board years ago and I wasted a day too.
Same trap with setServer(host.c_str(), ...): PubSubClient keeps the pointer, not a copy, so if host is a local String in setup() you’ll get odd reconnect failures later.
Use buffers that live as long as the client:
static char clientId[32];
static char brokerHost[64];
void setupMqtt() {
uint8_t mac[6];
WiFi.macAddress(mac);
snprintf(clientId, sizeof(clientId), "barn-%02x%02x%02x", mac[3], mac[4], mac[5]);
strlcpy(brokerHost, settings.host.c_str(), sizeof(brokerHost));
mqtt.setServer(brokerHost, 8883);
}
// later
mqtt.connect(clientId, settings.token.c_str(), "");
settings.token.c_str() is fine inside the call as long as settings lives globally.
Traducido del English por IA ·
Era eso. Buffers estáticos y conecta a la primera en las cinco placas. Además, había creado el host en setup() exactamente como dijiste, lo que explica los fallos de reconexión aleatorios que yo atribuía al Wi-Fi. Gracias, Laura.
That was it. Static buffers and it connects first time on all five boards. I’d also been building the host in setup() exactly like you said, which explains the random reconnect failures I’d been blaming on my Wi-Fi. Thanks Laura.
- Debes estar registrado para responder a este debate.
Únete a la conversación
Inicia sesión para preguntar y responder, dar me gusta a las publicaciones útiles y marcar la respuesta que resolvió tu problema. Cada aportación suma puntos y niveles.

