Introduction
In this tutorial, you will learn how to build a Flask web dashboard for real-time visualization of MQTT data from ESP32 sensors. We will cover everything from setting up your environment to deploying the dashboard. By the end, you will have a functional web application that displays sensor data in real-time.
Prerequisites
- Basic knowledge of Python and Flask
- MQTT broker (e.g., Mosquitto) installed and running
- ESP32 development board with MicroPython or Arduino firmware
- Python 3.x installed on your system
- Required Python packages: Flask, paho-mqtt, and Flask-SocketIO
Parts/Tools
- ESP32 development board
- Computer with Python environment
- MQTT broker (e.g., Mosquitto)
- Web browser for viewing the dashboard
Steps
1. Set Up Your MQTT Broker
- Install Mosquitto on your computer:
- Start the Mosquitto service:
- Ensure Mosquitto is running:
sudo apt-get install mosquitto
sudo systemctl start mosquitto
sudo systemctl status mosquitto
2. Configure Your ESP32
- Connect your ESP32 to your computer and open the IDE (Arduino or MicroPython).
- Install the necessary libraries for MQTT.
- Use the following sample code to publish sensor data:
import network
import time
from umqtt.simple import MQTTClient
def connect_wifi():
# Connect to Wi-Fi
ssid = 'YOUR_SSID'
password = 'YOUR_PASSWORD'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
time.sleep(1)
def publish_data():
client = MQTTClient("esp32", "mqtt_broker_address")
client.connect()
while True:
sensor_data = read_sensor_data() # Replace with actual sensor reading
client.publish("sensor/topic", str(sensor_data))
time.sleep(5) # Publish every 5 seconds
connect_wifi()
publish_data()
3. Create the Flask Application
- Create a new directory for your project:
- Create a virtual environment and activate it:
- Install Flask and other required packages:
- Create a new file named app.py and add the following code:
mkdir flask_dashboard && cd flask_dashboard
python3 -m venv venv
source venv/bin/activate
pip install Flask paho-mqtt Flask-SocketIO
from flask import Flask, render_template
from flask_socketio import SocketIO
import paho.mqtt.client as mqtt
app = Flask(__name__)
socketio = SocketIO(app)
# MQTT setup
mqtt_client = mqtt.Client()
def on_message(client, userdata, message):
data = message.payload.decode()
socketio.emit('sensor_data', {'data': data})
mqtt_client.on_message = on_message
mqtt_client.connect("mqtt_broker_address")
mqtt_client.subscribe("sensor/topic")
mqtt_client.loop_start()
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app)
4. Create the Dashboard HTML Template
- Create a new directory named templates and a file named index.html inside it.
- Add the following HTML code to index.html:
<!DOCTYPE html>
<html>
<head>
<title>Real-Time Sensor Data</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.3/socket.io.js"></script>
<script>
var socket = io();
socket.on('sensor_data', function(msg) {
document.getElementById('data').innerHTML = msg.data;
});
</script>
</head>
<body>
<h1>Real-Time Sensor Data</h1>
<div id="data">No data yet</div>
</body>
</html>
5. Run the Flask Application
- Run the Flask application:
- Open your web browser and navigate to http://127.0.0.1:5000 to view the dashboard.
python app.py
Troubleshooting
- Cannot connect to MQTT broker: Ensure that the broker is running and you have the correct address.
- Data not showing in the dashboard: Check if the ESP32 is publishing data correctly; you can use MQTT clients like MQTT.fx to debug.
- Websocket connection issues: Ensure that Firewall settings allow traffic on the port used by Flask (default is 5000).
Conclusion
Congratulations! You have successfully built a Flask web dashboard for real-time visualization of MQTT data from ESP32 sensors. You can extend this project by adding more features, such as data storage or analytics. Happy coding!