Connecting ESP32 to ThingsBoard via MQTT for Telemetry
Connecting an ESP32 to ThingsBoard via MQTT is an industry-standard method for collecting, visualizing, and managing enterprise IoT telemetry. ThingsBoard provides an open-source platform for device provisioning, rule engine automations, and dynamic cloud dashboard visualization.
1. Device provisioning and authentication credentials
Create a new device profile in your ThingsBoard instance (Cloud or Community Edition). Assign an Access Token authentication credential. In your ESP32 firmware, this token serves as the MQTT username, while the password field is left empty.
2. Publishing telemetry topics
ThingsBoard listens for time-series sensor data on standard MQTT topics. Format telemetry as a valid JSON string and publish to v1/devices/me/telemetry:
- Publish simple key-value pairs:
{"temperature": 24.5, "humidity": 60.2}. - Publish client-side attributes (e.g., firmware version, IP address) to
v1/devices/me/attributes. - Use the
PubSubClientor officialThingsBoardC++ library for streamlined buffering.
3. Handling bidirectional Remote Procedure Calls (RPC)
ThingsBoard allows server-side dashboard buttons to trigger actuator actions on the ESP32. Subscribe to v1/devices/me/rpc/request/+ to receive RPC commands (such as toggling relays or updating PID setpoints) and send confirmation responses back to the server. For network comparisons, consult our guide on MQTT vs HTTP protocols[cite: 1].
4. Managing network retries and non-blocking loops
Ensure your MQTT reconnect loop does not block sensor reads. Implement an exponential backoff timer so that if the WiFi gateway drops, the ESP32 continues sampling local buffers without locking up.
When to get help
If you'd rather have this handled directly, see our IoT Cloud & Telemetry Development Services for scope and turnaround times.