# ESP32 Dashboard

## Description

ESP32 Dashboard is a project that displays useful information on a 2.9" e-paper display. It leverages an ESP32 microcontroller, MicroPython, and various APIs to provide real-time data. Key information displayed includes:

* **Clock:** Synchronized via NTP (Network Time Protocol) for accurate timekeeping.
* **Weather:** Fetches current weather conditions and forecasts using the OpenWeatherMap API.
* **Personal website view counter:** Displays statistics from personal website analytics.
* **Pi-hole statistics:** Integrates with the Pi-hole API to show ad-blocking and network statistics from Raspberry Pi or other Pi-hole instance.

This project utilizes **Python** and **MicroPython** for the ESP32, interacts with the **OpenWeatherMAP API** for weather data, and the **Pi-hole API** for network statistics.


## Blog post & visual demo

I wrote a short blog post with some photos about the making of this project - **[you can read here](https://pflaumax.dev/blog/esp32-dashboard/)**.

Here's how it looks in action:

![ESP32 Dashboard](esp32_demo.gif)


## Table of contents

1.  [Description](#description)
2.  [Blog post & visual demo](#blog-post--visual-demo)
3.  [Hardware requirements](#hardware-requirements)
4.  [Pin connections](#pin-connections)
5.  [Setup and installation](#setup-and-installation)
6.  [Files and core components](#files-and-core-components)
7.  [License](#license)

## Hardware requirements

* ESP32-WROOM development board
* 2.9" E-paper display WeActStudio (296x128, black/white)
* Micro USB cable
* Power source (USB or battery)

## Pin connections

Connect the e-paper display to the ESP32 as follows:

| E-paper pin | ESP32 pin |
|-------------|-----------|
| BUSY        | GPIO4     |
| RST         | GPIO16    |
| DC          | GPIO17    |
| CS          | GPIO5     |
| CLK/SCL     | GPIO18    |
| DIN/SDA     | GPIO23    |
| GND         | GND       |
| VCC         | 3.3V      |

## Setup and installation

This section guides through setting up the project on host computer and the ESP32.

1.  **Clone the repository:**
    First, clone the project repository to local machine.
    ```bash
    $ git clone https://github.com/pflaumax/esp32_dashboard
    $ cd esp32_dashboard
    ```

2.  **Install host computer requirements:**
    Tools needed on computer to interact with the ESP32 and manage files.
    * **`ampy`**: For transferring files to the MicroPython filesystem.
        ```bash
        $ pip install adafruit-ampy
        ```
    * **`esptool.py`** (Recommended): For flashing MicroPython firmware to the ESP32.
        ```bash
        $ pip install esptool
        ```

3.  **Install MicroPython on ESP32:**
    If ESP32 doesn't have MicroPython, or you want to use a specific version, you'll need to flash it.
    * Download the latest firmware from the [official MicroPython website for ESP32](https://micropython.org/download/ESP32_GENERIC/).
    * Follow the flashing instructions provided on the MicroPython website, typically using `esptool.py`. For example:
        ```bash
        # Erase flash (optional, but good for a clean start)
        $ esptool.py --chip esp32 --port /dev/ttyUSB0 erase_flash
        # Flash MicroPython firmware
        $ esptool.py --chip esp32 --port /dev/ttyUSB0 --baud 460800 write_flash -z 0x1000 esp32-generic-XXX.bin
        ```
        (Replace `/dev/ttyUSB0` with your ESP32's serial port and `esp32-generic-XXX.bin` with the downloaded firmware file name).

4.  **Font files:**
    Nothing to do here - the three fonts the dashboard needs are already in the `fonts/` directory and get uploaded in step 6.

    They are `freesans14.py`, `freesans17.py` and `freesans20.py`, and those exact module names are hardcoded in `main.py` (`from fonts import freesans14, freesans17, freesans20`). If you want different fonts or sizes, generate them from a TTF with [Peter Hinch's micropython-font-to-py](https://github.com/peterhinch/micropython-font-to-py) tool and update that import plus the `Writer(...)` calls in `main.py` to match - adding a differently named font file alone will fail at boot with an ImportError.

5.  **Configure `config.py`:**
    This file contains all personalized settings. Create a `config.py` file in the root of the cloned repository. Settings are grouped into classes, and the names below are the ones the code reads, so keep them exactly as written:

    ```python
    class Network_Config:
        WIFI_SSID = "your_wifi_ssid"
        WIFI_PASSWORD = "your_wifi_password"


    class Time_Config:
        # Preferred: a POSIX TZ string, which handles DST automatically.
        # Find yours in the "TZ identifier"/"POSIX TZ" column of the tz database,
        # or read it off a Linux/macOS box with: tail -1 /usr/share/zoneinfo/<Area>/<City>
        TZ = "EET-2EEST,M3.5.0/3,M10.5.0/4"  # Europe/Kyiv

        # Fallback, used when TZ is unset or unparseable. Hours, numeric;
        # fractional values work (5.5 for IST). No DST handling.
        TIMEZONE_OFFSET = 3


    class Weather_Config:
        API_KEY = "your_openweathermap_api_key"
        CITY_ID = "your_city_id"


    class Website_Config:
        API_URL = "https://your.website.com/api/stats"


    class Pihole_Config:
        PIHOLE_IP = "your_pihole_ip"
        PIHOLE_PASSWORD = "your_pihole_api_password"
        # For new version v6.x.x find password API in Pi-hole: Settings > Web interface/API > Enable expert mode in the top right corner > Enable 2FA (optional) > Configure app password (API)


    class EPD_Config:
        BUSY_PIN = 4
        RST_PIN = 16
        DC_PIN = 17
        CS_PIN = 5
    ```

    `EPD_Config` must match the wiring in [Pin connections](#pin-connections). The SPI pins (CLK 18, DIN 23, MISO 19) are fixed in `display/display.py`.

6.  **Upload files to ESP32:**
    Connect your ESP32 to your computer. Identify its serial port (e.g., `/dev/ttyUSB0` on Linux, `COM3` on Windows).
    Upload the project files with `ampy`. **The directory layout must be preserved on the device** - the code imports modules as packages (e.g. `from widgets.clock import Clock`), so uploading the files flat into the root will not work.
    * **Core project files:**
        ```bash
        $ ampy --port /dev/ttyUSB0 put main.py
        $ ampy --port /dev/ttyUSB0 put boot.py
        $ ampy --port /dev/ttyUSB0 put config.py
        ```
    * **Package directories** (`ampy put <local_dir> <remote_dir>` copies the directory recursively):
        ```bash
        $ ampy --port /dev/ttyUSB0 put driver driver
        $ ampy --port /dev/ttyUSB0 put display display
        $ ampy --port /dev/ttyUSB0 put fonts fonts
        $ ampy --port /dev/ttyUSB0 put widgets widgets
        ```
    * **Verify the upload:**
        ```bash
        $ ampy --port /dev/ttyUSB0 ls
        # Expected: /boot.py /config.py /main.py /display /driver /fonts /widgets
        ```

7.  **Run the dashboard:**
    Press the reset button on the board. `boot.py` runs automatically and starts the dashboard loop.

    To watch it run, open a serial terminal - every widget reports its state as it updates:
    ```bash
    $ pyserial-miniterm /dev/ttyUSB0 115200
    ```
    Note that `ampy run main.py` is not a useful way to test this project: the dashboard loop never exits, and `ampy run` waits for the script to finish, so the command just hangs.

## Files and core components

**This project typically consists of the following files to be uploaded to the ESP32:**

* `main.py`: The main script that initializes the display, networking, and orchestrates the fetching and displaying of data.
* `boot.py`: Runs automatically on boot. It constructs the `Dashboard` from `main.py` and starts its update loop, which never returns - so `main.py` is imported as a module rather than run as a script.
* `config.py`: Contains all user-specific configurations like WiFi, API keys, and other settings.

**E-paper driver library:**
* `epd29_ssd1680.py`: Driver library specific to the WeActStudio 2.9" e-paper display, handling low-level communication and drawing functions.

**Font files (`*.py`):** 
* Python files generated by `micropython-font-to-py`, defining pixel patterns for different characters.

**Display libraries (`display/` directory).** Two of these are vendored from the [official repository micropython-nano-gui by Peter Hinch](https://github.com/peterhinch/micropython-nano-gui):
* `writer.py`: (vendored) Renders the Python font files, handling text positioning, word wrap and tab stops. This is what the dashboard draws all its text with.
* `boolpalette.py`: (vendored) Defines the colour palette for 1-bit frame buffers, needed for correct rendering on a monochrome e-paper panel.
* `display.py`: `EPaperDisplay` - sets up SPI and the display pins, owns the frame buffer, and exposes the drawing primitives.
* `frame_buffer_wrapper.py`: A wrapper around MicroPython's `framebuf` that renders into its own buffer and copies it into the driver's buffer on `show()`.
* `nanogui.py`: (vendored) **Not used by this project and not importable as shipped** - it does `from colors import *`, and there is no `colors.py` here. It is kept only as a reference for anyone who wants to build out the nano-gui widget set (labels, meters, dials); the dashboard draws text directly with `writer.py` instead.

**Widgets and other support files:**
* `clock.py`: Implements the clock widget, managing time display synchronized via NTP and updating the dashboard in real time. 
* `ntp_client.py`: Handles communication with NTP servers to fetch accurate current time for synchronization.
* `pihole_stats.py`: Interfaces with the Pi-hole API to retrieve ad-blocking statistics and network data to be displayed on the dashboard.
* `weather.py`: Manages fetching and parsing weather data from the OpenWeatherMap API and provides current weather and forecast information for display. 
* `website_views.py`: Connects to the personal website's analytics API to retrieve and display visitor statistics.
* `network_manager.py`: Utility to manage WiFi connections, handle reconnections, and maintain network status for the ESP32.


## License

This project is licensed under the [MIT License](LICENSE).
