Dirección del broker escrita como texto en una página de configuración: ¿cómo convierto la cadena en algo que pueda usar el ESP32?
Traducido del English por IA ·
Aquí estoy otra vez. He añadido una pequeña página de configuración a mis placas ESP32 (WiFiManager con un parámetro personalizado) para poder escribir la dirección del broker MQTT en el navegador en lugar de fijarla en el código. El parámetro llega como String, por ejemplo «192.168.1.40» para mi Mosquitto de prueba en la Pi.PubSubClient espera un IPAddress en setServer() en el ejemplo que copié, y no consigo pasar de «192.168.1.40» a IPAddress. Probé IPAddress ip = brokerStr; y no compila. Cuando esto funcione, quiero apuntar las mismas placas a Hermetry en lugar de a la Pi.
Me again. I’ve added a little setup page to my ESP32 boards (WiFiManager with a custom parameter) so I can type the MQTT broker address in the browser instead of hardcoding it. The parameter comes back as a String, e.g. «192.168.1.40» for my test Mosquitto on the Pi.
PubSubClient wants an IPAddress in setServer() in the example I copied, and I can’t figure out how to get from «192.168.1.40» to IPAddress. I tried IPAddress ip = brokerStr; and it doesn’t compile. Once this works I want to point the same boards at Hermetry instead of the Pi.
Traducido del English por IA ·
Podrías dividirla por los puntos, convertir cada parte con atoi y luego usar IPAddress(a, b, c, d). Eso es lo que hice una vez.
You could split it on the dots and atoi each part, then IPAddress(a, b, c, d). That’s what I did once.
Traducido del English por IA ·
Eso funciona, pero existe una forma integrada. Además, la parte de Hermetry cambia un poco la pregunta.
That works but there’s a built-in way. Also, the Hermetry part changes the question a bit.
Traducido del English por IA ·
IPAddress tiene fromString(), así que no hace falta dividir nada:
IPAddress ip;
if (ip.fromString(brokerStr)) {
client.setServer(ip, 1883);
}
Pero el punto de Ciaran: para Hermetry no quieres usar una IP en absoluto. Su broker es TLS en el 8883 y necesita SNI, así que debes conectarte por nombre de host. setServer() tiene una versión que acepta un nombre de host, que también funciona para tu Pi si escribes su nombre o IP como texto:
char brokerHost[64]; // global, lives as long as the program
void applyConfig(const String &s) {
s.toCharArray(brokerHost, sizeof(brokerHost));
client.setServer(brokerHost, 8883);
}
El buffer global es lo importante. PubSubClient guarda el puntero que le pasas, no copia el texto. Si pasas brokerStr.c_str() desde un String que sale de ámbito al final de setup(), el puntero queda colgando y la placa intentará conectarse a basura más adelante. Perdí una tarde entera con eso en mi proyecto de fin de carrera: la placa se conectaba en el primer arranque y nunca más después de una reconexión.Haz que el parámetro sea lo bastante largo para el host de Hermetry en la tarjeta de Detalles de conexión de tu dispositivo; 64 caracteres son más que suficientes.
IPAddress has fromString(), so no splitting needed:
IPAddress ip;
if (ip.fromString(brokerStr)) {
client.setServer(ip, 1883);
}
But Ciaran’s point: for Hermetry you don’t want an IP at all. Its broker is TLS on 8883 and needs SNI, so you must connect by host name. setServer() has a version that takes a host name, which works for your Pi too if you type its name or IP as text:
char brokerHost[64]; // global, lives as long as the program
void applyConfig(const String &s) {
s.toCharArray(brokerHost, sizeof(brokerHost));
client.setServer(brokerHost, 8883);
}
The global buffer is the important bit. PubSubClient keeps the pointer you pass, it doesn’t copy the text. If you pass brokerStr.c_str() from a String that goes out of scope at the end of setup(), the pointer dangles and it’ll try to connect to garbage later. I lost an afternoon to that in my final year project, the board connected on first boot and then never again after a reconnect.
Make the parameter long enough for the Hermetry host on your device’s Connection details card, 64 characters is plenty.
Traducido del English por IA ·
fromString funcionó en la Pi, y luego cambié a la versión con buffer char. Aoife, tenías razón con el puntero: mi primer intento con c_str() conectó una vez y luego falló en cada reconexión con rc=-2. Con el buffer global funciona, y la placa del shed ya se comunica con Hermetry con el host escrito en la página de configuración.
fromString worked for the Pi, and then I switched to the char buffer version. Aoife you were right about the pointer: my first try with c_str() connected once and then failed every reconnect with rc=-2. With the global buffer it’s fine, and the shed board is now talking to Hermetry with the host typed into the setup page.
- 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.

