Broker address typed into a config page as text: how do I turn the string into something the ESP32 can use?
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.
You could split it on the dots and atoi each part, then IPAddress(a, b, c, d). That’s what I did once.
That works but there’s a built-in way. Also, the Hermetry part changes the question a bit.
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.
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.

