Nodo IIoT con ESP32 y MQTTESP32 IIoT node over MQTT
Un nodo de campo que mide, publica y obedece: cuatro variables analógicas hacia una aplicación en Python, y comandos de vuelta hacia sus salidas, por un único tópico MQTT.
A field node that measures, publishes and obeys: four analog variables up to a Python application, and commands back down to its outputs, over a single MQTT topic.
01ResumenSummary
El proyecto conecta un ESP32 con una aplicación de escritorio en Python mediante MQTT. El microcontrolador lee temperatura, humedad, consumo eléctrico e iluminación, los publica como JSON y, en el mismo canal, recibe órdenes para dos salidas digitales y dos analógicas. Es una base reutilizable para supervisar y operar equipos por red.
The project connects an ESP32 to a Python desktop application over MQTT. The microcontroller reads temperature, humidity, power consumption and light level, publishes them as JSON and, on the same channel, receives orders for two digital and two analog outputs. It is a reusable foundation for monitoring and operating equipment over a network.
02ProblemaProblem
Supervisar un equipo suele exigir estar a su lado o instalar software propietario y cableado dedicado. Para prototipos, laboratorios o pequeñas instalaciones hace falta una forma ligera de ver las variables en tiempo real y actuar sobre el equipo desde otra máquina.
Monitoring equipment usually means standing next to it, or installing proprietary software and dedicated wiring. Prototypes, labs and small installations need a lightweight way to see variables in real time and act on the equipment from another machine.
03ObjetivosGoals
- Leer cuatro señales analógicas y expresarlas en unidades de ingeniería.Read four analog signals and express them in engineering units.
- Publicar las mediciones con un formato simple y legible (JSON).Publish measurements in a simple, readable format (JSON).
- Recibir comandos digitales y analógicos sin un segundo canal de comunicación.Receive digital and analog commands without a second communication channel.
- Recuperarse solo ante pérdidas de conexión.Recover on its own from connection drops.
04Solución implementadaImplemented solution
El firmware lee las entradas cada segundo, escala la lectura del ADC de 12 bits (0–4095) al rango de cada variable y publica un documento JSON cada dos segundos. Cuando llega un mensaje con las claves bool1, bool2, float1 o float2, actualiza el estado de las salidas. En el lado de la PC, una aplicación en Flet usa paho-mqtt para suscribirse, mostrar los valores y enviar los comandos.
The firmware reads the inputs every second, scales the 12-bit ADC reading (0–4095) to each variable's range and publishes a JSON document every two seconds. When a message arrives with the keys bool1, bool2, float1 or float2, it updates the outputs. On the PC side, a Flet application uses paho-mqtt to subscribe, display the values and send commands.
{ "temperatura": 23.41, "humedad": 61.20,
"consumo": 845.73, "iluminacion": 4120.50 }05Arquitectura técnicaTechnical architecture
- Campo: entradas analógicas GPIO 36, 39, 34 y 35.Field: analog inputs GPIO 36, 39, 34 and 35.
- Control: ESP32 con WiFi, PubSubClient y ArduinoJson.Control: ESP32 with WiFi, PubSubClient and ArduinoJson.
- Comunicación: broker MQTT (puerto 1883) y un único tópico
ESP32/Datos.Communication: MQTT broker (port 1883) and a single topicESP32/Datos. - Software: aplicación en Python con Flet y paho-mqtt.Software: Python application with Flet and paho-mqtt.
06Mi contribuciónMy contribution
Diseñé y programé el firmware, definí el contrato de mensajes (claves, tipos y rangos) y desarrollé la integración con la aplicación en Python. También documenté los pasos de instalación de la placa y las librerías dentro del propio código.
I designed and programmed the firmware, defined the message contract (keys, types and ranges) and built the integration with the Python application. I also documented the board and library setup steps inside the code itself.
07Decisiones de diseño e ingenieríaDesign & engineering decisions
- Un solo tópico para datos y comandosOne topic for data and commands
- Simplifica la configuración del broker y de la app; los mensajes se distinguen por sus claves JSON.Simplifies broker and app setup; messages are told apart by their JSON keys.
- JSON en lugar de cadenas propiasJSON instead of custom strings
- Se puede leer, depurar y ampliar con nuevas variables sin romper a los consumidores existentes.It can be read, debugged and extended with new variables without breaking existing consumers.
- Lectura (1 s) separada del envío (2 s)Reading (1 s) separate from sending (2 s)
- Desacopla la frecuencia de muestreo del tráfico de red, controlado con millis() sin bloquear el bucle.Decouples sampling rate from network traffic, timed with millis() without blocking the loop.
- Escalado en el nodoScaling at the node
- La app recibe unidades de ingeniería, no cuentas del ADC, y no necesita conocer el hardware.The app receives engineering units, not ADC counts, and doesn't need to know the hardware.
08Dificultades y solucionesChallenges & solutions
- Conexiones inestables: el bucle verifica la sesión MQTT en cada ciclo y reintenta la conexión cada 5 s.Unstable connections: the loop checks the MQTT session every cycle and retries every 5 s.
- Mensajes malformados: el JSON recibido se valida; si falla el parseo, el comando se descarta y se registra por el puerto serie.Malformed messages: incoming JSON is validated; if parsing fails, the command is discarded and logged over serial.
- Comandos parciales: cada clave se aplica solo si está presente, así la app puede enviar un único valor.Partial commands: each key is applied only if present, so the app can send a single value.
09ResultadosResults
Funcionalidades implementadas y verificables en el código: publicación periódica de cuatro variables escaladas, recepción bidireccional por un mismo tópico, aplicación de cuatro comandos (dos digitales y dos analógicos), reconexión automática y registro de diagnóstico por puerto serie. No se reportan métricas de campo porque el proyecto se presenta como base de desarrollo.
Features implemented and verifiable in the code: periodic publishing of four scaled variables, bidirectional exchange over a single topic, four applied commands (two digital, two analog), automatic reconnection and diagnostic logging over serial. No field metrics are reported because the project is presented as a development foundation.
10Imágenes y diagramasImages & diagrams
| SeñalSignal | TipoType | Rango / claveRange / key |
|---|---|---|
| TemperaturaTemperature | AI · GPIO 36 | 0 – 40 °C |
| HumedadHumidity | AI · GPIO 39 | 0 – 100 % |
| Consumo eléctricoPower consumption | AI · GPIO 34 | 0 – 2000 W |
| IluminaciónLight level | AI · GPIO 35 | 0 – 10 000 lx |
| Salidas digitalesDigital outputs | DO ×2 | bool1 · bool2 |
| Salidas analógicasAnalog outputs | AO ×2 | float1 · float2 (0 – 100) |
Mapa de E/S tomado del firmware. El diagrama de arquitectura está al inicio de la página.I/O map taken from the firmware. The architecture diagram is at the top of the page.
11AprendizajesLearnings
Definir primero el contrato de mensajes ordena todo lo demás: el firmware y la aplicación pueden evolucionar por separado mientras respeten las mismas claves. Para un entorno de producción, el siguiente paso es usar un broker propio con autenticación y TLS, y separar tópicos de telemetría y de mando.
Defining the message contract first organizes everything else: firmware and application can evolve independently as long as they honor the same keys. For a production environment, the next step is a private broker with authentication and TLS, and separate telemetry and command topics.