Sin pantalla, sin teclado: cómo cargar Wi-Fi y un token en 12 nodos de laboratorio ESP32-C3
Traducido del English por IA ·
ok, esto es para un proyecto de la universidad, perdón si es el subforo equivocado. Estamos construyendo 12 pequeños nodos de calidad del aire (ESP32-C3 SuperMini + SCD41 + un PMS5003) que irán a distintos laboratorios del campus y enviarán datos a nuestra organización de Hermetry por MQTT. No tienen pantalla y el único botón es BOOT.Ahora mismo el SSID, la contraseña y el token de acceso del dispositivo son todos #defines en el sketch, así que cada nodo necesita su propia compilación. Con 2 prototipos estaba bien, pero para 12 no, y los técnicos de laboratorio que los van a mover no pueden usar el IDE.Lo que quiero: flashear el mismo firmware en todos, y luego, en el sitio, alguien conecta un teléfono al nodo, escribe la Wi-Fi del laboratorio, y el nodo obtiene de alguna forma su propia credencial de Hermetry. Encontré WiFiManager y la parte del portal cautivo funciona en el banco de pruebas. La parte del token no tengo ni idea. ¿Hay una forma habitual de hacer esto, o todo el mundo simplemente lo programa fijo en el código?
ok so this is for a uni project, sorry if it’s the wrong sub-forum. We’re building 12 little air quality nodes (ESP32-C3 SuperMini + SCD41 + a PMS5003) that go into different labs across campus and report to our Hermetry org over MQTT. They have no display and the only button is BOOT.
Right now the SSID, password and the device access token are all #defines in the sketch, so every node gets its own build. That was fine for 2 prototypes, it’s not fine for 12, and the lab techs who’ll move them around can’t run the IDE.
What I want: flash one identical firmware on all of them, then on site someone joins a phone to the node, types the lab Wi-Fi, and the node gets its own Hermetry credential somehow. I found WiFiManager and the captive portal part works on the bench. The token part I have no idea. Is there a normal way people do this, or does everyone just hardcode?
Traducido del English por IA ·
Quizás sea una pregunta tonta, pero ¿por qué no poner el Wi-Fi en el código una sola vez, si todo está en el mismo campus?
Possibly a dumb question but why not just put the Wi-Fi in the code once, if it’s all the same campus?
Traducido del English por IA ·
Por desgracia, no es la misma red en todas partes. Dos edificios están en un SSID IoT separado, un laboratorio tiene su propio router y las contraseñas se cambian cada semestre. Además, los tokens tienen que ser diferentes para cada nodo de todos modos.
Not the same network everywhere sadly. Two buildings are on a separate IoT SSID, one lab has its own router, and the passwords get rotated each term. Plus the tokens have to be different per node anyway.
Traducido del English por IA ·
¿WPS? Mantén pulsado BOOT durante 3 s, pulsa el botón del router, listo. Lo hice hace años con unos escáneres de almacén.
WPS? Hold BOOT for 3 s, press the button on the router, done. Did that on some warehouse scanners years ago.
Traducido del English por IA ·
El WPS está desactivado en casi todas las redes gestionadas que he visto, no contaría con él en una universidad. ¿Usáis el core de Arduino o ESP-IDF? IDF tiene un componente de provisioning sobre SoftAP o BLE que es más cómodo que un portal cautivo.
WPS is switched off on pretty much every managed network I’ve seen, I wouldn’t count on it at a uni. Are you on the Arduino core or ESP-IDF? IDF has a provisioning component over SoftAP or BLE that’s nicer than a captive portal.
Traducido del English por IA ·
Core de Arduino 2.0.14 en PlatformIO. No me importa seguir con WiFiManager para la parte de Wi-Fi; lo que me bloquea es el token de Hermetry. Tampoco quiero abrir la consola para crear 12 dispositivos y copiar 12 tokens en 12 portales, si puedo evitarlo.
Arduino core 2.0.14 in PlatformIO. Happy to stay with WiFiManager for the Wi-Fi bit, it’s the Hermetry token I’m stuck on. I don’t want to open the console and create 12 devices and copy 12 tokens into 12 portals either if I can avoid it.
Traducido del English por IA ·
No necesitas tokens por dispositivo en el firmware. Divide el problema en dos.Wi-Fi: mantén WiFiManager. Añade un campo personalizado en el portal si quieres un nombre de dispositivo amigable; si no, usa la MAC.Token: deja que el nodo pida el suyo. En el perfil del dispositivo abre la pestaña Provisioning, pon la estrategia en Allow creating new devices, guarda, luego pulsa Create key y copia el secreto (se muestra una sola vez). Esa clave y secreto son los mismos para las 12 compilaciones. En el primer arranque el nodo se conecta con el usuario provision y una contraseña vacía, se suscribe a v1/provision/res y publica su solicitud. La respuesta incluye su token de acceso; lo guardas en NVS y a partir de entonces inicia sesión normalmente.
// first boot only, after Wi-Fi is up
mqtt.setServer(host, 8883); // WiFiClientSecure, TLS
mqtt.connect(clientId, "provision", "");
mqtt.subscribe("v1/provision/res", 1);
String req = String("{"deviceName":"aq-") + mac6 +
"","provisionDeviceKey":"pk_xxx","provisionDeviceSecret":"ps_xxx"}";
mqtt.publish("v1/provision/req", req.c_str());
// in the callback: parse credentialsValue when status == "SUCCESS",
// prefs.putString("tok", value); then reconnect with the token as username
Dos cosas nos dieron problemas en una planta farmacéutica. Los dispositivos nuevos creados así acaban en cuarentena: se conectan, pero sus datos se descartan hasta que un administrador los active, así que avisa al responsable de la organización para que los busque. Y el nombre debe ser único; una segunda solicitud con el mismo nombre recibe device_exists, porque nunca entrega una credencial dos veces. Por eso no borres la NVS a la ligera. Los detalles están en Adding and claiming devices.
You don’t need per-device tokens in the firmware at all. Split it in two problems.
Wi-Fi: keep WiFiManager. Add one custom field in the portal if you want a friendly device name, otherwise use the MAC.
Token: let the node ask for its own. On the device profile open the Provisioning tab, set the strategy to Allow creating new devices, save, then Create key and copy the secret (it’s shown once). That key + secret is the same for all 12 builds. On first boot the node connects with username provision and an empty password, subscribes to v1/provision/res and publishes its request. The answer carries its access token, you store that in NVS and from then on it logs in normally.
// first boot only, after Wi-Fi is up
mqtt.setServer(host, 8883); // WiFiClientSecure, TLS
mqtt.connect(clientId, "provision", "");
mqtt.subscribe("v1/provision/res", 1);
String req = String("{"deviceName":"aq-") + mac6 +
"","provisionDeviceKey":"pk_xxx","provisionDeviceSecret":"ps_xxx"}";
mqtt.publish("v1/provision/req", req.c_str());
// in the callback: parse credentialsValue when status == "SUCCESS",
// prefs.putString("tok", value); then reconnect with the token as username
Two things bit us on a pharma site. New devices created this way land in quarantine, they connect but their data is dropped until an admin activates them, so tell whoever owns the org to look for them. And the name must be unique, a second request with the same name gets device_exists because it never hands out a credential twice. So never wipe NVS casually. Details are on Adding and claiming devices.
Traducido del English por IA ·
Funcionó, los 12 están activos. Enseguida me topé con lo de device_exists porque había borrado la flash del nodo 3 durante la depuración; ya se había registrado como aq-3c84a1. Eliminé ese dispositivo en la consola y luego se aprovisionó otra vez sin problemas. Los activé a todos desde cuarentena esta mañana. También tuve que escapar bien las comillas: mi primera versión enviaba JSON roto y no recibía nada de vuelta.
That worked, all 12 are up. I did hit the device_exists thing straight away because I’d erased flash on node 3 while debugging, it had already registered as aq-3c84a1. Deleted that device in the console and it provisioned again fine. Activated them all from quarantine this morning. Also had to escape the quotes properly, my first version sent broken JSON and just got nothing back.
Traducido del English por IA ·
Nosotros hacemos lo mismo en nuestros sensores de línea. Un consejo de planta: imprime el nombre del AP de configuración en una etiqueta pegada en la carcasa. Nadie recuerda seis meses después cuál nodo es «ESP-3C84A1».
We do the same on our line sensors. One tip from the floor: print the setup AP name on a sticker on the case. Nobody remembers which node is «ESP-3C84A1» six months later.
Traducido del English por IA ·
+1 a la pegatina. Además, si alguno de esos laboratorios solo tiene Wi-Fi empresarial con inicio de sesión por usuario, un portal cautivo normal no sirve; necesitarías campos de identidad/nombre de usuario y WPA2-Enterprise en el firmware. Pide mejor a TI una red IoT con PSK, mucho menos complicado.
+1 to the sticker. Also if any of those labs only has enterprise Wi-Fi with a per-user login, a plain captive portal can’t do it, you’d need identity/username fields and WPA2-Enterprise in the firmware. Ask IT for a PSK IoT network instead, much less pain.
- 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.

