# epd — a library for showing web pages on an e-paper display

[![PlatformIO CI](https://github.com/chrisjtwomey/epd/actions/workflows/build.yaml/badge.svg)](https://github.com/chrisjtwomey/epd/actions/workflows/build.yaml)
[![PlatformIO registry](https://badges.registry.platformio.org/packages/chrisjtwomey/library/EpdClient.svg)](https://registry.platformio.org/libraries/chrisjtwomey/EpdClient)
[![Server coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/chrisjtwomey/3c210a371fde90aa65369080ad509e39/raw/epd-server-coverage.json)](CONTRIBUTING.md#coverage)
[![Firmware coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/chrisjtwomey/3c210a371fde90aa65369080ad509e39/raw/epd-firmware-coverage.json)](CONTRIBUTING.md#coverage)
[![PyPI](https://img.shields.io/pypi/v/epd-server)](https://pypi.org/project/epd-server/)
[![License](https://img.shields.io/github/license/chrisjtwomey/epd)](LICENSE)

<p align="center">
  <img src="docs/assets/panel-on-shelf.jpg"
       alt="A framed e-paper panel on a shelf, showing the date, a map and a five-day forecast"
       width="720">
</p>

Write a page in Python and HTML. A machine you keep on — a Raspberry Pi, a
NAS, an old laptop — renders it to an image. Your e-paper panel wakes,
fetches it, draws it, and sleeps again, for months, on one battery.

**Good for** a wall calendar · a weather board · train and bus times · a
family chore list · a photo frame · a sensor readout · anything you can
write as a web page.

The server is the brains of the pair:

- It builds the page and converts it to a PNG.
- It serves that PNG over HTTP, and tells the panel how long to sleep and
  which page to fetch next.
- It watches for new firmware releases and offers them to the panel, which
  takes one at its next wake.

epd is a library in two parts. They share one HTTP contract and version
together:

- **`server/`** — `epd_server`, a Python package. Run it on whatever machine
  you keep on.
- **`firmware/`** — `EpdClient`, a PlatformIO library for the ESP32 inside
  the panel. It knows one address and nothing else: no layout, no schedule,
  no timezone.

The panel driver is a library of its own — `firmware/boards/inkplate/` for
Inkplate panels. Any other e-paper board can bring its own: write an
[`IBoard`](docs/custom-board.md) for your hardware and everything above it
works unchanged.

## What you need

|  |  |
|---|---|
| **A panel** | An [Inkplate](https://soldered.com/categories/inkplate/): an e-paper screen with an ESP32 already on it. The driver knows the 10, 6, 6PLUS, 6FLICK, 5, 5 Gen2, 4 and 2, and the 10 and the 5 Gen2 are in daily use. Other ESP32 e-paper boards work too: see [Other hardware](docs/custom-board.md). |
| **A computer that stays on** | A Raspberry Pi, a NAS, an old laptop. It runs the server. The panel needs to reach it over your home network each time it wakes. |
| **Python 3.11+ and Chromium** | The server draws your page with a real browser, so ordinary HTML and CSS work as they do everywhere else. |
| **[PlatformIO](https://platformio.org/install)** | To put the software on the panel. |
| **A USB cable** | For the first flash only. After that the panel updates itself over WiFi. |

On battery, turn off the board's power LED with its switch, if it has one. With the LED on, an Inkplate 5 Gen2 draws about 0.8 mA asleep instead of 17 µA, and the battery lasts weeks instead of months.

Expect about 30 minutes to the first picture on the screen.

## Quickstart

You never run anything inside epd, or check it out. Both halves of your
display live in your own project, which takes epd from PyPI and the
PlatformIO registry.

```sh
mkdir -p my-display/src && cd my-display
```

Everything below happens in `my-display`.

The four files below are also in [`examples/minimal`](examples/minimal),
ready to copy.

### 1. Start a server

```sh
python3 -m venv .venv && source .venv/bin/activate
pip install "epd-server~=0.23.3"
```

Save this as `server.py`. It is a whole server: one page showing the time,
shown at 08:00 and again at 20:00.

```python
from datetime import datetime
from zoneinfo import ZoneInfo

from epd_server import DisplayServer, Page, StaticSource

CSS = """
body { margin:0; height:100vh; display:flex; flex-direction:column;
       align-items:center; justify-content:center; font-family:Helvetica, sans-serif; }
.time { font-size:180px; font-weight:700; }
.date { font-size:48px; }
"""


class ClockPage(Page):
    def template(self, **kwargs):
        now = datetime.now()
        with self.airium.html():
            with self.airium.head():
                self.airium.style(_t=CSS)
            with self.airium.body():
                self.airium.div(klass="time", _t=now.strftime("%H:%M"))
                self.airium.div(klass="date", _t=now.strftime("%A %d %B"))


DisplayServer(
    pages=[ClockPage("clock", width=825, height=1200,
                     html_dir="build", png_dir="build")],
    source=StaticSource(),
    schedule=[("08:00:00", "clock.png"), ("20:00:00", "clock.png")],
    tz=ZoneInfo("Europe/Dublin"),
).run()
```

Make sure the server can find Chromium. On Debian or a Raspberry Pi:

```sh
sudo apt install chromium chromium-driver
```

On macOS, point it at the browser you already have:

```sh
export CHROME_BIN="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
```

Then run it:

```sh
python3 server.py
```

Open <http://localhost:8080/clock.png> in a browser. That image is exactly
what the panel will show. Change the CSS, restart, and look again.

### 2. Find the server's address

The panel needs an address it can reach — not `localhost`, which means the
panel itself.

```sh
ipconfig getifaddr en0     # macOS
hostname -I                # Linux
```

Write down what it prints, for example `192.168.1.10`.

### 3. Build the panel software

Three more files, alongside the `server.py` you already have.

`platformio.ini` — which board, and which libraries:

```ini
[env:release]
; pioarduino's platform for Arduino core 3, pinned: every epd board is built
; and tested on it. PlatformIO's own espressif32 cannot build EpdBoardInkplate.
platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.312-1/platform-espressif32.zip
framework = arduino
board = esp32dev
monitor_speed = 115200
lib_deps =
	chrisjtwomey/EpdClient @ ^0.23.3
	chrisjtwomey/EpdBoardInkplate @ ^0.23.3
; The framework passes -std=gnu++2b, then -std=gnu++2a, and the last one wins.
build_unflags = -std=gnu++2a -DARDUINO_ESP32 -DARDUINO_ESP32_DEV
build_flags =
	-DHTTPCLIENT_NOSECURE          ; no HTTPS: the panel fetches over HTTP
	-DARDUINO_INKPLATE10           ; or ARDUINO_INKPLATE6, ARDUINO_INKPLATE5V2…
	-DBOARD_HAS_PSRAM
	-DCLIENT_NAME='"my-display"'   ; how this panel introduces itself
	-DCLIENT_VERSION='"v1.0.0"'
	-DLOG_LEVEL=4
```

`src/defaults.cpp` — your settings. Put your own address, network name and
password in the first block; the rest can stay as it is:

```cpp
#include "EpdClient.h"

ClientConfig builtInSettings() {
    ClientConfig cfg = {};

    cfg.serverURL = "http://YOUR_SERVER_HOST:8080/clock.png";
    cfg.wifiSSID = "XXXX";
    cfg.wifiPass = "XXXX";

    cfg.serverRetries = 3;
    cfg.defaultRefreshSeconds = 3600;
    cfg.wifiConnectTimeoutSeconds = 10;

    // Leave the broker as XXXX and this block comes from the panel's own
    // store instead, which is what an image built by CI relies on.
    cfg.mqttEnabled = false;
    cfg.mqttBroker = "XXXX";
    cfg.mqttPort = 1883;
    cfg.mqttClientID = "my-display";
    cfg.mqttPrefix = "mqtt/epd";
    cfg.mqttRetries = 3;

    return cfg;
}
```

The name is yours — epd declares no settings of its own, it just takes a
`ClientConfig`. Keep this file out of git: it holds your WiFi password.

`src/main.cpp` — one wake, from beginning to end:

```cpp
#include "EpdBoardInkplate.h"
#include "EpdClient.h"

static InkplateBoard inkplateBoard;

ClientConfig builtInSettings();     // from src/defaults.cpp

void setup() {
    epdBegin(inkplateBoard);        // the panel epd draws on
    startBoard(1);                  // 1 = portrait

    // Your settings, with the ones the panel keeps for itself resolved.
    ClientConfig cfg = loadConfig(builtInSettings());
    applySdConfig(&cfg);            // with -DUSE_SDCARD, the card's config.yaml wins

    uint32_t sleepSeconds = cfg.defaultRefreshSeconds;
    if (connectNetwork(cfg) == ESP_OK) {
        PageFetch page = {};
        page.length = epdBoard().getWidth() * epdBoard().getHeight() * 8 + 100;
        const char* errMsg = nullptr;
        if (fetchPage(cfg.serverURL, clientUserAgent(epdBoard().deviceName()),
                      cfg.serverRetries, &page, &errMsg)) {
            drawPage(page, nullptr, cfg.serverRetries, nullptr, &errMsg);
            if (page.response.nextRefreshSeconds)
                sleepSeconds = page.response.nextRefreshSeconds;   // the server decides
        }
    }
    sleepFor(sleepSeconds);
}

void loop() {}
```

Two includes is the whole library: `EpdClient.h` brings everything above,
and `EpdBoardInkplate.h` brings the panel driver.

Plug the panel in, turn its power switch on, and flash it:

```sh
pio run -t upload
pio device monitor -b 115200
```

The log shows it connect, fetch, draw, and sleep. The page appears on the
screen and stays there while the panel is asleep, because e-paper needs no
power to keep an image.

That is the whole loop. From here you change the server, not the panel.

## How it works

Each time the panel wakes it asks the server for a picture. The server
answers with the picture plus two facts: how many seconds to sleep, and
which address to ask for next time.

```
panel ──── GET /clock.png ────▶ server
      ◀─── the image, "sleep 7200s", "ask for daily.png next"
      (draws it, then sleeps)
```

A project on top of epd supplies three things:

1. **Which panel** — an Inkplate, or your own board.
2. **Which pages** — the HTML you want drawn.
3. **Which data** — where the content comes from: an API, a sensor, a file.

Everything else — waking on time, WiFi, retries when the network is
flaky, watching the battery, sleeping, showing an error on screen, updating
itself — is already written.

## Going further

| | |
|---|---|
| **[Examples](examples/)** | Three projects to copy: the quickstart above, the same panel updating itself, and a server with live data behind two pages. |
| **[Configuration](docs/configuration.md)** | Every setting, the build flags, and reading settings from an SD card instead of compiling them in. |
| **[Updates over the air](docs/ota.md)** | Publish a new version and every panel takes it at its next wake. How a bad release is caught and undone by itself. |
| **[The HTTP contract](docs/protocol.md)** | The exact requests and headers, for debugging with `curl` or writing your own client. How each board signs its posts with a key of its own. |
| **[Other hardware](docs/custom-board.md)** | Any ESP32 e-paper board, by writing one class. The Inkplate one is about 300 lines. |
| **[Testing your own project](docs/testing.md)** | Run your panel's logic on your laptop, with no board attached. |
| **[Server reference](server/README.md)** | Pages, data sources, scheduling, image quantising, the config file. |

## Built on epd

<img src="docs/assets/panel-on-wall.jpg"
     alt="A framed e-paper panel hanging on a wall beside a bookshelf"
     width="340" align="right">

[**inkplate10-weather-cal**](https://github.com/chrisjtwomey/inkplate10-weather-cal)
— a framed Inkplate 10 on a wall. Weather, forecast and calendar, on
battery, waking seven times a day.

[**canary**](https://github.com/chrisjtwomey/canary)
— a mains-powered Inkplate 5 Gen2 that shows temperature, humidity and air
quality from the sensors in its dock.

<br clear="right">

Using epd for something? Open a pull request and add it.

## License

MIT. The install page ships esptool-js (Apache-2.0), which contains pako
(MIT and Zlib); their licences are in `server/epd_server/static/install/`. The server's pages
ship the Fraunces font (SIL Open Font License), with its licence in
`server/epd_server/static/look/`.
`install-firmware.sh` downloads Espressif's esptool (GPL-2.0) when it runs;
it is not shipped.
