Compare commits

...
4 Commits
Author SHA1 Message Date
mangavalkandClaude Opus 5.5 ad9fd062a8 Stop reading the old settings format
The display has stored its settings as version 8 since 2.22.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 02:45:24 +01:00
mangavalkandClaude Opus 5.5 48e29096c0 Random refresh effect: choose which effects it picks from
The list is a new setting (hardware settings, also used by pages set to
Random); an empty list is refused. The ESP32 picks an effect per frame and
sends that, so the Nano needs no change. The power-on time after a frame now
follows the slowest effect on the list.

The settings record goes to version 8. Version 7 is a prefix of it, so it is
still read, and becomes version 8 with the next save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 02:41:41 +01:00
mangavalkandClaude Opus 5.5 8fcb17c395 Matrix refresh effect, and Random really picks from all effects
Yellow streaks fall down the columns that changed, at random moments, and
leave the new image behind them. The start ticks come from a hash, so the
only new RAM is one bit per column. Only a dot's final flip gets all pulses.

Random took micros() % 8, but micros() only gives multiples of 4 on the
Nano, so it could only pick sparkle or diagonal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 02:28:34 +01:00
mangavalkandClaude Opus 5.5 35e678d78d Rules can have a second condition, and contains / does not contain
A paused printer that is only soaking no longer brings the printer page to the
front: print state = paused and display message does not contain soaking.

The schedule format changes (version 6), so the stored schedule has to be saved
again after flashing. Pins espressif32@6.10.0: the unpinned platform now resolves
to Arduino core 3, which the firmware doesn't build on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 22:43:17 +01:00
26 changed files with 623 additions and 68 deletions

No files matched your search

+4 -1
View File
@@ -160,6 +160,9 @@ See README.md for the overview.
`web/web_ui.cpp` is the JSON API (endpoints listed in `web_ui.h`), `web/web_page.h` the
single HTML/JS page (raw string literal in PROGMEM). Keep image work in the browser; the
ESP32 only handles 418-character hex bitmaps (`logic/bitmap_format.h`, MSB = left dot).
- The Random effect's list (`Settings::random_effects`) is only known to the ESP32:
`FlipdotFrames::_useEffect()` picks an effect per frame and sends that, so the Nano doesn't
run its own `EFFECT_RANDOM` (which picks from all effects).
- Settings: `logic/settings.h` struct with defaults = original behaviour, stored as an NVS
blob with a version (`system/settings_store.cpp`). When the struct changes, bump
`VERSION` there (old records then fall back to defaults). Only the current version is
@@ -218,7 +221,7 @@ See README.md for the overview.
page (the HA "Mode" dropdown). Schedule and rules are stored in NVS
(`system/schedule_store.cpp`, bump `VERSION` when `PageSchedule` changes). Pages used by
the schedule or rules can't be deleted.
- The ESP32 flash slot is about 90% full (web page and fonts are in flash). Check the size
- The ESP32 flash slot is about 95% full (web page and fonts are in flash). Check the size
after adding features; the web page could be served gzipped if it gets tight.
- Fonts use the "FDF1" format of `logic/font.h`; the web page writes the same format.
`logic/builtin_fonts.cpp` is generated: change `tools/make_builtin_fonts.py` and rerun it.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 177 KiB

After

Width:  |  Height:  |  Size: 156 KiB

+6 -2
View File
@@ -64,7 +64,9 @@ to 6 pages or bitmaps that rotate (each for its own time, 5 s to 1 hour), switch
the refresh effect or instantly.
Rules bring a page to the front from a Home Assistant state (an entity or attribute, `=`,
`is not`, `above`, `below`): they show it while the state is true, add it to the rotation
`is not`, `above`, `below`, `contains`, `does not contain`), optionally with a second
condition that must be true as well (e.g. print state `=` `paused` and display message
`does not contain` `soaking`; an unknown value is never true): they show it while the state is true, add it to the rotation
while it is true, or show it for a while when it becomes true. Each rule is read at its own
interval (2-600 s) and can be limited to some of the blocks. The first rule that shows a
page wins. A rule can leave a page chosen by hand alone (untick "also over a page chosen by
@@ -138,7 +140,9 @@ The display schedule (on/off, when the display is on, when it switches off); slo
(also a Home Assistant switch: the display only changes every 1-60 minutes, on the clock,
and is switched off in between, for less noise); the "No WiFi" screen; the flip time, the pause after each pulse,
pulses per dot and the refresh effect (instant, sparkle, wipe, rain, from the middle out,
diagonal, spiral, flip all then reveal, push, random; optionally only for small changes
diagonal, spiral, flip all then reveal, push, Matrix (yellow streaks fall down the columns
that change and leave the new image behind them), random (with a list of the effects it can
pick from, also for pages set to random); optionally only for small changes
like the clock's minutes; pages can choose their own effect); how often every dot is flipped again ("Dot refresh", default
2 min) and how often the whole image is sent again ("Image resync", default 10 min; 0
switches either off); test patterns; the status LED.
+70 -2
View File
@@ -15,6 +15,9 @@ BROSE9323::BROSE9323(uint8_t w, uint8_t h, uint8_t pw, uint16_t ft) : Adafruit_G
_old_buffer = (uint8_t *)calloc(_buffer_size, sizeof(uint8_t));
#endif
_new_buffer = (uint8_t *)calloc(_buffer_size, sizeof(uint8_t));
#ifndef ESPSERIAL
_changed_columns = (uint8_t *)calloc(_buffer_width, sizeof(uint8_t));
#endif
}
#ifdef ESPSERIAL
@@ -424,9 +427,14 @@ void BROSE9323::_startEffect(bool all, bool instant)
{
uint16_t total = width() * height();
uint16_t changed = 0;
memset(_changed_columns, 0, _buffer_width);
for (uint8_t y = 0; y < height(); y++)
for (uint8_t x = 0; x < width(); x++)
changed += _changed(x, y);
if (_changed(x, y))
{
changed++;
_changed_columns[x >> 3] |= 1 << (x & 7);
}
if (changed == 0 && !all)
{
_animating = false;
@@ -438,7 +446,7 @@ void BROSE9323::_startEffect(bool all, bool instant)
if (effect != EFFECT_INSTANT && (_effect_flags & EFFECT_FLAG_SMALL_ONLY) && (all || changed > total / 10))
effect = EFFECT_INSTANT;
if (effect == EFFECT_RANDOM)
effect = 1 + micros() % (EFFECT_RANDOM - 1);
effect = randomEffect(micros());
// Pushing needs to know what is shown; after boot that is unknown
if (all && effect == EFFECT_PUSH)
effect = EFFECT_WIPE;
@@ -462,6 +470,15 @@ void BROSE9323::_startEffect(bool all, bool instant)
_push_pos = 0;
steps = width();
}
else if (effect == EFFECT_MATRIX)
{
_push_shift = 0;
_push_pos = 0;
_matrix_seed = micros() >> 2;
if (all)
memset(_changed_columns, 0xFF, _buffer_width);
steps = matrixTicks(height());
}
else
{
_sequence.begin(effect == EFFECT_FLAP ? EFFECT_WIPE : effect, width(), height(), (uint16_t)micros());
@@ -517,6 +534,48 @@ bool BROSE9323::_pushDot(void)
return ++_push_shift <= w;
}
// The next flip of the current matrix tick. _push_pos walks over two places per column: the
// streak's head (turns the dot yellow), then its tail (the new image). Only the changed
// columns have a streak. Only a dot's final flip gets all pulses, so the head gives a dot
// that ends up black just one: a full screen change takes much less time. False when all
// ticks are done.
bool BROSE9323::_matrixStep(void)
{
uint8_t w = width(), h = height();
uint8_t spread = matrixStartSpread(h);
while (true)
{
uint8_t x = _push_pos >> 1;
bool tail = _push_pos & 1;
bool flipped = false;
if (_changed_columns[x >> 3] & (1 << (x & 7)))
{
int16_t row = (int16_t)_push_shift - matrixStartTick(x, _matrix_seed, spread);
if (tail)
row -= MATRIX_STREAK;
if (row >= 0 && row < h)
{
bool wanted = _wanted(x, row);
bool target = tail ? wanted : true;
bool changed = _shown(x, row) != target;
if (changed || _animate_all)
{
_flipTo(x, row, target, changed && (tail || wanted) ? _pulses : 1);
flipped = true;
}
}
}
if (++_push_pos >= (uint16_t)w * 2)
{
_push_pos = 0;
_next_step += _step_time;
return ++_push_shift < matrixTicks(h);
}
if (flipped)
return true;
}
}
bool BROSE9323::busy(void) const
{
return _animating && !_drawing;
@@ -548,6 +607,15 @@ bool BROSE9323::update(void)
}
continue;
}
if (_running_effect == EFFECT_MATRIX)
{
if (!_matrixStep())
{
_animating = false;
break;
}
continue;
}
uint8_t x, y;
if (!_sequence.next(x, y))
+7 -4
View File
@@ -44,8 +44,10 @@ private:
bool _animating = false;
uint8_t _running_effect = EFFECT_INSTANT; // _effect, or the one chosen for EFFECT_RANDOM
uint8_t _phase = 0; // EFFECT_FLAP: 0 = to yellow, 1 = the new image
uint8_t _push_shift = 0; // EFFECT_PUSH: column shift 1..width
uint16_t _push_pos = 0; // EFFECT_PUSH: dot within the shift
uint8_t _push_shift = 0; // EFFECT_PUSH: column shift 1..width; EFFECT_MATRIX: tick
uint16_t _push_pos = 0; // EFFECT_PUSH: dot within the shift; EFFECT_MATRIX: see _matrixStep()
uint8_t *_changed_columns = NULL; // a bit per column, set by _startEffect() (EFFECT_MATRIX)
uint8_t _matrix_seed = 0; // EFFECT_MATRIX: different start ticks for each frame
bool _animate_all = false; // flip every dot, not only the changed ones
bool _drawing = false; // the buffer changed since the last display(): pause
uint32_t _step_time = 0; // us per step
@@ -106,6 +108,7 @@ private:
void _flipTo(uint8_t x, uint8_t y, bool on, uint8_t pulses);
void _flipDot(uint8_t x, uint8_t y, uint8_t pulses);
bool _pushDot(void);
bool _matrixStep(void);
void _startEffect(bool all, bool instant);
void _refreshStep(uint32_t start);
#endif
@@ -138,8 +141,8 @@ public:
// Pulses for each changed dot (a second pulse catches dots that didn't flip). Full
// redraws use one pulse per dot.
void setPulses(uint8_t);
// How display() shows a new frame (RefreshEffect), how long it takes in ms (pushing
// can take longer: it flips many dots per step) and EFFECT_FLAG_... flags.
// How display() shows a new frame (RefreshEffect), how long it takes in ms (push and
// matrix can take longer: they flip many dots) and EFFECT_FLAG_... flags.
// Effects run in steps from update(), so call that often (every loop).
void setEffect(uint8_t effect, uint16_t time_ms, uint8_t flags = 0);
#ifndef ESPSERIAL
+31 -2
View File
@@ -16,10 +16,39 @@ enum RefreshEffect : uint8_t
// The ones below are run by BROSE9323 itself (DotSequence uses column order for them)
EFFECT_FLAP = 7, // every dot to yellow (wipe), then the new image (wipe)
EFFECT_PUSH = 8, // the new image slides in from the right, pushing the old one out
EFFECT_RANDOM = 9, // one of the effects 1-8, chosen for each frame
EFFECT_COUNT = 10,
EFFECT_RANDOM = 9, // one of the effects 1-8 or 10, chosen for each frame
EFFECT_MATRIX = 10, // yellow streaks fall down the changed columns, the new image behind them
EFFECT_COUNT = 11,
};
// The effect for EFFECT_RANDOM. now: micros(), which only gives multiples of 4 on a 16 MHz
// Nano, so its lowest bits say nothing.
inline uint8_t randomEffect(uint32_t now)
{
uint8_t pick = 1 + (now >> 2) % 9;
return pick == EFFECT_RANDOM ? (uint8_t)EFFECT_MATRIX : pick;
}
// EFFECT_MATRIX runs in ticks: per tick every streak moves one row down. A streak's head
// starts at the top in the column's start tick and turns dots yellow; MATRIX_STREAK rows
// behind it, its tail shows the new image.
const uint8_t MATRIX_STREAK = 4;
// Columns start in the first 2/3 of the ticks, the last 1/3 is the last streak falling
inline uint8_t matrixTicks(uint8_t h) { return 3 * (h + MATRIX_STREAK); }
inline uint8_t matrixStartSpread(uint8_t h) { return 2 * (h + MATRIX_STREAK); }
// The start tick of a column, a mixed hash so that no pattern shows between the columns
// (and no RAM per column). Fast on the AVR: only 8 bit steps and one 8 x 8 multiplication.
inline uint8_t matrixStartTick(uint8_t column, uint8_t seed, uint8_t spread)
{
uint8_t v = (uint8_t)(column * 167) ^ seed;
v *= 29;
v ^= v >> 3;
v *= 113;
v ^= v >> 4;
return ((uint16_t)v * spread) >> 8;
}
// Flags for BROSE9323::setEffect()
const uint8_t EFFECT_FLAG_SMALL_ONLY = 1; // big changes (> 1/10 of the dots) are instant
// E command only: use the effect until the next E command or power cycle, without storing
+2 -1
View File
@@ -55,7 +55,8 @@ upload_command = "$PYTHONEXE" "$PROJECT_DIR/tools/nano_net_upload.py" "$SOURCE"
; ESP32 - controller, talks to the Nano over serial
; ---------------------------------------------------------------------------
[esp32_common]
platform = espressif32
; Pinned: Arduino core 2.0.17 (ESP-IDF 4.4). The firmware doesn't build on core 3 (watchdog API)
platform = espressif32@6.10.0
board = esp32doit-devkit-v1
; factory = recovery app, ota_0 / ota_1 = clock firmware (see partitions.csv)
board_build.partitions = partitions.csv
+11 -4
View File
@@ -93,9 +93,14 @@ static void applyOffPage()
static void apply()
{
controller.setSettings(settings.schedule, settings.clock, settings.slow_mode);
controller.setEffectTime(effectTime(settings.drive));
status.setDrive(settings.flip_time, settings.drive, settings.refresh.dots);
frames.setDrive(settings.flip_time, settings.drive);
controller.setEffectTime(effectTime(settings.drive, settings.random_effects));
// What the Nano stores and uses until the first frame. Its own Random doesn't know the
// list, so it never gets that: the first effect on the list instead.
DriveSettings stored_drive = settings.drive;
if (stored_drive.effect == DRIVE_EFFECT_RANDOM)
stored_drive.effect = pickRandomEffect(settings.random_effects, 0);
status.setDrive(settings.flip_time, stored_drive, settings.refresh.dots);
frames.setDrive(settings.flip_time, settings.drive, settings.random_effects);
char user[PLEX_USER_SIZE];
plexUserSlug(settings.plex_user, user, sizeof(user));
haApiSetSettings(settings.home_assistant, user);
@@ -149,6 +154,7 @@ const char *appSaveSettings(const Settings &new_settings, bool &restart_needed)
bool drive_changed = settings.flip_time != new_settings.flip_time || a.flip_gap != b.flip_gap ||
a.pulses != b.pulses || a.effect != b.effect || a.effect_time != b.effect_time ||
a.effect_small_only != b.effect_small_only ||
settings.random_effects != new_settings.random_effects ||
settings.refresh.dots != new_settings.refresh.dots;
settings = new_settings;
saveSettings(settings);
@@ -274,7 +280,8 @@ void appPageLoop(bool time_valid, const LocalTime &time)
for (int i = 0; i < page_schedule.rule_count; i++)
{
const TriggerRule &r = page_schedule.rules[i];
selector.setRuleState(i, ruleMatches(r, haApiValue(r.entity, r.attribute)), now);
const char *and_value = r.and_entity[0] ? haApiValue(r.and_entity, r.and_attribute) : nullptr;
selector.setRuleState(i, ruleMatches(r, haApiValue(r.entity, r.attribute), and_value), now);
}
time_known = time_valid;
if (!time_valid)
+1 -1
View File
@@ -118,7 +118,7 @@ const uint32_t SETUP_AP_DELAY = 20000; // open the AP when WiFi fails thi
const uint32_t WIFI_CONNECT_TIMEOUT = 30000;
const uint32_t WIFI_RESTART_TIME = 10UL * 60 * 1000;
#define FIRMWARE_VERSION "2.19.3"
#define FIRMWARE_VERSION "2.22.1"
// Home Assistant device id (do not change: Home Assistant's entities are linked to it)
const uint8_t HA_DEVICE_ID[] = {0x34, 0x86, 0x5d, 0x3a, 0x08, 0x28};
+8 -2
View File
@@ -1,5 +1,6 @@
#include "display/frames.h"
#include <esp_random.h>
#include <stdio.h>
#include <string.h>
@@ -20,16 +21,19 @@ uint32_t FlipdotFrames::dynamicPage(const LocalTime &time, uint32_t now, bool re
bool moving = wait != 0;
// The Nano has no acknowledgement: the next frame waits until it has received this one
// and flipped its dots, or the next frame overflows its serial buffer
_useEffect(_page_effect, redraw);
// Instant frames don't use the effect (moving ones come fast: no E command for each)
if (redraw || !(moving || _instant_next))
_useEffect(_page_effect, redraw);
uint32_t busy = _show(bitmap, !redraw, moving || _instant_next);
_instant_next = false;
return moving && wait < busy ? busy : wait;
}
void FlipdotFrames::setDrive(uint16_t flip_time, const DriveSettings &drive)
void FlipdotFrames::setDrive(uint16_t flip_time, const DriveSettings &drive, uint16_t random_effects)
{
_dot_us = (uint32_t)drive.pulses * (flip_time + drive.flip_gap);
_drive = drive;
_random_effects = random_effects;
_nano_effect = EFFECT_UNKNOWN;
}
@@ -37,6 +41,8 @@ void FlipdotFrames::_useEffect(uint8_t effect, bool full)
{
if (effect == PAGE_EFFECT_DEFAULT || effect >= DRIVE_EFFECT_COUNT)
effect = _drive.effect;
if (effect == DRIVE_EFFECT_RANDOM)
effect = pickRandomEffect(_random_effects, esp_random());
if (effect == _nano_effect && !full)
return;
uint8_t flags = EFFECT_FLAG_NO_SAVE | (_drive.effect_small_only ? EFFECT_FLAG_SMALL_ONLY : 0);
+3 -1
View File
@@ -32,7 +32,7 @@ public:
// block that switches instantly)
void showNextInstant() { _instant_next = true; }
// How the Nano flips the dots: for the time a frame takes, and the refresh effect
void setDrive(uint16_t flip_time, const DriveSettings &drive);
void setDrive(uint16_t flip_time, const DriveSettings &drive, uint16_t random_effects);
// The refresh effect of the shown page (PAGE_EFFECT_DEFAULT: the one of the drive
// settings). Sent to the Nano before page frames, without storing it in its EEPROM;
// the other screens (off, live, No WiFi) use the drive settings' effect.
@@ -52,6 +52,7 @@ private:
DynamicPage _dynamic;
static const uint8_t EFFECT_UNKNOWN = 254;
DriveSettings _drive;
uint16_t _random_effects = RANDOM_EFFECTS_ALL;
uint8_t _page_effect = PAGE_EFFECT_DEFAULT;
uint8_t _nano_effect = EFFECT_UNKNOWN; // the effect last sent by _useEffect()
uint32_t _dot_us = 1000;
@@ -63,6 +64,7 @@ private:
void _drawFullScreen(const uint8_t *bitmap);
// Makes the Nano use this effect (PAGE_EFFECT_DEFAULT: the drive settings' one). Sent
// when it changed, and always with full frames: a restarted Nano has the stored one.
// Random is decided here, for each frame, as only the ESP32 knows the list.
void _useEffect(uint8_t effect, bool full);
uint32_t _show(const uint8_t *bitmap, bool changes_only, bool instant);
};
+1 -1
View File
@@ -26,7 +26,7 @@ const int ELEMENT_MAP_SIZE = 64;
const char DEGREE_SIGN = 127;
// DynamicPage::effect: the refresh effect of the Hardware settings
const uint8_t PAGE_EFFECT_DEFAULT = 255;
const uint8_t PAGE_EFFECT_COUNT = 10; // DRIVE_EFFECT_COUNT (checked in logic/settings.cpp)
const uint8_t PAGE_EFFECT_COUNT = 11; // DRIVE_EFFECT_COUNT (checked in logic/settings.cpp)
enum class ElementType : uint8_t
{
+38 -7
View File
@@ -50,10 +50,16 @@ const char *validateSchedule(const PageSchedule &s)
return "Rules need an entity id like sensor.printer_state";
if (!terminated(r.attribute, sizeof(r.attribute)) || !validAttribute(r.attribute))
return "Invalid attribute";
if (r.compare >= Compare::Count || r.mode >= TriggerMode::Count)
if (r.compare >= Compare::Count || r.and_compare >= Compare::Count || r.mode >= TriggerMode::Count)
return "Unknown rule setting";
if (!terminated(r.value, sizeof(r.value)))
return "Rule value too long (32 characters)";
if (!terminated(r.and_entity, sizeof(r.and_entity)) || (r.and_entity[0] && !validEntityId(r.and_entity)))
return "Rules need an entity id like sensor.printer_state";
if (!terminated(r.and_attribute, sizeof(r.and_attribute)) || !validAttribute(r.and_attribute))
return "Invalid attribute";
if (!terminated(r.and_value, sizeof(r.and_value)))
return "Rule value too long (32 characters)";
if (!terminated(r.page, sizeof(r.page)) || !validBitmapName(r.page))
return "Choose a page for each rule";
if (r.mode != TriggerMode::WhileTrue && (r.seconds < 1 || r.seconds > ITEM_SECONDS_MAX))
@@ -74,6 +80,21 @@ static bool sameText(const char *a, const char *b)
return *a == *b;
}
// Whether `part` is somewhere in `text`, without case
static bool hasText(const char *text, const char *part)
{
for (;; text++)
{
const char *a = text, *b = part;
while (*a && *b && tolower((unsigned char)*a) == tolower((unsigned char)*b))
a++, b++;
if (!*b)
return true;
if (!*text)
return false;
}
}
static bool number(const char *text, double &value)
{
char *end;
@@ -86,26 +107,36 @@ bool ruleInBlock(const TriggerRule &rule, int block)
return rule.blocks == 0 || block < 0 || (rule.blocks >> block) & 1;
}
bool ruleMatches(const TriggerRule &rule, const char *value)
static bool conditionTrue(Compare compare, const char *value, const char *wanted)
{
if (value == nullptr)
return false;
double a, b;
switch (rule.compare)
switch (compare)
{
case Compare::Equal:
return sameText(value, rule.value);
return sameText(value, wanted);
case Compare::NotEqual:
return !sameText(value, rule.value);
return !sameText(value, wanted);
case Compare::Above:
return number(value, a) && number(rule.value, b) && a > b;
return number(value, a) && number(wanted, b) && a > b;
case Compare::Below:
return number(value, a) && number(rule.value, b) && a < b;
return number(value, a) && number(wanted, b) && a < b;
case Compare::Contains:
return hasText(value, wanted);
case Compare::NotContains:
return !hasText(value, wanted);
default:
return false;
}
}
bool ruleMatches(const TriggerRule &rule, const char *value, const char *and_value)
{
return conditionTrue(rule.compare, value, rule.value) &&
(!rule.and_entity[0] || conditionTrue(rule.and_compare, and_value, rule.and_value));
}
bool scheduleUses(const PageSchedule &s, const char *name)
{
for (int i = 0; i < s.block_count; i++)
+10 -2
View File
@@ -43,6 +43,8 @@ enum class Compare : uint8_t
NotEqual,
Above, // numbers
Below,
Contains, // text, without case
NotContains,
Count,
};
@@ -68,6 +70,11 @@ struct TriggerRule
bool over_manual = true; // also over a page picked by hand (false: it waits until the pick ends)
bool over_slow_mode = false; // while its page is shown the display works normally (slow mode waits)
bool skip_slow_mode = false; // AddToRotation: left out of the rotation while slow mode is on
// Optional second condition, which must be true as well (empty entity: none)
char and_entity[ELEMENT_ENTITY_SIZE] = "";
char and_attribute[ELEMENT_ATTRIBUTE_SIZE] = ""; // empty: the state
Compare and_compare = Compare::Equal;
char and_value[RULE_VALUE_SIZE] = "";
};
struct PageSchedule
@@ -86,8 +93,9 @@ const char *validateSchedule(const PageSchedule &schedule);
// Whether a rule acts during this block (-1: no schedule runs, then always)
bool ruleInBlock(const TriggerRule &rule, int block);
// Whether a rule's condition is true for this value (nullptr: not known, never true)
bool ruleMatches(const TriggerRule &rule, const char *value);
// Whether a rule's conditions are true for these values (nullptr: not known, never true).
// and_value is only used when the rule has a second condition.
bool ruleMatches(const TriggerRule &rule, const char *value, const char *and_value = nullptr);
// Whether the schedule or a rule shows this page or bitmap (compared without case)
bool scheduleUses(const PageSchedule &schedule, const char *name);
+22 -2
View File
@@ -39,6 +39,8 @@ const char *validateSettings(const Settings &s)
return "Unknown refresh effect";
if (d.effect_time < 100 || d.effect_time > 10000)
return "The effect time must be between 100 and 10000 ms";
if (s.random_effects == 0 || (s.random_effects & ~RANDOM_EFFECTS_ALL))
return "Random needs at least one effect to pick from";
if (s.refresh.dots > REFRESH_MINUTES_MAX || s.refresh.image > REFRESH_MINUTES_MAX)
return "Refresh intervals must be between 0 and 1440 minutes";
@@ -63,15 +65,33 @@ bool validSlowModeMinutes(int minutes)
return false;
}
uint32_t effectTime(const DriveSettings &drive)
uint32_t effectTime(const DriveSettings &drive, uint16_t random_effects)
{
if (drive.effect == DRIVE_EFFECT_INSTANT)
return 0;
if (drive.effect == DRIVE_EFFECT_PUSH || drive.effect == DRIVE_EFFECT_RANDOM)
// Random: the slowest effect it can pick
bool random = drive.effect == DRIVE_EFFECT_RANDOM;
if (drive.effect == DRIVE_EFFECT_PUSH || (random && (random_effects & (1 << DRIVE_EFFECT_PUSH))))
return drive.effect_time + DRIVE_PUSH_EXTRA_TIME;
if (drive.effect == DRIVE_EFFECT_MATRIX || (random && (random_effects & (1 << DRIVE_EFFECT_MATRIX))))
return drive.effect_time + DRIVE_MATRIX_EXTRA_TIME;
return drive.effect_time;
}
uint8_t pickRandomEffect(uint16_t random_effects, uint32_t random)
{
uint8_t count = 0;
for (uint8_t effect = 0; effect < DRIVE_EFFECT_COUNT; effect++)
count += (random_effects >> effect) & 1;
if (count == 0)
return DRIVE_EFFECT_INSTANT;
uint8_t skip = random % count;
for (uint8_t effect = 0; effect < DRIVE_EFFECT_COUNT; effect++)
if (((random_effects >> effect) & 1) && skip-- == 0)
return effect;
return DRIVE_EFFECT_INSTANT; // not reached
}
bool parseTime(const char *text, uint16_t &minutes)
{
if (text == nullptr)
+11 -2
View File
@@ -51,9 +51,14 @@ struct HomeAssistantSettings
const uint8_t DRIVE_EFFECT_INSTANT = 0; // numbers: RefreshEffect in lib/BROSE9323/dot_sequence.h
const uint8_t DRIVE_EFFECT_PUSH = 8;
const uint8_t DRIVE_EFFECT_RANDOM = 9;
const uint8_t DRIVE_EFFECT_COUNT = 10;
const uint8_t DRIVE_EFFECT_MATRIX = 10;
const uint8_t DRIVE_EFFECT_COUNT = 11;
// Pushing flips many dots per column step, so it can take much longer than effect_time
const uint32_t DRIVE_PUSH_EXTRA_TIME = 20000;
// The matrix streaks flip most dots of a changed column twice, also more than effect_time
const uint32_t DRIVE_MATRIX_EXTRA_TIME = 5000;
// What Random can pick from: bit n = effect n. All effects but Instant and Random itself.
const uint16_t RANDOM_EFFECTS_ALL = 0x05FE;
struct DriveSettings
{
@@ -96,11 +101,15 @@ struct Settings
// Plex user name for {plex_user} in entity ids (Tautulli's sensors of that user)
char plex_user[PLEX_USER_SIZE] = "";
SlowModeSettings slow_mode;
// What the Random effect picks from (drive settings and pages), see RANDOM_EFFECTS_ALL
uint16_t random_effects = RANDOM_EFFECTS_ALL;
// New fields go here, at the end (see system/settings_store.cpp)
};
// How long a new frame can take to appear on the dots in ms (0 when instant)
uint32_t effectTime(const DriveSettings &drive);
uint32_t effectTime(const DriveSettings &drive, uint16_t random_effects);
// One of the effects of a valid random_effects list. random: any random number.
uint8_t pickRandomEffect(uint16_t random_effects, uint32_t random);
const uint16_t MINUTES_PER_DAY = 24 * 60;
const uint16_t SETTINGS_FLIP_TIME_MIN = 50;
+16 -9
View File
@@ -269,6 +269,19 @@ void haApiWatch(const DynamicPage *page)
}
}
static void watchRuleEntity(const char *rule_entity, const char *attribute, uint16_t interval)
{
String entity;
if (!expand(rule_entity, entity))
return;
Entry &e = add(entity, attribute);
if (!e.watched())
e.next_poll = millis();
uint32_t ms = interval * 1000UL;
if (!e.rule_interval || ms < e.rule_interval)
e.rule_interval = ms;
}
void haApiWatchRules(const PageSchedule *schedule)
{
for (Entry &e : entries)
@@ -278,15 +291,9 @@ void haApiWatchRules(const PageSchedule *schedule)
for (int i = 0; i < schedule->rule_count; i++)
{
const TriggerRule &rule = schedule->rules[i];
String entity;
if (!expand(rule.entity, entity))
continue;
Entry &e = add(entity, rule.attribute);
if (!e.watched())
e.next_poll = millis();
uint32_t ms = rule.interval * 1000UL;
if (!e.rule_interval || ms < e.rule_interval)
e.rule_interval = ms;
watchRuleEntity(rule.entity, rule.attribute, rule.interval);
if (rule.and_entity[0])
watchRuleEntity(rule.and_entity, rule.and_attribute, rule.interval);
}
}
+4 -3
View File
@@ -6,9 +6,10 @@
static const char *NAMESPACE = "flipdot";
static const char *KEY = "schedule";
// Increase when PageSchedule changes; records of other versions are ignored (an empty
// schedule). 2.18.0 stored the schedule again in version 5. To keep the schedule over a
// change, add a frozen copy of the old layout and convert it (see git history).
static const uint16_t VERSION = 5;
// schedule). 2.20.0 added the second rule condition (version 6). To keep the schedule over a
// change, add a frozen copy of the old layout and convert it (see git history), or save it
// again through the web API after flashing.
static const uint16_t VERSION = 6;
struct StoredSchedule
{
+3 -3
View File
@@ -7,9 +7,9 @@
static const char *NAMESPACE = "flipdot";
static const char *KEY = "settings";
// Increase when the Settings struct changes; records of other versions are ignored
// (defaults). 2.15.0 stored all older records again in version 7. To keep the settings over
// a change, add a frozen copy of the old layout and convert it (see git history).
static const uint16_t VERSION = 7;
// (defaults). To keep the settings over a change, read or convert the old layout for one
// release (see git history: 2.22.0 read version 7, a prefix of version 8).
static const uint16_t VERSION = 8;
struct StoredSettings
{
+12 -3
View File
@@ -5,7 +5,7 @@
#include "logic/settings.h"
static const char *const COMPARES[] = {"eq", "ne", "gt", "lt"};
static const char *const COMPARES[] = {"eq", "ne", "gt", "lt", "contains", "not_contains"};
static const char *const MODES[] = {"while", "rotate", "for"};
template <size_t N> static int indexOf(const char *const (&names)[N], const char *name)
@@ -63,6 +63,10 @@ void scheduleToJson(const PageSchedule &s, JsonObject out)
o["over_manual"] = r.over_manual;
o["over_slow_mode"] = r.over_slow_mode;
o["skip_slow_mode"] = r.skip_slow_mode;
o["and_entity"] = r.and_entity;
o["and_attribute"] = r.and_attribute;
o["and_compare"] = COMPARES[(int)r.and_compare];
o["and_value"] = r.and_value;
JsonArray in_blocks = o["blocks"].to<JsonArray>();
for (int b = 0; b < s.block_count; b++)
if ((r.blocks >> b) & 1)
@@ -107,12 +111,17 @@ const char *scheduleFromJson(JsonVariantConst in, PageSchedule &s)
{
TriggerRule &r = s.rules[s.rule_count++];
int compare = indexOf(COMPARES, o["compare"] | "eq"), mode = indexOf(MODES, o["mode"] | "while");
if (compare < 0 || mode < 0)
int and_compare = indexOf(COMPARES, o["and_compare"] | "eq");
if (compare < 0 || and_compare < 0 || mode < 0)
return "Unknown rule setting";
r.compare = (Compare)compare;
r.and_compare = (Compare)and_compare;
r.mode = (TriggerMode)mode;
if (!copyText(o["entity"], r.entity, sizeof(r.entity)) || !copyText(o["attribute"], r.attribute, sizeof(r.attribute)) ||
!copyText(o["value"], r.value, sizeof(r.value)) || !copyText(o["page"], r.page, sizeof(r.page)))
!copyText(o["value"], r.value, sizeof(r.value)) || !copyText(o["page"], r.page, sizeof(r.page)) ||
!copyText(o["and_entity"], r.and_entity, sizeof(r.and_entity)) ||
!copyText(o["and_attribute"], r.and_attribute, sizeof(r.and_attribute)) ||
!copyText(o["and_value"], r.and_value, sizeof(r.and_value)))
return "Rule text too long";
r.seconds = constrain(o["seconds"] | 30, 0, 65535);
r.interval = constrain(o["interval"] | 10, 0, 65535);
+12 -6
View File
@@ -171,9 +171,10 @@ details{margin-top:10px}summary{cursor:pointer;color:var(--dim);font-size:13px;m
<label>Refresh effect</label><select id="h_effect"><option value="0">Instant (left to right)</option><option value="1">Sparkle</option>
<option value="2">Wipe (left to right)</option><option value="3">Rain (top to bottom)</option><option value="4">From the middle out</option>
<option value="5">Diagonal</option><option value="6">Spiral (outside in)</option><option value="7">Flip all, then reveal</option>
<option value="8">Push (slides in from the right)</option><option value="9">Random</option></select>
<option value="8">Push (slides in from the right)</option><option value="10">Matrix (falling streaks)</option><option value="9">Random</option></select>
<label>Random picks from</label><div id="h_random"></div>
<label>Effect for</label><label><input type="checkbox" id="h_small"> small changes only (the clock's minutes); a new page appears at once</label>
<label>Effect time</label><label><input type="number" id="h_efft" min="100" max="10000" style="width:6em"> ms (100-10000, not for Instant; Push needs more when many dots change)</label>
<label>Effect time</label><label><input type="number" id="h_efft" min="100" max="10000" style="width:6em"> ms (100-10000, not for Instant; Push and Matrix need more when many dots change)</label>
<label>Dot refresh</label><label>every <input type="number" id="h_rdots" min="0" max="1440" style="width:5em"> min (0 = off): every dot flipped again</label>
<label>Image resync</label><label>every <input type="number" id="h_rimg" min="0" max="1440" style="width:5em"> min (0 = off): the whole image sent again</label>
<label>Status LED</label><label><input type="checkbox" id="h_led"> blink while the display is on</label>
@@ -336,7 +337,7 @@ async function swSetStart(){const v=$('swstart').value;if(!v){msg('Pick a date a
async function live(bits){await post('/api/live',{data:toHex(bits)});msg('Shown on the display')}
async function stopLive(){await post('/api/live/stop');msg('Back to normal')}
// schedule and rules
const RCMP=[['eq','='],['ne','is not'],['gt','above'],['lt','below']];
const RCMP=[['eq','='],['ne','is not'],['gt','above'],['lt','below'],['contains','contains'],['not_contains','does not contain']];
const RMODE=[['while','show it while true'],['rotate','add it to the rotation while true'],['for','show it for a while when it becomes true']];
function sinp(o,k,type,props){const i=mk('input',Object.assign({type:type||'text',value:o[k]},props||{}));i.oninput=()=>{o[k]=type=='number'?Math.round(+i.value||0):i.value;schedDirty=true};return i}
function ssel(o,k,opts,after){const s=mk('select');opts.forEach(([v,t])=>s.append(mk('option',{value:v,textContent:t})));if(!opts.some(x=>x[0]==o[k]))s.append(mk('option',{value:o[k],textContent:o[k]+' (gone)'}));
@@ -365,6 +366,9 @@ function schedBuild(){if(!sched)return;schedLink();$('sc_en').checked=sched.enab
mk('div',{className:'row'},mk('b',{textContent:(i+1)+'. When'}),sinp(ru,'entity','text',{placeholder:'sensor.mainsailos_current_print_state',size:30,maxLength:64}),
sinp(ru,'attribute','text',{placeholder:'(the state)',size:10,maxLength:32}),ssel(ru,'compare',RCMP),sinp(ru,'value','text',{size:12,maxLength:32,placeholder:'printing'}),
btn('Test',async()=>{state.textContent='now: '+await haValue(ru.entity,ru.attribute)})),
mk('div',{className:'row'},'and',sinp(ru,'and_entity','text',{placeholder:'(optional) second entity',size:30,maxLength:64}),
sinp(ru,'and_attribute','text',{placeholder:'(the state)',size:10,maxLength:32}),ssel(ru,'and_compare',RCMP),sinp(ru,'and_value','text',{size:12,maxLength:32}),
btn('Test',async()=>{state.textContent='now: '+await haValue(ru.and_entity,ru.and_attribute)})),
mk('div',{className:'row'},'then',ssel(ru,'page',opts),ssel(ru,'mode',RMODE,()=>{secs.style.display=ru.mode=='while'?'none':'';skip.style.display=ru.mode=='rotate'?'':'none'}),secs,skip,
'read every',sinp(ru,'interval','number',{style:'width:5em',min:2,max:600}),'s',state,btn('Remove',()=>{sched.rules.splice(i,1);schedDirty=true;schedBuild()},'d')),
mk('div',{className:'row'},(()=>{const c=mk('input',{type:'checkbox',checked:ru.over_manual!==false});c.onchange=()=>{ru.over_manual=c.checked;schedDirty=true};
@@ -378,7 +382,7 @@ function schedBuild(){if(!sched)return;schedLink();$('sc_en').checked=sched.enab
function scAddBlock(){if(sched.blocks.length>=8){msg('8 blocks at most',true);return}
sched.blocks.push({start:'12:00',effect:true,items:[{page:settings.page,seconds:30}]});sched.blocks.sort(bySlot);schedDirty=true;schedBuild()}
function scAddRule(){if(sched.rules.length>=8){msg('8 rules at most',true);return}
sched.rules.push({entity:'',attribute:'',compare:'eq',value:'',page:settings.page,mode:'while',seconds:30,interval:10,over_manual:true,over_slow_mode:false,skip_slow_mode:false});schedDirty=true;schedBuild()}
sched.rules.push({entity:'',attribute:'',compare:'eq',value:'',page:settings.page,mode:'while',seconds:30,interval:10,over_manual:true,over_slow_mode:false,skip_slow_mode:false,and_entity:'',and_attribute:'',and_compare:'eq',and_value:''});schedDirty=true;schedBuild()}
async function scSave(){sched.blocks.sort(bySlot);sched=await post('/api/schedule',schedPayload());schedDirty=false;schedBuild();msg('Schedule saved');loadLists([])}
async function backToSchedule(){await post('/api/schedule/back');msg('Back to the schedule');setTimeout(pollStatusOnce,500)}
async function pollStatusOnce(){try{status=await api('/api/status');$('sc_now').textContent='Showing: '+status.shown+' ('+status.shown_status+')';$('shownnow').textContent=$('sc_now').textContent}catch(e){}}
@@ -701,10 +705,12 @@ async function cycleTest(){clearInterval(testTimer);let n=0;const step=()=>live(
await step();testTimer=setInterval(step,Math.max(4000,(settings.drive.effect?settings.drive.effect_time:0)+2000))}
async function stopTest(){clearInterval(testTimer);testTimer=null;await stopLive()}
// settings
function fillRandom(list){const d=$('h_random');d.textContent='';for(const o of $('h_effect').options)if(+o.value&&o.value!=9)
d.append(mk('label',{style:'display:inline-block;margin-right:1em'},mk('input',{type:'checkbox',value:o.value,checked:!!(list>>o.value&1)}),' '+o.textContent))}
function fill(){const s=settings;$('s_en').checked=s.schedule.enabled;$('s_day').value=s.schedule.day_start;
$('s_night').value=s.schedule.night_start;$('s_slow').checked=s.slow_mode.enabled;$('s_slowmin').value=s.slow_mode.minutes;
$('c_nw').checked=s.clock.no_wifi_screen;$('h_flip').value=s.flip_time;$('h_led').checked=s.status_led;
$('h_gap').value=s.drive.flip_gap;$('h_pulses').value=s.drive.pulses;$('h_effect').value=s.drive.effect;$('h_efft').value=s.drive.effect_time;$('h_small').checked=s.drive.effect_small_only;$('h_rdots').value=s.refresh.dots;$('h_rimg').value=s.refresh.image;
$('h_gap').value=s.drive.flip_gap;$('h_pulses').value=s.drive.pulses;$('h_effect').value=s.drive.effect;$('h_efft').value=s.drive.effect_time;$('h_small').checked=s.drive.effect_small_only;fillRandom(s.drive.random_effects);$('h_rdots').value=s.refresh.dots;$('h_rimg').value=s.refresh.image;
$('ha_en').checked=s.home_assistant.enabled;$('ha_host').value=s.home_assistant.host;$('ha_port').value=s.home_assistant.port;$('ha_user').value=s.home_assistant.user;
$('ha_pass').placeholder=s.home_assistant.password_set?'unchanged':'none';$('ha_url').value=s.home_assistant.api_url;$('ha_plex').value=s.plex_user||'';
$('ha_token').value='';$('ha_token').placeholder=s.home_assistant.token_set?'unchanged':'none'}
@@ -714,7 +720,7 @@ function collect(){const s=JSON.parse(JSON.stringify(settings));
if(sm.enabled!=settings.slow_mode.enabled||sm.minutes!=settings.slow_mode.minutes)s.slow_mode=sm;else delete s.slow_mode; // HA may have switched it meanwhile
s.clock={no_wifi_screen:$('c_nw').checked};
s.flip_time=+$('h_flip').value;s.status_led=$('h_led').checked;
s.drive={flip_gap:+$('h_gap').value,pulses:+$('h_pulses').value,effect:+$('h_effect').value,effect_time:+$('h_efft').value,effect_small_only:$('h_small').checked};s.refresh={dots:+$('h_rdots').value,image:+$('h_rimg').value};
s.drive={flip_gap:+$('h_gap').value,pulses:+$('h_pulses').value,effect:+$('h_effect').value,effect_time:+$('h_efft').value,effect_small_only:$('h_small').checked,random_effects:[...$('h_random').querySelectorAll('input')].reduce((m,c)=>c.checked?m|1<<c.value:m,0)};s.refresh={dots:+$('h_rdots').value,image:+$('h_rimg').value};
Object.assign(s.home_assistant,{enabled:$('ha_en').checked,host:$('ha_host').value.trim(),port:+$('ha_port').value,user:$('ha_user').value.trim(),api_url:$('ha_url').value.trim()});s.plex_user=$('ha_plex').value.trim();
if($('ha_pass').value)s.home_assistant.password=$('ha_pass').value;if($('ha_token').value)s.home_assistant.token=$('ha_token').value.trim();return s}
async function saveSettings(){const r=await post('/api/settings',collect());settings=r.settings;fill();msg(r.restart?'Saved, restarting...':'Settings saved')}
+3
View File
@@ -692,6 +692,7 @@ static void settingsToJson(const Settings &s, JsonObject o)
drive["effect"] = s.drive.effect;
drive["effect_time"] = s.drive.effect_time;
drive["effect_small_only"] = s.drive.effect_small_only;
drive["random_effects"] = s.random_effects;
JsonObject refresh = o["refresh"].to<JsonObject>();
refresh["dots"] = s.refresh.dots;
refresh["image"] = s.refresh.image;
@@ -760,6 +761,8 @@ static void handleSettingsPost()
if (drive["effect_time"].is<int>())
s.drive.effect_time = constrain(drive["effect_time"].as<int>(), 0, 65535);
copyBool(drive["effect_small_only"], s.drive.effect_small_only);
if (drive["random_effects"].is<int>())
s.random_effects = constrain(drive["random_effects"].as<int>(), 0, 65535);
JsonVariantConst refresh = body["refresh"];
if (refresh["dots"].is<int>())
s.refresh.dots = constrain(refresh["dots"].as<int>(), 0, 65535);
+5 -4
View File
@@ -38,9 +38,10 @@ Arduino core, EEPROM and the display driver are replaced by fakes in
so the coil supply can recover.
- **Refresh effect** (`E`): with `0` (default) a frame appears column by column as fast
as possible. The other effects (sparkle, wipe, rain, from the middle out, diagonal,
spiral, flip all then reveal, push, random) spread the flips over the effect time.
Push shifts the whole picture one column per step, so it flips many dots and can take
longer than the effect time. With flag 1 only small changes (at most 1/10 of the dots,
spiral, flip all then reveal, push, matrix, random) spread the flips over the effect
time. Push shifts the whole picture one column per step, so it flips many dots and can
take longer than the effect time. Matrix drops a yellow streak down each column that
changed, so it flips those columns' dots up to twice and can also take longer. With flag 1 only small changes (at most 1/10 of the dots,
like the clock's minutes) get the effect. After boot the dot state is unknown, so push
falls back to a wipe. They run in small steps from `loop()`, so serial data keeps
being read; while a new frame is being drawn into the buffer the effect pauses, and the
@@ -90,7 +91,7 @@ skipped and the next line starts clean. Coordinates are 2-digit **hex**. Color i
| `N` | `Nn` | Pulses for each changed dot (1–3), stored in EEPROM |
| `I` | `Innn` | Minutes between full redraws (decimal, 0–1440, 0 = never), stored in EEPROM |
| `C` | `C` | Reply `C xxxx`: checksum of the image received so far (CRC-16/CCITT of the buffer, only the dots, `lib/BROSE9323/buffer_crc.h`), 4 hex digits |
| `E` | `Ee,nnnn[,f]` | Refresh effect `e` (0 instant, 1 sparkle, 2 wipe, 3 rain, 4 from the middle out, 5 diagonal, 6 spiral, 7 flip all then reveal, 8 push, 9 random), its time in ms (100–10000) and flags `f` (1 = only small changes, default 0), stored in EEPROM |
| `E` | `Ee,nnnn[,f]` | Refresh effect `e` (0 instant, 1 sparkle, 2 wipe, 3 rain, 4 from the middle out, 5 diagonal, 6 spiral, 7 flip all then reveal, 8 push, 9 random, 10 matrix), its time in ms (100–10000) and flags `f` (1 = only small changes, default 0), stored in EEPROM |
Replies on the Nano's TX pin:
+146
View File
@@ -124,6 +124,147 @@ void test_effects_end_with_the_right_image()
}
}
// Stricter than assertPanelShows(): shownPixel() would also agree with a leftover streak
static void assertPanelHasPattern(int seed)
{
for (int x = 0; x < W; x++)
for (int y = 0; y < H; y++)
if (panel.dot[x][y] != (((x * 7 + y * 3 + seed) % 5) == 0))
{
char msg[64];
snprintf(msg, sizeof(msg), "dot %d,%d is wrong", x, y);
TEST_FAIL_MESSAGE(msg);
}
}
void test_matrix_ends_with_the_right_image_and_reaches_every_dot_after_boot()
{
BROSE9323 *d = make();
d->setEffect(EFFECT_MATRIX, 500);
drawPattern(*d, 0);
d->display();
finish(*d);
TEST_ASSERT_EQUAL(W * H, dotsFlippedAtLeast(1));
assertPanelHasPattern(0);
drawPattern(*d, 2);
d->display();
finish(*d);
assertPanelHasPattern(2);
delete d;
}
void test_matrix_flips_only_changed_columns_with_the_right_pulses()
{
BROSE9323 *d = make();
d->setEffect(EFFECT_MATRIX, 500);
d->fillScreen(0);
d->drawPixel(40, 3, 1); // stays yellow
d->drawPixel(40, 9, 1); // yellow to black
d->display();
finish(*d);
panel.clearCounts();
d->drawPixel(40, 9, 0);
d->drawPixel(40, 12, 1); // black to yellow
d->display();
finish(*d);
for (int x = 0; x < W; x++)
for (int y = 0; y < H; y++)
{
int expected = x != 40 ? 0 : y == 3 ? 0 : y == 9 ? 3 : y == 12 ? 3 : 1 + 3;
if (panel.flips[x][y] != expected)
{
char msg[64];
snprintf(msg, sizeof(msg), "dot %d,%d: %d pulses, not %d", x, y, panel.flips[x][y], expected);
TEST_FAIL_MESSAGE(msg);
}
}
TEST_ASSERT_TRUE(panel.dot[40][3]);
TEST_ASSERT_FALSE(panel.dot[40][9]);
TEST_ASSERT_TRUE(panel.dot[40][12]);
delete d;
}
void test_matrix_streak_falls_from_the_top_and_takes_the_effect_time()
{
BROSE9323 *d = make();
d->setEffect(EFFECT_MATRIX, 1000);
d->fillScreen(0);
d->display();
finish(*d);
d->drawPixel(40, 18, 1);
uint32_t start = fake_micros;
d->display();
int highest = -1, longest = 0;
while (d->busy())
{
d->update();
int lit = 0, bottom = -1;
for (int y = 0; y < H; y++)
if (panel.dot[40][y])
{
lit++;
bottom = y;
}
TEST_ASSERT_LESS_OR_EQUAL(highest + 1, bottom); // one row at a time, never upwards
if (bottom > highest)
highest = bottom;
if (lit > longest)
longest = lit;
}
TEST_ASSERT_EQUAL(H - 1, highest);
TEST_ASSERT_EQUAL(MATRIX_STREAK + 1, longest); // the tail goes after the head moved
uint32_t took = fake_micros - start;
TEST_ASSERT_UINT32_WITHIN(100000, 1000000, took);
delete d;
}
void test_matrix_full_screen_change_never_blocks_and_finishes_soon_enough()
{
BROSE9323 *d = make();
d->setEffect(EFFECT_MATRIX, 1500);
drawPattern(*d, 0);
d->display();
finish(*d);
drawPattern(*d, 1);
uint32_t start = fake_micros;
d->display();
finish(*d);
assertPanelHasPattern(1);
uint32_t took = fake_micros - start;
// DRIVE_MATRIX_EXTRA_TIME on the ESP32 keeps the power on for this much longer
TEST_ASSERT_LESS_THAN(1500000 + 5000000, took);
delete d;
}
void test_matrix_interrupted_by_a_new_frame_leaves_no_streaks()
{
BROSE9323 *d = make();
d->setEffect(EFFECT_MATRIX, 1000);
drawPattern(*d, 0);
d->display();
finish(*d);
drawPattern(*d, 1);
d->display();
// Until streaks are visible: dots yellow that are in neither image
int streak_dots = 0;
while (d->busy() && streak_dots < 10)
{
d->update();
streak_dots = 0;
for (int x = 0; x < W; x++)
for (int y = 0; y < H; y++)
streak_dots += panel.dot[x][y] && ((x * 7 + y * 3) % 5) != 0 && ((x * 7 + y * 3 + 1) % 5) != 0;
}
TEST_ASSERT_TRUE(d->busy());
drawPattern(*d, 2);
d->display(false, true); // a moving page: instant
finish(*d);
assertPanelHasPattern(2);
delete d;
}
void test_refresh_flips_every_dot_once_without_blocking()
{
BROSE9323 *d = make();
@@ -264,6 +405,11 @@ int main()
RUN_TEST(test_first_frame_flips_every_dot_without_blocking);
RUN_TEST(test_instant_frame_flips_only_the_changed_dots_with_all_pulses);
RUN_TEST(test_effects_end_with_the_right_image);
RUN_TEST(test_matrix_ends_with_the_right_image_and_reaches_every_dot_after_boot);
RUN_TEST(test_matrix_flips_only_changed_columns_with_the_right_pulses);
RUN_TEST(test_matrix_streak_falls_from_the_top_and_takes_the_effect_time);
RUN_TEST(test_matrix_full_screen_change_never_blocks_and_finishes_soon_enough);
RUN_TEST(test_matrix_interrupted_by_a_new_frame_leaves_no_streaks);
RUN_TEST(test_refresh_flips_every_dot_once_without_blocking);
RUN_TEST(test_refresh_pauses_while_a_frame_arrives_and_then_finishes);
RUN_TEST(test_refresh_waits_for_a_running_effect);
+128 -5
View File
@@ -748,14 +748,73 @@ void test_settings_drive_ranges()
void test_effect_time_is_zero_when_instant()
{
DriveSettings d;
TEST_ASSERT_EQUAL(0, (int)effectTime(d)); // default: instant
TEST_ASSERT_EQUAL(0, (int)effectTime(d, RANDOM_EFFECTS_ALL)); // default: instant
d.effect = 1;
d.effect_time = 2500;
TEST_ASSERT_EQUAL(2500, (int)effectTime(d));
TEST_ASSERT_EQUAL(2500, (int)effectTime(d, RANDOM_EFFECTS_ALL));
d.effect = DRIVE_EFFECT_PUSH; // can take much longer
TEST_ASSERT_EQUAL(2500 + (int)DRIVE_PUSH_EXTRA_TIME, (int)effectTime(d));
d.effect = DRIVE_EFFECT_RANDOM; // can be a push
TEST_ASSERT_EQUAL(2500 + (int)DRIVE_PUSH_EXTRA_TIME, (int)effectTime(d));
TEST_ASSERT_EQUAL(2500 + (int)DRIVE_PUSH_EXTRA_TIME, (int)effectTime(d, 0x2));
d.effect = DRIVE_EFFECT_MATRIX; // flips most dots of a changed column twice
TEST_ASSERT_EQUAL(2500 + (int)DRIVE_MATRIX_EXTRA_TIME, (int)effectTime(d, 0x2));
Settings s;
s.drive.effect = DRIVE_EFFECT_MATRIX;
TEST_ASSERT_NULL(validateSettings(s));
}
void test_effect_time_of_random_is_the_slowest_on_its_list()
{
DriveSettings d;
d.effect = DRIVE_EFFECT_RANDOM;
d.effect_time = 2500;
const uint16_t push = 1 << DRIVE_EFFECT_PUSH, matrix = 1 << DRIVE_EFFECT_MATRIX, sparkle = 1 << 1;
TEST_ASSERT_EQUAL(2500 + (int)DRIVE_PUSH_EXTRA_TIME, (int)effectTime(d, RANDOM_EFFECTS_ALL));
TEST_ASSERT_EQUAL(2500 + (int)DRIVE_PUSH_EXTRA_TIME, (int)effectTime(d, push | sparkle));
TEST_ASSERT_EQUAL(2500 + (int)DRIVE_MATRIX_EXTRA_TIME, (int)effectTime(d, matrix | sparkle));
TEST_ASSERT_EQUAL(2500, (int)effectTime(d, sparkle));
}
void test_random_effects_list_is_validated()
{
Settings s;
TEST_ASSERT_EQUAL_HEX16(RANDOM_EFFECTS_ALL, s.random_effects); // default: everything
TEST_ASSERT_NULL(validateSettings(s));
s.random_effects = 1 << DRIVE_EFFECT_MATRIX;
TEST_ASSERT_NULL(validateSettings(s));
s.random_effects = 0; // nothing to pick from
TEST_ASSERT_NOT_NULL(validateSettings(s));
s.random_effects = 1 << DRIVE_EFFECT_INSTANT;
TEST_ASSERT_NOT_NULL(validateSettings(s));
s.random_effects = 1 << DRIVE_EFFECT_RANDOM; // would pick itself
TEST_ASSERT_NOT_NULL(validateSettings(s));
s.random_effects = 1 << DRIVE_EFFECT_COUNT;
TEST_ASSERT_NOT_NULL(validateSettings(s));
}
void test_random_picks_only_from_its_list_and_all_of_it()
{
// Each list of 2 or 3 of the effects, and the whole list
const uint16_t lists[] = {RANDOM_EFFECTS_ALL, 1 << 3, (1 << 3) | (1 << DRIVE_EFFECT_MATRIX),
(1 << 1) | (1 << 5) | (1 << DRIVE_EFFECT_PUSH)};
for (uint16_t list : lists)
{
int seen[DRIVE_EFFECT_COUNT] = {};
for (uint32_t r = 0; r < 990; r++)
seen[pickRandomEffect(list, r * 2654435761u)]++;
for (int effect = 0; effect < DRIVE_EFFECT_COUNT; effect++)
{
if (list & (1 << effect))
{
TEST_ASSERT_GREATER_THAN(50, seen[effect]);
}
else
{
TEST_ASSERT_EQUAL(0, seen[effect]);
}
}
}
// The first on the list: what the Nano stores
TEST_ASSERT_EQUAL(DRIVE_EFFECT_MATRIX, pickRandomEffect(1 << DRIVE_EFFECT_MATRIX, 0));
TEST_ASSERT_EQUAL(3, pickRandomEffect((1 << 3) | (1 << DRIVE_EFFECT_MATRIX), 0));
}
void test_settings_off_page_blank_or_bitmap_name()
@@ -1976,6 +2035,64 @@ void test_rule_comparisons()
TEST_ASSERT_TRUE(ruleMatches(r, "-3"));
}
void test_rule_contains()
{
const char *soaking = "Soaking -- temp: 51.3C / 46.0C -- 26.8m remaining";
TriggerRule r = rule("x", TriggerMode::WhileTrue);
r.compare = Compare::Contains;
strcpy(r.value, "soaking");
TEST_ASSERT_TRUE(ruleMatches(r, soaking)); // without case
TEST_ASSERT_FALSE(ruleMatches(r, "Heating"));
TEST_ASSERT_FALSE(ruleMatches(r, ""));
TEST_ASSERT_FALSE(ruleMatches(r, nullptr));
strcpy(r.value, "remaining");
TEST_ASSERT_TRUE(ruleMatches(r, soaking)); // at the very end
strcpy(r.value, "remaining!");
TEST_ASSERT_FALSE(ruleMatches(r, soaking)); // longer than what is left of the text
strcpy(r.value, "soaking");
r.compare = Compare::NotContains;
TEST_ASSERT_FALSE(ruleMatches(r, soaking));
TEST_ASSERT_TRUE(ruleMatches(r, "Heating"));
TEST_ASSERT_TRUE(ruleMatches(r, ""));
TEST_ASSERT_FALSE(ruleMatches(r, nullptr)); // unknown is never true
}
void test_rule_second_condition()
{
TriggerRule r = rule("x", TriggerMode::WhileTrue);
strcpy(r.value, "paused");
// Without a second entity its value doesn't matter
TEST_ASSERT_TRUE(ruleMatches(r, "paused"));
TEST_ASSERT_TRUE(ruleMatches(r, "paused", "Soaking"));
strcpy(r.and_entity, "sensor.message");
r.and_compare = Compare::NotContains;
strcpy(r.and_value, "soaking");
TEST_ASSERT_TRUE(ruleMatches(r, "paused", "Filament runout"));
TEST_ASSERT_FALSE(ruleMatches(r, "paused", "Soaking -- temp: 51.3C"));
TEST_ASSERT_FALSE(ruleMatches(r, "printing", "Filament runout"));
TEST_ASSERT_FALSE(ruleMatches(r, nullptr, "Filament runout"));
TEST_ASSERT_FALSE(ruleMatches(r, "paused", nullptr)); // unknown is never true
}
void test_schedule_checks_the_second_condition()
{
PageSchedule s;
s.rule_count = 1;
s.rules[0] = rule("x", TriggerMode::WhileTrue);
TEST_ASSERT_NULL(validateSchedule(s)); // no second condition is fine
strcpy(s.rules[0].and_entity, "sensor.message");
TEST_ASSERT_NULL(validateSchedule(s));
strcpy(s.rules[0].and_entity, "not an entity");
TEST_ASSERT_NOT_NULL(validateSchedule(s));
strcpy(s.rules[0].and_entity, "sensor.message");
strcpy(s.rules[0].and_attribute, "a b");
TEST_ASSERT_NOT_NULL(validateSchedule(s));
s.rules[0].and_attribute[0] = '\0';
s.rules[0].and_compare = Compare::Count;
TEST_ASSERT_NOT_NULL(validateSchedule(s));
}
void test_selector_without_schedule_shows_the_chosen_page()
{
PageSelector sel;
@@ -3317,6 +3434,9 @@ int main()
RUN_TEST(test_settings_slow_mode_interval);
RUN_TEST(test_settings_drive_ranges);
RUN_TEST(test_effect_time_is_zero_when_instant);
RUN_TEST(test_effect_time_of_random_is_the_slowest_on_its_list);
RUN_TEST(test_random_effects_list_is_validated);
RUN_TEST(test_random_picks_only_from_its_list_and_all_of_it);
RUN_TEST(test_settings_off_page_blank_or_bitmap_name);
RUN_TEST(test_changed_off_image_is_redrawn_while_the_display_is_on);
RUN_TEST(test_settings_flip_time_and_port_ranges);
@@ -3375,6 +3495,9 @@ int main()
RUN_TEST(test_moving_page_is_redrawn_when_due);
RUN_TEST(test_schedule_validation);
RUN_TEST(test_rule_comparisons);
RUN_TEST(test_rule_contains);
RUN_TEST(test_rule_second_condition);
RUN_TEST(test_schedule_checks_the_second_condition);
RUN_TEST(test_selector_without_schedule_shows_the_chosen_page);
RUN_TEST(test_selector_rotates_the_block);
RUN_TEST(test_selector_manual_pick_until_the_next_block);
+69 -1
View File
@@ -478,7 +478,7 @@ void test_effect_without_saving()
void test_invalid_effect_is_rejected()
{
send("E10,1500\n"); // unknown effect
send("E11,1500\n"); // unknown effect
send("E1,1500,4\n"); // unknown flag
send("E1,50\n"); // too fast
send("E1\n"); // no duration
@@ -486,6 +486,18 @@ void test_invalid_effect_is_rejected()
TEST_ASSERT_TRUE(replied("ERR"));
}
void test_matrix_effect_is_accepted_and_stored()
{
send("E10,2000\n");
TEST_ASSERT_EQUAL(EFFECT_MATRIX, display.last("effect")->a);
TEST_ASSERT_FALSE(replied("ERR"));
display.calls.clear();
setup();
TEST_ASSERT_EQUAL(EFFECT_MATRIX, display.last("effect")->a);
TEST_ASSERT_EQUAL(2000, display.last("effect")->b);
send("E0,1500,0\n");
}
// Every effect order visits each dot exactly once
static void checkSequence(uint8_t effect, uint8_t w, uint8_t h, uint16_t seed)
{
@@ -574,6 +586,59 @@ void test_sparkle_order_is_scrambled()
TEST_ASSERT_LESS_THAN(n / 20, neighbours);
}
void test_random_effect_reaches_all_effects_with_nano_micros()
{
// micros() on the Nano: multiples of 4. Taking the modulo of that directly only ever
// gave sparkle and diagonal.
int seen[EFFECT_COUNT] = {};
for (uint32_t now = 0; now < 4000; now += 4)
{
uint8_t effect = randomEffect(now);
TEST_ASSERT_LESS_THAN(EFFECT_COUNT, effect);
seen[effect]++;
}
TEST_ASSERT_EQUAL(0, seen[EFFECT_INSTANT]);
TEST_ASSERT_EQUAL(0, seen[EFFECT_RANDOM]);
for (uint8_t effect = EFFECT_SPARKLE; effect < EFFECT_COUNT; effect++)
if (effect != EFFECT_RANDOM)
TEST_ASSERT_GREATER_THAN(100, seen[effect]);
}
void test_matrix_start_ticks_are_spread_without_a_pattern()
{
const uint8_t spread = matrixStartSpread(19);
TEST_ASSERT_EQUAL(matrixTicks(19), spread + 19 + MATRIX_STREAK);
for (int seed = 0; seed < 256; seed++)
{
int starts[46] = {};
int steps[46] = {};
int close = 0, previous = 0;
for (int x = 0; x < 84; x++)
{
int start = matrixStartTick(x, seed, spread);
TEST_ASSERT_LESS_THAN(spread, start);
starts[start]++;
if (x)
{
close += abs(start - previous) <= 1;
steps[(start - previous + spread) % spread]++;
}
previous = start;
}
for (int i = 0; i < spread; i++)
{
TEST_ASSERT_LESS_THAN(9, starts[i]); // no walls of streaks
TEST_ASSERT_LESS_THAN(15, steps[i]); // no diagonal lines
}
TEST_ASSERT_LESS_THAN(20, close); // no wide bands
}
// A new frame gets other columns first
int same = 0;
for (int x = 0; x < 84; x++)
same += matrixStartTick(x, 1, spread) == matrixStartTick(x, 2, spread);
TEST_ASSERT_LESS_THAN(20, same);
}
// ---------------------------------------------------------------------------
// Periodic full redraw
// ---------------------------------------------------------------------------
@@ -750,9 +815,12 @@ int main()
RUN_TEST(test_effect_is_applied_and_stored);
RUN_TEST(test_effect_without_saving);
RUN_TEST(test_invalid_effect_is_rejected);
RUN_TEST(test_matrix_effect_is_accepted_and_stored);
RUN_TEST(test_every_effect_visits_each_dot_once);
RUN_TEST(test_wipe_goes_left_to_right_and_center_starts_in_the_middle);
RUN_TEST(test_sparkle_order_is_scrambled);
RUN_TEST(test_random_effect_reaches_all_effects_with_nano_micros);
RUN_TEST(test_matrix_start_ticks_are_spread_without_a_pattern);
RUN_TEST(test_refresh_when_due);
RUN_TEST(test_refresh_only_once_per_interval);