Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: CI

on:
push:
pull_request:

jobs:
logic-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: g++ -std=c++17 -Wall -Wextra -Imain test/test_logic.cpp -o test_logic && ./test_logic

compile:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: arduino/compile-sketches@v1
with:
# Versions match the comments at the top of main/main.ino
fqbn: esp32:esp32:esp32
platforms: |
- name: esp32:esp32
version: 3.3.2
source-url: https://espressif.github.io/arduino-esp32/package_esp32_index.json
libraries: |
- name: FastLED
version: 3.10.3
- name: ArduinoJson
version: 7.4.2
- name: StreamUtils
version: 1.9.1
sketch-paths: |
- main
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,12 @@ Control your Esp32 based LED matrix remotely. This firmware works in conjunction
Loading animations indicate different processes. If the loading animation color is...
* Green: firmware is updating
* Blue: fetching and saving new data
* Red: old files are being cleaned up
* Red: old files are being cleaned up
## Tests
The hardware-free logic lives in `main/logic.h` and can be tested on a PC without the device:

```
mkdir -p build && g++ -std=c++17 -Wall -Wextra -Imain test/test_logic.cpp -o build/test_logic && build/test_logic
```

GitHub Actions runs these tests and compiles the sketch on every push.
59 changes: 59 additions & 0 deletions main/logic.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Hardware-free logic, kept separate so it can be compiled and tested on a PC.
// Tests live in test/test_logic.cpp. Do not include Arduino headers here.
#pragma once
#include <stddef.h>

#define MIN_FRAME_DURATION_MS 16 // ~60 FPS cap

// Maps a matrix position to the pixel index in the frame buffer,
// accounting for the serpentine layout of the LED strips (odd rows run backwards).
inline int serpentineIndex(int row, int col, int length) {
return row * length + (row % 2 == 0 ? col : length - 1 - col);
}

// Number of LEDs to light for a progress bar.
inline int progressLedCount(size_t processed, size_t total, int numLeds) {
return total == 0 ? 0 : (int)(processed * numLeds / total);
}

// Playback position within the current animation.
struct Playback {
int frameIndex = 0;
int repeatCount = 0;
bool loaded = false;
unsigned long previousMillis = 0; // last time a frame was shown
};

const int STEP_WAIT = -1; // nothing to do yet
const int STEP_DONE = -2; // animation finished, move to the next one
const int STEP_INVALID = -3; // animation has no frames or no repeats, skip it

// Advances playback. Returns the index of the frame to show now, or one of the STEP_ codes.
inline int stepPlayback(Playback& p, unsigned long now, int frameCount, int repeats, int frameDuration) {
if (repeats <= 0 || frameCount <= 0) return STEP_INVALID;
if (frameDuration < MIN_FRAME_DURATION_MS) frameDuration = MIN_FRAME_DURATION_MS;

if (!p.loaded) {
p.loaded = true;
p.repeatCount = 0;
p.previousMillis = now - frameDuration; // show the first frame immediately
}

if (now - p.previousMillis < (unsigned long)frameDuration) return STEP_WAIT;

if (p.frameIndex < frameCount) {
p.previousMillis = now;
return p.frameIndex++;
}

// all frames shown and the last one has had its full duration
if (p.repeatCount < repeats - 1) {
p.repeatCount++;
p.frameIndex = 0;
p.previousMillis = now - frameDuration; // restart immediately
return STEP_WAIT;
}

p = Playback();
return STEP_DONE;
}
111 changes: 31 additions & 80 deletions main/main.ino
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <WebServer.h>
#include <DNSServer.h>
#include <Preferences.h>
#include "logic.h"

// board setup
#define DATA_PIN 13
Expand Down Expand Up @@ -75,12 +76,8 @@ const unsigned long firmwareCheckInterval = 60 * 60 * 1000;
unsigned long lastHashCheckMillis = 0;
const unsigned long hashCheckInterval = 5 * 60 * 1000; // 5 minute interval

unsigned long previousMillis = 0; // stores last time frame was updated
int currentFrameIndex = 0; // index of the current frame
int currentAnimationIndex = 0; // index of the current animation
int currentRepeatCount = 0; // Current count of how many times the animation has been repeated
bool animationLoaded = false; // flag to check if the animation details are loaded
JsonObject currentAnimation; // stores the current animation
int currentAnimationIndex = 0; // index of the current animation
Playback playback; // position within the current animation (see logic.h)

// used to track the progress of different processes in order to display loading animations
size_t progressStepsCompleted = 0;
Expand Down Expand Up @@ -443,7 +440,7 @@ void updateAndDisplayProgress(size_t processed, size_t total, CRGB color) {

// Calculate progress as a percentage and number of LEDs to light
uint8_t progressPercent = (processed * 100) / total;
uint16_t numLedsToLight = (processed * NUM_LEDS) / total;
uint16_t numLedsToLight = progressLedCount(processed, total, NUM_LEDS);

Serial.printf("%u%% ", progressPercent);

Expand Down Expand Up @@ -563,17 +560,7 @@ void parseAndDisplayFrame() {
for (int row = 0; row < LENGTH; ++row) {
for (int col = 0; col < LENGTH; ++col) {
int ledIndex = row * LENGTH + col;
int bufferIndex;

// account for serpentine layout of led strips
if (row % 2 == 0) {
// Even rows: direct mapping
bufferIndex = ledIndex * BYTES_PER_PIXEL;
} else {
// Odd rows: reverse order
int reverseCol = LENGTH - 1 - col;
bufferIndex = (row * LENGTH + reverseCol) * BYTES_PER_PIXEL;
}
int bufferIndex = serpentineIndex(row, col, LENGTH) * BYTES_PER_PIXEL;

// Bounds checking to prevent memory corruption
if (bufferIndex >= 0 && bufferIndex + 2 < SIZE) {
Expand Down Expand Up @@ -1030,75 +1017,40 @@ void setup() {
}

void loop() {
if (currentAnimationIndex < jsonMetadata["metadata"].as<JsonArray>().size()) {
if (!animationLoaded) { // If this is the first frame of the animation, load the animation
currentAnimation = jsonMetadata["metadata"].as<JsonArray>()[currentAnimationIndex];
const char* animationID = currentAnimation["animationID"];

// Skip animations with invalid parameters
int repeatCount = currentAnimation["repeatCount"].as<int>();
JsonArray frameOrder = currentAnimation["frameOrder"].as<JsonArray>();

if (repeatCount <= 0 || frameOrder.size() == 0) {
Serial.print(F("Skipping invalid animation: "));
Serial.println(animationID);
currentAnimationIndex++;
return; // Skip this loop iteration
}
JsonArray animations = jsonMetadata["metadata"].as<JsonArray>();
if (currentAnimationIndex < animations.size()) {
JsonObject animation = animations[currentAnimationIndex];
JsonArray frameOrder = animation["frameOrder"].as<JsonArray>();
const char* animationID = animation["animationID"];

bool starting = !playback.loaded;
int step = stepPlayback(playback, millis(), frameOrder.size(),
animation["repeatCount"].as<int>(), animation["frameDuration"].as<int>());

if (step == STEP_INVALID) {
Serial.print(F("Skipping invalid animation: "));
Serial.println(animationID);
currentAnimationIndex++;
return; // Skip this loop iteration
}

if (starting) {
Serial.print(F("Displaying Animation: "));
Serial.println(animationID);

animationLoaded = true;
currentRepeatCount = 0;

// Enforce minimum frame duration to prevent CPU overload
int frameDuration = currentAnimation["frameDuration"].as<int>();
if (frameDuration < 16) frameDuration = 16; // Minimum 16ms (~60 FPS)

previousMillis = millis() - frameDuration; // Reset timing for immediate first frame
}

// Enforce minimum frame duration in timing check too
int frameDuration = currentAnimation["frameDuration"].as<int>();
if (frameDuration < 16) frameDuration = 16;

if (millis() - previousMillis >= frameDuration) {
// Time to show the next frame
JsonArray frameOrder = currentAnimation["frameOrder"].as<JsonArray>();
if (currentFrameIndex < frameOrder.size()) {
// If there are more frames to display
const char* currentFrameID = frameOrder[currentFrameIndex];

readFrameFromSPIFFS(currentFrameID);
parseAndDisplayFrame();

previousMillis = millis(); // save the last time a frame was displayed
currentFrameIndex++;
} else {
// All frames displayed, but need to wait for frame duration before transitioning
// Check if enough time has passed since the last frame was displayed
if (millis() - previousMillis >= frameDuration) {
// Check if the animation needs to be repeated
if (currentRepeatCount < currentAnimation["repeatCount"].as<int>() - 1) {
// Repeat the animation again
currentRepeatCount++;
currentFrameIndex = 0; // Reset frame index to restart the animation
previousMillis = millis() - frameDuration; // Reset timing for immediate repeat
} else {
// No more repeats, move to the next animation
currentFrameIndex = 0;
currentAnimationIndex++;
animationLoaded = false;
currentRepeatCount = 0; // Reset repeat count for the next animation
}
}
}
if (step >= 0) {
const char* currentFrameID = frameOrder[step];
readFrameFromSPIFFS(currentFrameID);
parseAndDisplayFrame();
playback.previousMillis = millis(); // time the frame from when it was actually displayed
} else if (step == STEP_DONE) {
currentAnimationIndex++;
}
} else {
// All animations done, reset for the next loop
currentAnimationIndex = 0;
animationLoaded = false;
playback = Playback();
}

if (millis() - lastFirmwareCheckMillis >= firmwareCheckInterval) {
Expand Down Expand Up @@ -1128,8 +1080,7 @@ void loop() {

// Reset animation parameters if new metadata is fetched
currentAnimationIndex = 0;
currentFrameIndex = 0;
animationLoaded = false;
playback = Playback();
} else {
Serial.println(F("Local metadata is up to date."));
}
Expand Down
87 changes: 87 additions & 0 deletions test/test_logic.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Host tests for main/logic.h. Run from the repo root:
// g++ -std=c++17 -Wall -Wextra -Imain test/test_logic.cpp -o build/test_logic && build/test_logic
#undef NDEBUG
#include <cassert>
#include <cstdio>
#include "logic.h"

static void testSerpentine() {
assert(serpentineIndex(0, 0, 16) == 0);
assert(serpentineIndex(0, 15, 16) == 15);
assert(serpentineIndex(1, 0, 16) == 31); // odd rows are reversed
assert(serpentineIndex(1, 15, 16) == 16);
assert(serpentineIndex(2, 3, 16) == 35);
assert(serpentineIndex(15, 0, 16) == 255);

// every pixel is used exactly once
bool seen[256] = {};
for (int r = 0; r < 16; r++)
for (int c = 0; c < 16; c++) {
int i = serpentineIndex(r, c, 16);
assert(i >= 0 && i < 256 && !seen[i]);
seen[i] = true;
}
}

static void testProgress() {
assert(progressLedCount(0, 10, 256) == 0);
assert(progressLedCount(5, 10, 256) == 128);
assert(progressLedCount(10, 10, 256) == 256);
assert(progressLedCount(3, 0, 256) == 0); // no division by zero
}

static void testPlaybackRepeats() {
Playback p;
// 2 frames, 2 repeats, 100ms per frame
assert(stepPlayback(p, 0, 2, 2, 100) == 0); // first frame is immediate
assert(stepPlayback(p, 50, 2, 2, 100) == STEP_WAIT);
assert(stepPlayback(p, 100, 2, 2, 100) == 1);
assert(stepPlayback(p, 150, 2, 2, 100) == STEP_WAIT);
assert(stepPlayback(p, 200, 2, 2, 100) == STEP_WAIT); // rewinds for the second pass
assert(stepPlayback(p, 200, 2, 2, 100) == 0); // and restarts without delay
assert(stepPlayback(p, 300, 2, 2, 100) == 1);
assert(stepPlayback(p, 399, 2, 2, 100) == STEP_WAIT); // last frame gets its full duration
assert(stepPlayback(p, 400, 2, 2, 100) == STEP_DONE);
assert(!p.loaded && p.frameIndex == 0 && p.repeatCount == 0);
}

static void testSingleFrameHoldsForDuration() {
Playback p;
assert(stepPlayback(p, 1000, 1, 1, 500) == 0);
assert(stepPlayback(p, 1499, 1, 1, 500) == STEP_WAIT);
assert(stepPlayback(p, 1500, 1, 1, 500) == STEP_DONE);
}

static void testMinimumFrameDuration() {
Playback p;
assert(stepPlayback(p, 0, 2, 1, 0) == 0);
assert(stepPlayback(p, 15, 2, 1, 0) == STEP_WAIT);
assert(stepPlayback(p, 16, 2, 1, 0) == 1);
}

static void testInvalidAnimations() {
Playback p;
assert(stepPlayback(p, 0, 0, 1, 100) == STEP_INVALID);
assert(stepPlayback(p, 0, 3, 0, 100) == STEP_INVALID);
assert(stepPlayback(p, 0, 3, -1, 100) == STEP_INVALID);
assert(!p.loaded);
}

static void testMillisRollover() {
Playback p;
unsigned long nearMax = (unsigned long)-1 - 10;
assert(stepPlayback(p, nearMax, 2, 1, 100) == 0);
assert(stepPlayback(p, nearMax + 50, 2, 1, 100) == STEP_WAIT); // wrapped past zero
assert(stepPlayback(p, nearMax + 100, 2, 1, 100) == 1);
}

int main() {
testSerpentine();
testProgress();
testPlaybackRepeats();
testSingleFrameHoldsForDuration();
testMinimumFrameDuration();
testInvalidAnimations();
testMillisRollover();
puts("all logic tests passed");
}
Loading