DEV Community

Cover image for Sensors Dashboard (MQTT Raspberry PI+ESP32+FastHTML)
Alan
Alan

Posted on

Sensors Dashboard (MQTT Raspberry PI+ESP32+FastHTML)

This guide explains how to set up an ESP32 microcontroller with an LM35 temperature sensor to send real-time data via MQTT to a Raspberry Pi running a Mosquitto broker. The data is then visualized using a sensor dashboard with an interactive UI.

We'll walk through:

  • Setting up Mosquitto on a Raspberry Pi
  • Configuring the ESP32 to send sensor data via MQTT
  • Deploying a real-time web-based dashboard for visualization

1️⃣ Install Mosquitto on Raspberry Pi (Raspbian)

Run the following commands to install Mosquitto:

sudo apt update -y
sudo apt install mosquitto
Enter fullscreen mode Exit fullscreen mode

2️⃣ Configure Mosquitto Broker

Edit the Mosquitto configuration file:

sudo vi /etc/mosquitto/mosquitto.conf
Enter fullscreen mode Exit fullscreen mode

Copy and paste the following configuration:

pid_file /run/mosquitto/mosquitto.pid

persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log

include_dir /etc/mosquitto/conf.d

allow_anonymous false  # Change to 'true' for public connections
password_file /etc/mosquitto/passwd

listener 1883 0.0.0.0  # Allow binding to the network
Enter fullscreen mode Exit fullscreen mode

Save and exit, then restart Mosquitto:

sudo systemctl restart mosquitto
Enter fullscreen mode Exit fullscreen mode

3️⃣ Enable and Start Mosquitto

sudo systemctl enable mosquitto
sudo systemctl start mosquitto
Enter fullscreen mode Exit fullscreen mode

4️⃣ (Optional) Set a Username and Password

If allow_anonymous false is set, create a username and password:

sudo mosquitto_passwd -c /etc/mosquitto/passwd myUsername
Enter fullscreen mode Exit fullscreen mode

Restart Mosquitto:

sudo systemctl restart mosquitto
Enter fullscreen mode Exit fullscreen mode

5️⃣ Test the MQTT Server

Install Mosquitto Clients

sudo apt install mosquitto-clients
Enter fullscreen mode Exit fullscreen mode

Publish a Message

Without authentication:

mosquitto_pub -h localhost -t "test/topic" -m "Hello, Raspberry Pi!"
Enter fullscreen mode Exit fullscreen mode

With authentication:

mosquitto_pub -h localhost -u "myUser" -P "myPassword" -t "test/topic" -m "Hello, Raspberry Pi!"
Enter fullscreen mode Exit fullscreen mode

Subscribe to a Topic

Without authentication:

mosquitto_sub -h localhost -t "test/topic"
Enter fullscreen mode Exit fullscreen mode

With authentication:

mosquitto_sub -h localhost -u "myUser" -P "myPassword" -t "test/topic"
Enter fullscreen mode Exit fullscreen mode

Tip: For better performance, set a static IP on your Raspberry Pi:

🔗 Guide: Set a Static IP on Raspberry Pi


6️⃣ ESP32 Circuit Setup

We'll use an ESP32 with an LM35 temperature sensor.

🔗 Code Repository: ESP32 MQTT Code

Set WiFi Credentials

Modify boot.py:

SSID = "Your_SSID"  # WiFi network name
PASSWORD = "Your_PASSWORD"  # WiFi password
Enter fullscreen mode Exit fullscreen mode

Set MQTT Credentials

Modify main.py:

mqtt_server = "YOUR_RASPBERRY_IP"
mqtt_user = "myUser"  # Optional
mqtt_pass = "myPassword"  # Optional
Enter fullscreen mode Exit fullscreen mode

Upload the Code to ESP32

ampy --port /dev/ttyUSB0 put boot.py
ampy --port /dev/ttyUSB0 put main.py
ampy --port /dev/ttyUSB0 put mqtt.py
Enter fullscreen mode Exit fullscreen mode

Note: ttyUSB0 is the ESP32's serial port.


Circuit Diagram

Build the circuit as shown in the image:

circuit

D34 is used as the analog-to-digital converter (ADC).


7️⃣ Receiving Data from ESP32

Once everything is set up, the ESP32 will send data to the MQTT topic sensors in this format:

[{"name": "temperature", "value": 29.9}]
Enter fullscreen mode Exit fullscreen mode

This happens inside main.py:

while True:
    try:
        client.check_msg()
        if (time.time() - last_message) > message_interval:
            sensors = [{"name": "temperature", "value": read_temp()}]  # Sensor data sent to MQTT
            client.publish(topic_pub, json.dumps(sensors))
            last_message = time.time()
        time.sleep(1)
    except OSError as e:
        print("Failed to connect to MQTT broker. Restarting...", e)
        restart_and_reconnect()
Enter fullscreen mode Exit fullscreen mode

8️⃣ Sensor Dashboard Integration

Once the ESP32 sends data via MQTT, you can visualize it in real time using a web-based sensor dashboard with FastHTML

🔗 Dashboard Code Repository: Sensor Dashboard

Run the Sensor Dashboard

Clone the repository and install dependencies:

git clone https://github.com/BloodBoy21/sensorsDashboard.git
cd sensorsDashboard
pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

Set MQTT Credentials in .env

MQTT_BROKER="MY_RASPBERRY_IP"
MQTT_USER=""
MQTT_PASSWORD=""
Enter fullscreen mode Exit fullscreen mode

Run the Dashboard

python main.py
Enter fullscreen mode Exit fullscreen mode

Access it in your browser:

http://localhost:5001
Enter fullscreen mode Exit fullscreen mode

Alternatively, run using Docker:

docker compose up
Enter fullscreen mode Exit fullscreen mode

9️⃣ Adding More Sensors

Modify main.py to add new sensors:

list_of_sensors = [
    Sensor(
        "temperature",  # Name from MQTT payload
        "Living Room",
        layout=Layout(
            title="Temperature Sensor",
            width=400,
            height=400,
        ),
        view_data=[
            View(
                title="Temperature",
                type="indicator",
                mode="number+gauge", # Type of chart
                domain={"x": [0, 1], "y": [0, 1]},
            )
        ],
    ),
    Sensor(
        "humidity",
        "Living Room",
        layout=Layout(
            title="Humidity Sensor",
            width=400,
            height=400,
        ),
        view_data=[
            View(
                title="Humidity",
                type="indicator",
                mode="number+gauge",
                domain={"x": [0, 1], "y": [0, 1]},
            )
        ],
    ),
    # Add more sensors here
]

my_dashboard.add_sensors(list_of_sensors)
Enter fullscreen mode Exit fullscreen mode

🎉 Final Result: Live Sensor Dashboard!

Now, you can visualize real-time sensor data with interactive charts.

dashboard


🔗 References

🚀 Now you have a complete IoT system with ESP32, MQTT, and a live sensor dashboard! 🚀

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs