# LED Cube

[![build-release](https://github.com/elliotmatson/LED_Cube/actions/workflows/build-release.yml/badge.svg)](https://github.com/elliotmatson/LED_Cube/actions/workflows/build-release.yml)

![cube](docs/cube.jpeg)

An ESP32 based LED cube, inspired by [this project](https://github.com/Staacks/there.oughta.be/tree/master/led-cube).

## Patterns

Recorded from a running cube with `scripts/capture_patterns.py` and drawn as the cube looks from its corner.

<table>
<tr><td align="center" width="33%"><img src="docs/patterns/snake.webp" alt="Snake" width="220"><br><b>Snake</b><br><sub>Snakes of many kinds roam all three faces, crossing the seams, eating and growing.</sub></td><td align="center" width="33%"><img src="docs/patterns/plasma.webp" alt="Plasma" width="220"><br><b>Plasma</b><br><sub>A plasma glowing from the corner and fading out at the outer edges, flowing continuously across the seams.</sub></td><td align="center" width="33%"><img src="docs/patterns/spotify.webp" alt="Spotify" width="220"><br><b>Spotify</b><br><sub>Album art, scrolling track details and playback state, with the album's colours on top. See <a href="#spotify">Spotify</a>.</sub></td></tr>
<tr><td align="center" width="33%"><img src="docs/patterns/clock.webp" alt="Clock" width="220"><br><b>Clock</b><br><sub>An analog dial on top, the time on the right, the date on the left.</sub></td><td align="center" width="33%"><img src="docs/patterns/game_of_life.webp" alt="Game of Life" width="220"><br><b>Game of Life</b><br><sub>Conway's Life on all three faces as one surface; gliders cross the seams.</sub></td><td align="center" width="33%"><img src="docs/patterns/ripples.webp" alt="Ripples" width="220"><br><b>Ripples</b><br><sub>Rings spreading from the corner, plus raindrops.</sub></td></tr>
<tr><td align="center" width="33%"><img src="docs/patterns/matrix_rain.webp" alt="Matrix Rain" width="220"><br><b>Matrix Rain</b><br><sub>Rain across the top, over the edges and down the sides.</sub></td><td align="center" width="33%"><img src="docs/patterns/nebula.webp" alt="Nebula" width="220"><br><b>Nebula</b><br><sub>A drifting 3D noise cloud the cube is cut out of.</sub></td><td align="center" width="33%"><img src="docs/patterns/wireframes.webp" alt="Wireframes" width="220"><br><b>Wireframes</b><br><sub>Rotating solids floating inside the cube.</sub></td></tr>
<tr><td align="center" width="33%"><img src="docs/patterns/rubiks_cube.webp" alt="Rubik's Cube" width="220"><br><b>Rubik's Cube</b><br><sub>Scrambles, then solves itself.</sub></td><td align="center" width="33%"><img src="docs/patterns/falling_sand.webp" alt="Falling Sand" width="220"><br><b>Falling Sand</b><br><sub>Sand poured from the top piles up down the sides.</sub></td><td align="center" width="33%"><img src="docs/patterns/plane_sweep.webp" alt="Plane Sweep" width="220"><br><b>Plane Sweep</b><br><sub>Coloured planes sweeping through the cube's volume.</sub></td></tr>
<tr><td align="center" width="33%"><img src="docs/patterns/ticker.webp" alt="Ticker" width="220"><br><b>Ticker</b><br><sub>Your message, the time and the date scrolling around the sides.</sub></td><td align="center" width="33%"><img src="docs/patterns/dvd.webp" alt="DVD" width="220"><br><b>DVD</b><br><sub>The screensaver logo, cut out of a coloured block, gliding around the sides; the top counts perfect corner hits.</sub></td><td align="center" width="33%"><img src="docs/patterns/hyperspace.webp" alt="Hyperspace" width="220"><br><b>Hyperspace</b><br><sub>Stars streaming out of the corner, with a jump to light speed every so often.</sub></td></tr>
<tr><td align="center" width="33%"><img src="docs/patterns/aurora.webp" alt="Aurora" width="220"><br><b>Aurora</b><br><sub>Green curtains with violet tops rippling round the sides, ribbons and stars overhead.</sub></td><td align="center" width="33%"><img src="docs/patterns/lava_lamp.webp" alt="Lava Lamp" width="220"><br><b>Lava Lamp</b><br><sub>Blobs of wax rising and sinking through the cube, glowing where they meet the faces.</sub></td><td align="center" width="33%"><img src="docs/patterns/fire.webp" alt="Fire" width="220"><br><b>Fire</b><br><sub>Flames licking up the sides, embers drifting over the edge onto the top.</sub></td></tr>
<tr><td align="center" width="33%"><img src="docs/patterns/fireworks.webp" alt="Fireworks" width="220"><br><b>Fireworks</b><br><sub>Rockets climbing the sides and bursting, sparks spilling over the edges.</sub></td><td align="center" width="33%"><img src="docs/patterns/aquarium.webp" alt="Aquarium" width="220"><br><b>Aquarium</b><br><sub>Fish, seaweed and bubbles in the tank; caustics and ripples on the surface above.</sub></td><td align="center" width="33%"><img src="docs/patterns/maze.webp" alt="Maze" width="220"><br><b>Maze</b><br><sub>A maze grown across all three faces and over the seams, then solved.</sub></td></tr>
<tr><td align="center" width="33%"><img src="docs/patterns/langtons_ant.webp" alt="Langton's Ant" width="220"><br><b>Langton's Ant</b><br><sub>Ants and their multi-colour cousins building highways and blooms across the seams.</sub></td><td align="center" width="33%"><img src="docs/patterns/pong.webp" alt="Pong" width="220"><br><b>Pong</b><br><sub>The cube playing itself at Pong round the sides, the net down the corner, the score on top.</sub></td><td align="center" width="33%"><img src="docs/patterns/breakout.webp" alt="Breakout" width="220"><br><b>Breakout</b><br><sub>The cube playing Breakout round the sides; score, lives and level on top.</sub></td></tr>
<tr><td align="center" width="33%"><img src="docs/patterns/word_clock.webp" alt="Word Clock" width="220"><br><b>Word Clock</b><br><sub>The time in words, lit in a grid of letters round the sides, with a seconds ring on top.</sub></td><td align="center" width="33%"><img src="docs/patterns/weather.webp" alt="Weather" width="220"><br><b>Weather</b><br><sub>The sky outside round the sides -- sun, moon, clouds, rain, snow or storm -- and the forecast on top.</sub></td></tr>
</table>

## Table of Contents
- [LED Cube](#led-cube)
  - [Patterns](#patterns)
  - [Table of Contents](#table-of-contents)
  - [Development](#development)
    - [Setting up Dev Environment](#setting-up-dev-environment)
    - [Building](#building)
    - [Uploading](#uploading)
  - [Spotify](#spotify)
  - [Weather](#weather)
  - [Telemetry](#telemetry)

## Development

### Setting up Dev Environment
To build firmware for this cube, all you need is an IDE and PlatformIO. I use VSCode, but you can use whatever you want. See [here](https://docs.platformio.org/en/latest/integration/ide/vscode.html#quick-start) for more details on setting up PlatformIO in VSCode.

Clone this repo, and open it in your IDE. You should be able to move on to building.

### Building
This project uses ESPIDF with Arduino as a component, and PlatformIO to build and upload firmware. To build, just click the build button in your IDE. To upload, click the upload button. You can also use the PlatformIO CLI to build and upload. See [here](https://docs.platformio.org/en/latest/core/userguide/cmd_build.html) for more details.

### Uploading
Currently, the cubes support 4 different methods of getting new firmware. The first one, used exclusively in production, is downloading straight from Github releases. These builds are created with Github Actions and are not used for development; a cube running a local `DEV` build never replaces itself this way. The second is the **Update Firmware** card on the dashboard's System tab: upload `esp32-s3-devkitc-1-<version>.bin` from a release, or `.pio/build/esp32-s3-devkitc-1/firmware.bin` from a local build. The cube checks the image before writing it. The third method is using OTA updates (switch on "OTA Update Enabled" on the dashboard first). This is the easiest method of uploading new firmware during development. To upload using OTA, you need to have the cube connected to your network. Ensure that these two lines are uncommented in platformio.ini, and that the cube is on the same network as your computer:

```ini
upload_protocol = espota
upload_port = cube.local
```

Then, click the upload button in your IDE. This will upload the firmware to the cube over the network. The cube will then reboot and start running the new firmware. 

The fourth method is using a USB to serial adapter. This is mostly only useful if you have uploaded firmware that breaks OTA, bur can also be used for debugging. To upload using serial, you need to have the cube connected to your computer via USB. 


Connect the Cube GND to the adaptor GND, the Cube TX to the adaptor RX, and the Cube RX to the adaptor TX, then comment out these two lines in platformio.ini:

```ini
;upload_protocol = espota
;upload_port = cube.local
```
    
Then, click the upload button in your IDE. This will upload the firmware to the cube over serial. The cube will then reboot and start running the new firmware.

## Spotify

The Spotify pattern shows what is playing on your account: album art on one side face, the track, artist, a progress bar and playback state on the other. Each cube uses your own Spotify app, because Spotify's developer mode limits an app to its owner and a few allowlisted users.

1. Sign in at [developer.spotify.com/dashboard](https://developer.spotify.com/dashboard) and create an app (any name). Development mode needs the app owner to have Spotify Premium.
2. Under **Redirect URIs**, add exactly:
   `https://elliotmatson.github.io/LED_Cube/spotify/callback.html`
   (Spotify only accepts HTTPS redirects, which the cube cannot serve itself; this page just forwards the login back to your cube on your network.)
3. Select **Web API**, save, then copy the app's **Client ID** and **Client Secret**.
4. On the cube's dashboard, open the **Spotify** tab and paste them into **Spotify Client ID** and **Spotify Client Secret**.
5. Use **Log in to Spotify** on that tab (or open `http://cube.local/spotify`), and approve the app. The browser comes back to the cube, which finishes the login and switches to the Spotify pattern.

If something goes wrong, the Spotify card on that tab says what (also at `/api/v1/spotify`). **Log out of Spotify** forgets the linked account. To use another account in development mode, add its email under the app's **User Management** first.

For local builds you can instead put `SPOTIFY_CLIENT_ID` and `SPOTIFY_CLIENT_SECRET` in `lib/cube/secrets.h` (gitignored); they are used only when the dashboard fields are empty. Never put the secret in a build you publish.

## Weather

The Weather pattern shows the conditions outside on the side faces (sun or moon, clouds, fog, rain, snow or a storm, by day or night) and the temperature, conditions and today's high and low on top. Forecasts come from [Open-Meteo](https://open-meteo.com), which needs no account or key, every 15 minutes while the pattern runs.

By default the cube works out where it is from its IP address, which can be off by a town or two. To set it, open the dashboard's **Weather** tab and type a city or postcode into **Weather Location**; the status card shows the place it found. Clear the box to go back to the IP address. **Weather in °C and km/h** switches units.

The same settings are at `/api/v1/weather`: GET for what the pattern knows, POST `location=` and/or `metric=true|false`. POST `preview=<WMO code>` (and `day=false` for night) shows a kind of weather for two minutes, to try the animations: 0 clear, 2 partly cloudy, 3 overcast, 45 fog, 53 drizzle, 63 rain, 73 snow, 95 thunderstorm.

## Telemetry

Release builds report to an MQTT broker, and take settings from it, so cubes in the field can be followed and managed. **While the project is in testing this is always on, with no opt-out.** A build reports only if it was given a broker (`MQTT_URL`, `MQTT_USER`, `MQTT_PASSWORD` in `lib/cube/secrets.h`, written by CI from repository secrets); other builds never connect.

Each cube picks a random ID once and publishes under `cube/<id>/`, as JSON:

| Topic | When | Contents |
|---|---|---|
| `status` | retained | `online`, or `offline` (the broker publishes that if the cube drops) |
| `boot` | each boot (retained) | firmware version and build, chip, MAC address, WiFi network (SSID, BSSID, signal, channel), local and **public IP**, the boot log (reset reasons, rollbacks, how far startup got) |
| `network` | each (re)connection (retained) | SSID, BSSID, signal, local and public IP, and whether it is on its own network or an open one |
| `health` | every interval | uptime, memory and its low-water marks, signal, current network (SSID, BSSID), pattern |
| `usage` | every interval | seconds per pattern, brightness, whether Spotify, a weather location and a ticker message are set |
| `perf` | every interval | the renderer's frame rate and tick/push times |
| `wifi` | boot, then hourly (retained) | a scan of the networks in range: SSID, BSSID, signal, channel, security |
| `location` | while lost: every 2 minutes (retained) | a fresh public IP, its network and access point, and a scan of what is in range |
| `lost` | when lost mode changes (retained) | whether it is on, silent, its message, whether a PIN is set |
| `crash` | once per crash | a summary (task, PC, cause, backtrace), then the core dump in base64 parts on `crash/<n>` |
| `settings` | retained | current settings |
| `ack` | per command | whether a command was applied, and why not |

The interval defaults to 5 minutes. No Spotify or WiFi credentials are ever sent.

Commands are messages to `cube/<id>/set/<name>`:

| Name | Value |
|---|---|
| `pattern` | a pattern id (see `/api/v1/patterns`) |
| `brightness` | 0-255 |
| `ticker`, `timezone`, `weather_location` | text |
| `weather_metric`, `github_updates`, `development`, `ota` | `true` / `false` |
| `telemetry_interval` | seconds, 60-86400 |
| `report_health`, `report_usage`, `report_perf` | `true` / `false` |
| `lost_message` | text shown in lost mode (up to 120 characters) |
| `lost_pin` | 4-12 digits that unlock it on its dashboard; empty removes it |
| `lost_silent` | `true`: in lost mode, keep looking normal |
| `lost_mode` | `true` / `false` |
| `restart`, `check_updates`, `resend_crash` | anything (actions) |

### Lost mode

If a cube goes missing, set `lost_message` (and `lost_pin`, if whoever finds it should be able to unlock it), then `lost_mode` `true`:

- It shows the message, scrolling round the sides, with LOST and its ID on top -- unless `lost_silent` is set, when it keeps showing patterns as usual.
- Its dashboard and API refuse changes (status still reads), and the upload card and ArduinoOTA refuse firmware. GitHub updates still install.
- It reports a `location` every two minutes, and `network` whenever it comes online anywhere.
- WiFi setup stays open on purpose: someone setting it up on their own network is its likeliest way back online. If it is offline for a few minutes, it also tries nearby open networks, keeping one only if the broker can be reached through it; its saved network is never overwritten.
- It persists through restarts, power loss and WiFi resets. `lost_mode` `false`, or the PIN on the dashboard's System tab, turns it off. PIN guesses are limited: after five wrong ones, one every 15 minutes.

### Broker setup

The firmware connects with `wss://` (MQTT over WebSockets, TLS on a standard HTTPS port), checking the certificate against ESP-IDF's bundle, so the broker needs a publicly trusted certificate. Every cube shares one login, which is readable from any published image, so the broker must confine it. With EMQX:

```
{allow, {username, "admin"}, all, ["#"]}.
{deny,  {username, "cube"}, publish, ["cube/${clientid}/set/#"]}.
{allow, {username, "cube"}, publish, ["cube/${clientid}/#"]}.
{allow, {username, "cube"}, subscribe, ["cube/${clientid}/set/#"]}.
{deny, all}.
```

A cube can then only publish its own reports and read its own commands; commands come from a separate admin login that never goes in firmware.

## Recording the pattern animations

The animations above come from the cube itself: `GET /api/v1/frame` returns the frame it is showing, and the script switches through every pattern and records each one.

```bash
uv run --with pillow scripts/capture_patterns.py --host cube.local
```

Pass pattern ids to record only some of them, e.g. `... --host cube.local clock nebula`.
