El ESP32 se conecta en setup(), pero client.connected() es false unos segundos después en loop()
Traducido del English por IA ·
Laboratorio universitario, ESP32 DevKit, PubSubClient, WiFiClientSecure. En setup() me conecto a la Wi-Fi y a Hermetry, imprime «MQTT connected» y llega la primera lectura. Luego, en loop(), leo un BME280, publico y ejecuto delay(30000). A partir del segundo ciclo, client.connected() es false y client.state() es -3. Mi código de reconexión vuelve a conectar, pasa una lectura más y se repite. Es decir, recibo lecturas, pero la página del dispositivo alterna constantemente entre en línea y fuera de línea.
void loop() {
if (!client.connected()) reconnect();
float t = bme.readTemperature();
snprintf(buf, sizeof buf, "{"temperature":%.2f}", t);
client.publish("v1/telemetry", buf);
delay(30000);
}
El keepalive está en el valor predeterminado. No sé qué estoy haciendo mal, parece igual que en cualquier tutorial.
Uni lab, ESP32 DevKit, PubSubClient, WiFiClientSecure. In setup() I connect to Wi-Fi and to Hermetry, it prints «MQTT connected», and the first reading arrives. Then in loop() I read a BME280, publish, and delay(30000). From the second loop on client.connected() is false and client.state() is -3. My reconnect code connects again, one more reading gets through, and it repeats. So I get readings but the device keeps flipping online/offline on the device page.
void loop() {
if (!client.connected()) reconnect();
float t = bme.readTemperature();
snprintf(buf, sizeof buf, "{"temperature":%.2f}", t);
client.publish("v1/telemetry", buf);
delay(30000);
}
Keepalive is the default. I’m not sure what I’m doing wrong, it looks like every tutorial.
Traducido del English por IA ·
delay(30000) sin atender nada más. Ese es tu problema.
delay(30000) with nothing serviced. That’s your problem.
Traducido del English por IA ·
Revise también la pestaña Log del dispositivo para ver los motivos de la desconexión. Si ve «Taken over by a new session», otra placa está usando el mismo token.
Also check the device’s Log tab for the disconnect reasons. If you see «Taken over by a new session», another board is using the same token.
Traducido del English por IA ·
Tyler tiene razón en una línea, aquí va la versión larga. PubSubClient solo lee del socket y envía los pings dentro de client.loop(). Su keepalive por defecto es de 15 s. Usted duerme 30 s, así que no sale ningún ping, el broker lo desconecta tras keepalive_timeout, y el estado -3 es «connection lost».
Nunca bloquee en loop(), use un temporizador en su lugar:
unsigned long last = 0;
void setup() {
...
client.setKeepAlive(60);
client.setBufferSize(512);
}
void loop() {
if (!client.connected()) reconnect(); // with a back-off, not a tight loop
client.loop(); // every pass
if (millis() - last >= 30000) {
last = millis();
snprintf(buf, sizeof buf, "{"temperature":%.2f}", bme.readTemperature());
client.publish("v1/telemetry", buf);
}
}
Un keepalive entre 30 y 300 s es lo que recomienda la documentación. Y haga lo que dijo Niall: la pestaña Log indica el motivo de cada desconexión.
Tyler’s right in one line, here’s the longer version. PubSubClient only reads from the socket and sends pings inside client.loop(). Its default keepalive is 15 s. You sleep 30 s, so no ping goes out, the broker drops you for keepalive_timeout, and state -3 is «connection lost».
Never block in loop(), use a timer instead:
unsigned long last = 0;
void setup() {
...
client.setKeepAlive(60);
client.setBufferSize(512);
}
void loop() {
if (!client.connected()) reconnect(); // with a back-off, not a tight loop
client.loop(); // every pass
if (millis() - last >= 30000) {
last = millis();
snprintf(buf, sizeof buf, "{"temperature":%.2f}", bme.readTemperature());
client.publish("v1/telemetry", buf);
}
}
Keepalive between 30 and 300 s is what the docs recommend. And do what Niall said, the Log tab names the reason for every disconnect.
Traducido del English por IA ·
¡Resuelto, pero eran dos cosas! La pestaña Log mostraba keepalive_timeout Y «Taken over by a new session». Mi primer prototipo en protoboard seguía conectado a un cargador USB en casa con el mismo token. Lo desconecté, cambié a la versión con millis() y el dispositivo lleva 6 horas en línea.
Fixed, but it was two things! Log tab showed keepalive_timeout AND «Taken over by a new session». My first breadboard prototype was still plugged into a USB charger at home with the same token. Unplugged it, switched to the millis() version, and the device has been online for 6 hours.
Traducido del English por IA ·
La pestaña Log evita mucho adivinar. +1
The Log tab saves so much guessing. +1
- 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.

