Create a Flask Dashboard for Real-Time MQTT Data from ESP32 Sensors

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

  1. Install Mosquitto on your computer:
  2. sudo apt-get install mosquitto
  3. Start the Mosquitto service:
  4. sudo systemctl start mosquitto
  5. Ensure Mosquitto is running:
  6. sudo systemctl status mosquitto

2. Configure Your ESP32

  1. Connect your ESP32 to your computer and open the IDE (Arduino or MicroPython).
  2. Install the necessary libraries for MQTT.
  3. Use the following sample code to publish sensor data:
  4. 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

  1. Create a new directory for your project:
  2. mkdir flask_dashboard && cd flask_dashboard
  3. Create a virtual environment and activate it:
  4. python3 -m venv venv
    source venv/bin/activate
  5. Install Flask and other required packages:
  6. pip install Flask paho-mqtt Flask-SocketIO
  7. Create a new file named app.py and add the following code:
  8. 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

  1. Create a new directory named templates and a file named index.html inside it.
  2. Add the following HTML code to index.html:
  3. <!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

  1. Run the Flask application:
  2. python app.py
  3. Open your web browser and navigate to http://127.0.0.1:5000 to view the dashboard.

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!

Leave a Comment

Your email address will not be published. Required fields are marked *