Compare commits

..
10 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
mangavalkandClaude Opus 5.5 abd63d070f Tests against lost bytes in dense frames
- test_nano: every hex digit of B data is one drawDots() call, never single
  drawPixel() calls (the slow path that broke dense images in 2.19.2)
- tools/display_smoke_test.py: all yellow, a dense image and a checkerboard
  in live mode on the real display; fails on any frame check problem (wrong
  image, no answer, Nano restart, ERR reply)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 00:30:31 +02:00
mangavalkandClaude Opus 5.5 7a28e34380 Fix dense images on the Nano and the off image in slow mode
- Nano: B data is drawn fast enough for the serial line. A hex digit arrives
  every 87 us; with a division and four drawPixel() calls per digit a lit
  digit took about 105 us, so dense frames (all yellow, the panda bitmap)
  overflowed the 64 byte receive buffer: frames not shown or wrong, "Line
  too long", frame check repairs that failed the same way. Now the parser
  counts columns and rows and BROSE9323::drawDots() sets the 4 dots
  (about 20 us).
- ESP32: Power off and the start of the night draw the off image also when
  slow mode had the power off already (it powers on for it, once)
- Tests: drawDots() against drawPixel(), off image in slow mode
- Version 2.19.3

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 00:24:14 +02:00
mangavalkandClaude Opus 5.5 41af2944bc Faster web UI: only changed lists reloaded, icon cache kept, storage usage cached
- Web UI: loadLists(only) fetches only the lists an action changed; saving a
  bitmap, icon or font also reloads the pages that use it
- Icons: a save or delete forgets only that name and updates the name list in
  place instead of listing the directory again
- Storage usage cached until a store writes or deletes a file (at most 60 s):
  /api/status 0.6 s -> 0.08 s
- Version 2.19.2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 00:13:46 +02:00
mangavalkandClaude Opus 5.5 72a193130e Page names kept in RAM: /api/pages 1.8 s -> 1.05 s
Measured on the display with 16 pages: listing the directory took 350 ms,
and every loadPage() first asked LittleFS whether the file exists (26 ms
each) before opening it (25 ms) and reading it (11 ms); drawing all
previews took only 29 ms. The names of the stored pages are now kept
until a page is saved or deleted, and storedPage() looks there instead
of calling exists().

Version 2.19.1, tested on the display over OTA (save, list, delete).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:31:01 +02:00
mangavalkandClaude Opus 5.5 0166d0ee46 Stopwatch counts in real time from a start date, kept over a restart
The stopwatch counted with millis(), so it started at 0 after every
restart and would overflow after 49 days. It now keeps the real start
time (UTC ms) and the time counted before a pause, stored in NVS
(system/stopwatch_store) on every change, so it keeps counting while
the display is off or restarting. Stop pauses, Start continues, and the
Stopwatch tab can set the start to a date and time (local, summer time
by mktime) to count from, e.g. days since an event. Start, stop and set
need the synced time.

New page formats: 12d 4:05:09 and 3w 2d.

Version 2.19.0, tested on the display over OTA (set start, future and
invalid dates refused, pause, restart).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:22:32 +02:00
mangavalkandClaude Opus 5.5 f5e77c7eca Icon cache holds all icons, icon list kept in RAM
With the 17 life_ patterns there are 66 icons, more than the 64 names the
cache held. It was cleared when full, so every pass over all icons (Icons
tab, page previews) read each one from LittleFS again: /api/icons took
6.5 s and blocked loop() all that time. The cache now holds 128 names and
forgets the missing names first. The sorted icon list is kept until an
icon is saved or deleted. /api/icons: 6.6 s -> 0.12 s.

Version 2.18.2, tested on the display over OTA.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:10:47 +02:00
50 changed files with 1327 additions and 189 deletions

No files matched your search

+26 -1
View File
@@ -69,6 +69,16 @@ See README.md for the overview.
longer than about 5 ms overflows the 64-byte serial receive buffer; lost bytes shift the
rest of a bitmap. That was the "picture moved up" bug. `test_driver` checks the time per
`update()` call with a simulated panel.
- The `B` data path must also keep up with the line: a hex digit arrives every 87 µs.
`_bitmapData()` counts columns and rows (no divisions) and sets each digit's 4 dots with
`BROSE9323::drawDots()`. With `p % w`, `p / w` and four `drawPixel()` calls it took about
105 µs per `F`, so dense images (all yellow, a full picture) lost bytes ("Line too long",
frame check mismatches). Check new per-character work with `avr-objdump` (the mock
clock in the tests doesn't count CPU time); `test_nano` only checks that each digit is
one `drawDots()` call. After flashing Nano or driver changes, run
`python tools/display_smoke_test.py` (asks the user first: it flips the dots for about
20 s): all yellow, a dense image and a checkerboard in live mode, fails on any frame
check problem.
- Flip time is stored in EEPROM as a magic word at address 0 and a `uint16_t` at
address 2. Values outside 50–2000 µs are rejected.
- The Nano replies `READY` (at boot), `ERR: ...` and `C xxxx` (checksum of its image, for
@@ -150,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
@@ -208,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.
@@ -218,12 +231,24 @@ See README.md for the overview.
answers through a queue of plain structs: never share Strings or other state with it,
and never wait for it in `loop()`. The web UI's test button polls (`{"pending":true}`).
The web server stays in `loop()` on purpose (its handlers touch everything).
- The stopwatch (`logic/stopwatch.h`) counts in real time (UTC ms from `epochMs()`, not
`millis()`), stored in NVS on every change (`system/stopwatch_store.cpp`, bump `VERSION`
when `Stopwatch::State` changes). Start, stop and set need the synced time.
- Entity ids may contain `{plex_user}` (`expandEntity()` in `logic/page`), filled in by
`net/ha_api` with `settings.plex_user` in entity id form (`plexUserSlug()`).
- Bitmaps are cached in RAM (`display/bitmap_store`, also missing names): a LittleFS read
takes about 100 ms, and pages are drawn for every frame and every web preview. Writes
must go through `saveBitmap()`/`deleteBitmap()`, which clear the cache. Long JSON lists
are sent in pieces of about 2 KB (`sendPiece()` in `web_ui.cpp`).
- Icons are cached too (`display/icon_store`, all of them). A save or delete only forgets
that name (`forget()`) and updates the cached name list in place (`listAdd()`/
`listRemove()`): clearing it all made the next icon list read every icon again (7 s).
- Storage usage (`bitmapStorageUsage()`, for `/api/status`) is cached: `usedBytes()` walks
the file system (about 0.5 s). Every store calls `bitmapStorageChanged()` after a write
or delete; the cache also expires after 60 s.
- The web UI reloads only the lists that changed (`loadLists(only)`, the ESP32 answers one
request at a time): saving a bitmap, icon or font also reloads the pages when a page
uses it (`pagesUsing()`, `pagesWithFont()`).
- Check the page's JavaScript after changes: extract the `<script>` part and run
`node --check` on it (node is installed).
Binary file not shown.

Before

Width:  |  Height:  |  Size: 177 KiB

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB

After

Width:  |  Height:  |  Size: 131 KiB

+2 -1
View File
@@ -29,7 +29,8 @@
Schedule pages and rotation rules with "skip in slow mode" are left out of the rotation
(none left in the block: the chosen page).
- **23:31–08:00:** the screen is cleared (or shows the off image chosen in the web UI)
and power is cut after 30 seconds.
and power is cut after 30 seconds. When slow mode had the power off already, it is
switched on for this. The same goes for the Power switch.
3. **Home Assistant**: switches, dropdowns and sensors over MQTT, see
[Home Assistant](home-assistant.md).
4. **Nano.** The Nano reads commands from the serial line and updates its frame buffer.
+12 -4
View File
@@ -36,7 +36,7 @@ pages that can be changed; their Reset button brings back the original. See the
| Home Assistant value | An entity or attribute (also a path into lists, e.g. `forecast.1.temperature`), text before and after. Shown as a number (multiplier, decimals, auto unit `1257 W` → `1.3 kW`, without minus sign), a duration (`2h 21m`, `2:21:00`, `2:21`, `2 uur`), a time from an HA timestamp (`23:07`, `do 23:07`, `15-10 23:07`, `over 34 min`) or with own texts per state (`printing=Bezig, standby=Klaar`) |
| Text | Up to 32 characters |
| Countdown | To a date and time: smart (`12 dagen`, `5 uur`, `34 min`, `0:45`), days, `12d 04:05`, with seconds; a text when it has passed |
| Stopwatch | `4:05`, `0:04`, `0:04:05`; started in the [Stopwatch](#stopwatch) tab or Home Assistant |
| Stopwatch | `4:05`, `0:04`, `0:04:05`, `12d 4:05:09`, `3w 2d`; started in the [Stopwatch](#stopwatch) tab or Home Assistant |
| Image | An icon (or a bitmap) at a position, fixed or chosen by a Home Assistant state (`weer ` + `cloudy` = the icon `weer cloudy`, `weer default` when there is none) |
| Progress bar | Filled from the left by a Home Assistant number: value x multiplier / "full at" (a percentage: full at 100). Width, height, with or without a frame. Optionally the percentage on top (e.g. 42%, rounded down, in the chosen font): its dots invert the bar, so it stays readable on the filled and the empty part; left out when it doesn't fit inside (Small needs a height of 7 with a frame) |
| Game of Life | [Conway's Game of Life](https://conwaylife.com/wiki/Conway%27s_Game_of_Life) in an area (the whole display by default), one per page. Start: random dots (density %), one pattern, or the patterns whose names start with a text (e.g. `life_`) in turn or in random order, in the middle or at a random place. Edges: wrap around, dead, or a hidden margin (the world is 16 dots larger on every side, so gliders fly out of view and disappear). Speed in generations per second. It restarts when it stops changing (still, or repeating within 16 generations) and/or after a number of generations, after running on for a few seconds (an empty board at once) |
@@ -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
@@ -80,7 +82,11 @@ is shown instead. The display schedule ([Settings](#settings)) still decides whe
## Stopwatch
Start, stop and reset the stopwatch that pages can show (also in Home Assistant).
Start, stop and reset the stopwatch that pages can show (also in Home Assistant). It
counts in real time from its start, so it keeps counting while the display is off or
restarting (it is stored in NVS), and can run for years. Stop pauses it, Start continues.
**Set start** makes it count from a date and time you pick (e.g. days since an event).
Start and Set start need the synced time.
![Stopwatch](../Pictures/web-ui/stopwatch.png)
@@ -134,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.
+89 -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
@@ -290,6 +293,25 @@ void BROSE9323::printBuffer(void)
}
}
void BROSE9323::drawDots(int16_t x, int16_t y, uint8_t bits, bool color)
{
if (!(bits & 0xF) || y < 0 || y >= height())
return;
// Never used in direct mode (B commands), so only the buffer changes
_drawing = true;
uint8_t *row = _new_buffer + y * _buffer_width;
for (uint8_t mask = 8; mask; mask >>= 1, x++)
{
if (!(bits & mask) || x < 0 || x >= width())
continue;
uint8_t bit = 1 << (x & 7);
if (color)
row[x >> 3] |= bit;
else
row[x >> 3] &= ~bit;
}
}
void BROSE9323::_selectColumn(uint8_t col)
{
if (_active_col == col)
@@ -405,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;
@@ -419,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;
@@ -443,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());
@@ -498,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;
@@ -529,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))
+11 -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
@@ -154,6 +157,10 @@ public:
bool refreshing(void) const { return _refreshing; }
#endif
#ifndef ESPSERIAL
// Draws the set bits of a hex digit of B data into the buffer (bit 3 at x, bit 0 at
// x + 3), like drawPixel() but fast enough for the serial port: dense B lines take
// about 23 us per dot with drawPixel(), and a digit arrives every 87 us
void drawDots(int16_t x, int16_t y, uint8_t bits, bool color);
void printBuffer(void);
#endif
size_t print(const char *ifsh);
+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
+2 -1
View File
@@ -29,7 +29,7 @@ debug output. Wiring is described in the [documentation](../../docs/wiring.md).
| `logic/life.*` | Conway's Game of Life: the board with its edges and cycle check (`LifeBoard`), timing and restarts (`LifeRunner`) |
| `logic/page_schedule.*` | Schedule blocks and trigger rules: the structs, checks, rule conditions |
| `logic/page_selector.*` | Which page is shown now: rules, a manual pick, the rotating schedule (`PageSelector`) |
| `logic/stopwatch.h` | The stopwatch of the dynamic pages |
| `logic/stopwatch.h` | The stopwatch of the dynamic pages (real time, stored by `system/stopwatch_store`) |
| `logic/power_timer.*` | Countdown to switching the display off |
| `logic/status_led.h` | Blink pattern of the built-in LED |
| `logic/boot_policy.*` | How to start after a reset: normal, OTA-only window, safe mode |
@@ -39,6 +39,7 @@ debug output. Wiring is described in the [documentation](../../docs/wiring.md).
| `system/system_store.*` | Settings in NVS: WiFi, recovery reason, firmware slot and version, power-on count |
| `system/settings_store.*` | The web UI settings in NVS |
| `system/schedule_store.*` | The page schedule and rules in NVS |
| `system/stopwatch_store.*` | The stopwatch in NVS (keeps counting over a restart) |
| **`display/`** | **What is drawn** |
| `display/frames.*` | The screens: dynamic page, "No WiFi", page bitmap, live image, off image (`FlipdotFrames`) |
| `display/bitmap_store.*` | Built-in bitmaps and the uploaded ones on LittleFS |
+55 -7
View File
@@ -15,6 +15,7 @@
#include "net/ha_api.h"
#include "system/schedule_store.h"
#include "system/settings_store.h"
#include "system/stopwatch_store.h"
static void copyName(char *out, const char *name)
{
@@ -92,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);
@@ -119,6 +125,7 @@ void appLoadSettings()
{
loadSettings(settings);
loadSchedule(page_schedule);
loadStopwatch(stopwatch);
selector.setSchedule(&page_schedule);
selector.setChosen(settings.page);
haApiWatchRules(&page_schedule);
@@ -147,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);
@@ -272,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)
@@ -486,15 +495,54 @@ const char *appDeleteFont(const char *name)
return deleteFont(name);
}
void appStopwatch(StopwatchAction action)
static const char *NO_TIME = "The time is not synced yet";
const char *appStopwatch(StopwatchAction action)
{
// It counts in real time: before the sync, the clock still says 1970
if (!time_known && action != StopwatchAction::Reset)
return NO_TIME;
int64_t now = epochMs();
if (action == StopwatchAction::Start)
stopwatch.start(millis());
stopwatch.start(now);
else if (action == StopwatchAction::Stop)
stopwatch.stop(millis());
stopwatch.stop(now);
else
stopwatch.reset();
saveStopwatch(stopwatch);
controller.pageChanged();
return nullptr;
}
const char *appStopwatchSetStart(const char *local)
{
uint32_t minutes;
if (!parseTarget(local, minutes))
return "Invalid start: use YYYY-MM-DDTHH:MM";
if (!time_known)
return NO_TIME;
struct tm t = {};
sscanf(local, "%4d-%2d-%2dT%2d:%2d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min);
t.tm_year -= 1900;
t.tm_mon -= 1;
t.tm_isdst = -1; // the time zone decides (summer time at that date)
time_t start = mktime(&t);
if (start == (time_t)-1 || !stopwatch.setStart((int64_t)start * 1000, epochMs()))
return "The start is in the future";
saveStopwatch(stopwatch);
controller.pageChanged();
return nullptr;
}
bool appStopwatchStart(char *out)
{
if (!time_known || !stopwatch.running())
return false;
time_t start = (time_t)((epochMs() - (int64_t)stopwatch.elapsed(epochMs())) / 1000);
struct tm t;
localtime_r(&start, &t);
strftime(out, 20, "%Y-%m-%dT%H:%M:%S", &t);
return true;
}
void appShowLive(const uint8_t *bitmap)
+7 -1
View File
@@ -77,7 +77,13 @@ enum class StopwatchAction
Stop,
Reset,
};
void appStopwatch(StopwatchAction action);
// nullptr or what went wrong (start and stop need the synced time)
const char *appStopwatch(StopwatchAction action);
// Counts from this local date and time on ("YYYY-MM-DDTHH:MM", in the past), running
const char *appStopwatchSetStart(const char *local);
// The local time it counts from when it is running ("YYYY-MM-DDTHH:MM:SS"; out holds 20
// characters); false when it is stopped or the time is not synced
bool appStopwatchStart(char *out);
// Live mode of the web UI
void appShowLive(const uint8_t *bitmap);
+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.18.1"
#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};
+23 -2
View File
@@ -62,10 +62,29 @@ bool bitmapStorageAvailable()
return mounted;
}
// usedBytes() walks the whole file system (about 0.5 s), and the web UI asks every 5 s:
// kept until a file is written or deleted, at most USAGE_MAX_AGE
static const uint32_t USAGE_MAX_AGE = 60000;
static bool usage_valid = false;
static uint32_t usage_time = 0;
static size_t usage_used = 0, usage_total = 0;
void bitmapStorageChanged()
{
usage_valid = false;
}
void bitmapStorageUsage(size_t &used, size_t &total)
{
used = mounted ? LittleFS.usedBytes() : 0;
total = mounted ? LittleFS.totalBytes() : 0;
if (!usage_valid || millis() - usage_time >= USAGE_MAX_AGE)
{
usage_used = mounted ? LittleFS.usedBytes() : 0;
usage_total = mounted ? LittleFS.totalBytes() : 0;
usage_valid = true;
usage_time = millis();
}
used = usage_used;
total = usage_total;
}
std::vector<String> storedNames(const char *dir_path, const char *extension)
@@ -175,6 +194,7 @@ const char *saveBitmap(const char *name, const uint8_t *bitmap)
bool ok = file.write(bitmap, BITMAP_BYTES) == (size_t)BITMAP_BYTES;
file.close();
revision++;
bitmapStorageChanged();
cache.clear();
return ok ? nullptr : "Storage full";
}
@@ -188,6 +208,7 @@ const char *deleteBitmap(const char *name)
if (!LittleFS.remove(path(name)))
return "Could not delete the file";
revision++;
bitmapStorageChanged();
cache.clear();
return nullptr;
}
+2
View File
@@ -24,6 +24,8 @@ bool bitmapStoreBegin();
// (LittleFS is shared with display/page_store and display/font_store)
bool bitmapStorageAvailable();
void bitmapStorageUsage(size_t &used, size_t &total);
// A file in the storage was written or deleted (the stores call it): usage changed
void bitmapStorageChanged();
// The valid names of the files with this extension in a LittleFS directory
std::vector<String> storedNames(const char *dir, const char *extension);
+2
View File
@@ -97,6 +97,7 @@ const char *saveFont(const char *name, const uint8_t *data, size_t size)
file.close();
cache.clear();
revision++;
bitmapStorageChanged();
return ok ? nullptr : "Could not write the file (storage full?)";
}
@@ -110,5 +111,6 @@ const char *deleteFont(const char *name)
return "Could not delete the file";
cache.clear();
revision++;
bitmapStorageChanged();
return nullptr;
}
+7 -1
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
// 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);
};
+69 -8
View File
@@ -2,6 +2,7 @@
#include <LittleFS.h>
#include <algorithm>
#include <iterator>
#include <map>
#include <strings.h>
@@ -49,14 +50,36 @@ static uint32_t revision = 0;
static int count = -1;
// Like the bitmaps (display/bitmap_store.cpp): images try a name per state, and pages are
// drawn for every frame and preview, so icons and missing names are kept in RAM
// drawn for every frame and preview, so icons and missing names are kept in RAM. Room for
// more names than there are icons: when the cache is cleared during a pass over all icons
// (Icons tab, page previews), every one of them is read again (6.5 s with 66 icons and a
// limit of 64). About 270 bytes per name.
struct CachedIcon
{
bool exists;
Icon icon;
};
static std::map<String, CachedIcon> cache;
static const size_t CACHE_MAX = 64;
static const size_t CACHE_MAX = 128;
// After a save or delete: only this name (in any case, as it was looked up) is read again.
// Clearing everything made the next list of all icons read each one again (7 s).
static void forget(const char *name)
{
for (auto it = cache.begin(); it != cache.end();)
it = it->first.equalsIgnoreCase(name) ? cache.erase(it) : std::next(it);
}
// Full: first forget the missing names, only then the icons
static void makeRoom()
{
if (cache.size() < CACHE_MAX)
return;
for (auto it = cache.begin(); it != cache.end();)
it = it->second.exists ? std::next(it) : cache.erase(it);
if (cache.size() >= CACHE_MAX)
cache.clear();
}
static String path(const char *name)
{
@@ -82,14 +105,46 @@ void iconStoreBegin()
}
}
// The sorted names, listed once (about a second) and then kept up to date
static std::vector<String> listed;
static bool listed_valid = false;
static bool nameBefore(const String &a, const String &b)
{
return strcasecmp(a.c_str(), b.c_str()) < 0;
}
static void listAdd(const char *name)
{
// It may replace a built-in one in another case: list again
if (builtinIconName(name))
listed_valid = false;
if (!listed_valid || std::find(listed.begin(), listed.end(), String(name)) != listed.end())
return;
listed.insert(std::lower_bound(listed.begin(), listed.end(), String(name), nameBefore), String(name));
}
static void listRemove(const char *name)
{
// A built-in one stays in the list (from the firmware): list again
if (builtinIconName(name))
listed_valid = false;
auto it = std::find(listed.begin(), listed.end(), String(name));
if (listed_valid && it != listed.end())
listed.erase(it);
}
std::vector<String> listIcons()
{
if (listed_valid)
return listed;
std::vector<String> names = storedNames(DIR, ".bin");
for (const BuiltinIcon &b : BUILTIN) // not stored (no storage)
if (std::none_of(names.begin(), names.end(), [&b](const String &n) { return strcasecmp(n.c_str(), b.name) == 0; }))
names.push_back(b.name);
std::sort(names.begin(), names.end(),
[](const String &a, const String &b) { return strcasecmp(a.c_str(), b.c_str()) < 0; });
std::sort(names.begin(), names.end(), nameBefore);
listed = names;
listed_valid = true;
return names;
}
@@ -138,8 +193,7 @@ bool loadIcon(const char *name, Icon &icon)
}
if (!ok)
ok = builtinIcon(name, loaded);
if (cache.size() >= CACHE_MAX)
cache.clear();
makeRoom();
CachedIcon &entry = cache[name];
entry.exists = ok;
if (ok)
@@ -172,15 +226,20 @@ const char *saveIcon(const char *name, const Icon &icon)
bool ok = file.write(size, 2) == 2 && file.write(icon.data, bytes) == bytes;
file.close();
revision++;
cache.clear();
bitmapStorageChanged();
forget(name);
if (!ok)
{
listed_valid = false;
LittleFS.remove(path(name)); // not half an icon
count = -1;
return "Storage full";
}
if (is_new)
{
count++;
listAdd(name);
}
return nullptr;
}
@@ -193,6 +252,8 @@ const char *deleteIcon(const char *name)
if (count > 0)
count--;
revision++;
cache.clear();
bitmapStorageChanged();
forget(name);
listRemove(name);
return nullptr;
}
+10 -2
View File
@@ -1,6 +1,7 @@
#include "display/page_resources.h"
#include <Arduino.h>
#include <sys/time.h>
#include "display/bitmap_store.h"
#include "display/font_store.h"
@@ -32,9 +33,16 @@ const char *StoredPageResources::haValue(const PageElement &element)
return haApiValue(element.entity, element.attribute);
}
uint32_t StoredPageResources::stopwatchMs()
uint64_t StoredPageResources::stopwatchMs()
{
return _stopwatch.elapsed(millis());
return _stopwatch.elapsed(epochMs());
}
int64_t epochMs()
{
struct timeval tv;
gettimeofday(&tv, nullptr);
return (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
bool StoredPageResources::stopwatchRunning()
+3 -1
View File
@@ -14,7 +14,7 @@ public:
bool background(const char *name, uint8_t *bitmap) override;
Font font(const char *name) override;
const char *haValue(const PageElement &element) override;
uint32_t stopwatchMs() override;
uint64_t stopwatchMs() override;
bool stopwatchRunning() override;
const LifeRunner *life(const PageElement &element) override;
@@ -23,4 +23,6 @@ private:
};
extern Stopwatch stopwatch;
// The real time in ms since 1970 (UTC), for the stopwatch; only right once the time is synced
int64_t epochMs();
extern StoredPageResources pageResources;
+32 -5
View File
@@ -25,9 +25,29 @@ static String path(const char *name)
return String(DIR) + "/" + name + EXTENSION;
}
// The names of the stored pages, kept until a page is saved or deleted: listing the
// directory takes about 350 ms with 16 pages, and each exists() about 25 ms
static std::vector<String> names;
static bool names_valid = false;
static const std::vector<String> &storedPageNames()
{
if (!names_valid)
{
names = bitmapStorageAvailable() ? storedNames(DIR, EXTENSION) : std::vector<String>();
names_valid = true;
}
return names;
}
static bool storedPage(const char *name)
{
return bitmapStorageAvailable() && validBitmapName(name) && LittleFS.exists(path(name));
if (!bitmapStorageAvailable() || !validBitmapName(name))
return false;
for (const String &stored : storedPageNames())
if (stored == name) // like exists(): the file names are case-sensitive
return true;
return false;
}
void pageStoreBegin()
@@ -48,7 +68,7 @@ std::vector<PageInfo> listPages()
for (int i = 0; i < builtinPageCount(); i++)
if (!storedPage(builtinPageName(i)))
list.push_back({builtinPageName(i), true, false});
for (const String &name : storedNames(DIR, EXTENSION))
for (const String &name : storedPageNames())
list.push_back({name, false, builtinPageName(name.c_str()) != nullptr});
return list;
}
@@ -99,7 +119,7 @@ const char *savePage(const char *name, const DynamicPage &page)
return error;
if (!bitmapStorageAvailable())
return "No storage (install the new flash layout over USB, see README)";
if (!LittleFS.exists(path(name)) && storedNames(DIR, EXTENSION).size() >= (size_t)MAX_PAGES)
if (!storedPage(name) && storedPageNames().size() >= (size_t)MAX_PAGES)
return "Too many pages, delete some first";
StoredPage *stored = new StoredPage;
@@ -112,6 +132,8 @@ const char *savePage(const char *name, const DynamicPage &page)
file.close();
delete stored;
revision++;
bitmapStorageChanged();
names_valid = false;
return ok ? nullptr : "Could not write the file (storage full?)";
}
@@ -121,9 +143,12 @@ const char *deletePage(const char *name)
return "Built-in pages can't be deleted";
if (!storedPage(name))
return "Page not found";
if (!LittleFS.remove(path(name)))
bool removed = LittleFS.remove(path(name));
names_valid = false;
if (!removed)
return "Could not delete the file";
revision++;
bitmapStorageChanged();
return nullptr;
}
@@ -132,7 +157,9 @@ template <typename F> static String findPage(F uses)
{
DynamicPage *page = new DynamicPage;
String found;
for (const String &name : storedNames(DIR, EXTENSION))
// A copy: loadPage() may list the directory again
std::vector<String> list = storedPageNames();
for (const String &name : list)
if (loadPage(name.c_str(), *page) && uses(*page))
{
found = name;
+6 -2
View File
@@ -103,8 +103,9 @@ void DisplayController::update(uint32_t now, bool time_valid, const LocalTime &t
if (!_power_enabled)
{
if (_power.isOn())
if (_power.isOn() || _off_needed)
{
_ensureOn();
_showOnce(Screen::Off);
_off_timer.request(now, CLEAR_BEFORE_OFF_TIME + _effect_time);
}
@@ -129,8 +130,9 @@ void DisplayController::update(uint32_t now, bool time_valid, const LocalTime &t
case ScheduleMode::Night:
_slow_last = -1; // the morning starts with an update
_slow_keep = false;
if (_power.isOn())
if (_power.isOn() || _off_needed)
{
_ensureOn();
_showOnce(Screen::Off);
_off_timer.request(now, POWER_OFF_DELAY);
}
@@ -209,6 +211,7 @@ void DisplayController::_showDynamic(uint32_t now, const LocalTime &time, bool n
_dynamic_due = now + wait;
}
_screen = screen;
_off_needed = true;
_shown_hour = time.hour;
_shown_minute = time.minute;
_shown_revision = _content_revision;
@@ -232,5 +235,6 @@ void DisplayController::_showOnce(Screen screen)
break;
}
_screen = screen;
_off_needed = screen != Screen::Off;
_shown_revision = _content_revision;
}
+3
View File
@@ -109,6 +109,9 @@ private:
bool _power_enabled = true;
Screen _screen = Screen::Unknown;
// The dots show a frame other than the off screen, also while the power is off (slow
// mode): Power off and night power on to draw the off screen
bool _off_needed = false;
int _shown_hour = -1;
int _shown_minute = -1;
uint32_t _dynamic_due = 0; // millis() when a moving dynamic page is drawn again
+15 -5
View File
@@ -778,13 +778,23 @@ static void formatCountdown(const PageElement &e, const LocalTime &t, char *out,
snprintf(out, size, "%s%s", e.text, value);
}
static void formatStopwatch(const PageElement &e, uint32_t ms, char *out, size_t size)
static void formatStopwatch(const PageElement &e, uint64_t ms, char *out, size_t size)
{
unsigned long s = ms / 1000, h = s / 3600, m = s % 3600 / 60, sec = s % 60;
unsigned long s = (unsigned long)(ms / 1000), h = s / 3600, m = s % 3600 / 60, sec = s % 60;
unsigned long days = h / 24;
char value[24];
if (e.format == STOPWATCH_H_MM)
if (e.format == STOPWATCH_W_D)
{
if (days >= 7)
snprintf(value, sizeof(value), "%luw %lud", days / 7, days % 7);
else
snprintf(value, sizeof(value), "%lud", days);
}
else if (e.format == STOPWATCH_D_H_MM_SS && days)
snprintf(value, sizeof(value), "%lud %lu:%02lu:%02lu", days, h % 24, m, sec);
else if (e.format == STOPWATCH_H_MM)
snprintf(value, sizeof(value), "%lu:%02lu", h, m);
else if (e.format == STOPWATCH_H_MM_SS || h)
else if (e.format == STOPWATCH_H_MM_SS || e.format == STOPWATCH_D_H_MM_SS || h)
snprintf(value, sizeof(value), "%lu:%02lu:%02lu", h, m, sec);
else
snprintf(value, sizeof(value), "%lu:%02lu", m, sec);
@@ -860,7 +870,7 @@ bool elementShowsSeconds(const PageElement &e, const LocalTime &t, bool stopwatc
case ElementType::Clock:
return e.format == CLOCK_HH_MM_SS || e.format == CLOCK_H_MM_SS;
case ElementType::Stopwatch:
return stopwatch_running && e.format != STOPWATCH_H_MM;
return stopwatch_running && e.format != STOPWATCH_H_MM && e.format != STOPWATCH_W_D;
case ElementType::Countdown:
{
int64_t left = secondsLeft(e, t);
+5 -3
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
{
@@ -97,7 +97,9 @@ const uint8_t COUNTDOWN_FORMAT_COUNT = 4;
const uint8_t STOPWATCH_M_SS = 0; // 4:05, from an hour on 1:04:05
const uint8_t STOPWATCH_H_MM = 1; // 0:04 (hours and minutes)
const uint8_t STOPWATCH_H_MM_SS = 2; // 0:04:05
const uint8_t STOPWATCH_FORMAT_COUNT = 3;
const uint8_t STOPWATCH_D_H_MM_SS = 3; // 12d 4:05:09, below a day 4:05:09
const uint8_t STOPWATCH_W_D = 4; // 3w 2d, without the weeks below a week
const uint8_t STOPWATCH_FORMAT_COUNT = 5;
// Progress bar formats
const uint8_t BAR_PLAIN = 0; // only the bar
@@ -238,7 +240,7 @@ const PageSlot *activeSlot(const DynamicPage &page, int minute_of_day);
struct ElementValues
{
const char *ha_value = nullptr; // nullptr: not known yet, shown as "--"
uint32_t stopwatch_ms = 0;
uint64_t stopwatch_ms = 0;
};
// The text of an element (not for images). out_size must be at least 2.
+4 -4
View File
@@ -270,7 +270,7 @@ uint32_t renderPage(const DynamicPage &page, const LocalTime &time, uint32_t now
uint32_t next = 0;
bool running = resources.stopwatchRunning();
uint32_t stopwatch_ms = resources.stopwatchMs();
uint64_t stopwatch_ms = resources.stopwatchMs();
for (int i = 0; i < page.element_count && i < PAGE_ELEMENTS; i++)
{
const PageElement &e = page.elements[i];
@@ -292,10 +292,10 @@ uint32_t renderPage(const DynamicPage &page, const LocalTime &time, uint32_t now
next = sooner(next, drawTextElement(e, text, now_ms, resources, bitmap, box));
if (elementShowsSeconds(e, time, running)) // the stopwatch's seconds count from its start
next = sooner(next, e.type == ElementType::Stopwatch ? 1000 - stopwatch_ms % 1000
next = sooner(next, e.type == ElementType::Stopwatch ? 1000 - (uint32_t)(stopwatch_ms % 1000)
: 1000 - (time.millisecond % 1000));
else if (e.type == ElementType::Stopwatch && running) // H:MM: the next stopwatch minute
next = sooner(next, 60000 - stopwatch_ms % 60000);
else if (e.type == ElementType::Stopwatch && running) // H:MM, weeks/days: the next stopwatch minute
next = sooner(next, 60000 - (uint32_t)(stopwatch_ms % 60000));
}
if (boxes)
boxes[i] = box;
+1 -1
View File
@@ -20,7 +20,7 @@ public:
virtual Font font(const char *name) = 0;
// The current value of a Home Assistant element; nullptr when not known
virtual const char *haValue(const PageElement &element) = 0;
virtual uint32_t stopwatchMs() { return 0; }
virtual uint64_t stopwatchMs() { return 0; }
virtual bool stopwatchRunning() { return false; }
// The running Game of Life of the shown page when this element starts like it
// (sameLifeStart); nullptr otherwise (the start is drawn then)
+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;
+42 -17
View File
@@ -3,35 +3,60 @@
#include <stdint.h>
// The stopwatch of the dynamic pages, started and stopped in the web UI and Home Assistant.
// Times are millis(). Pure logic, tested in test/test_esp32.
// Times are the real time in ms since 1970 (UTC), so it counts from a date, keeps counting
// while the display is off or restarting (system/stopwatch_store keeps it in NVS) and can
// run for years. Pure logic, tested in test/test_esp32.
class Stopwatch
{
public:
void start(uint32_t now)
// The state as it is stored
struct State
{
if (_running)
bool running = false;
int64_t started = 0; // when it was started (again)
int64_t before = 0; // ms counted before the last start
};
void start(int64_t now)
{
if (_state.running)
return;
_running = true;
_started = now;
_state.running = true;
_state.started = now;
}
void stop(uint32_t now)
void stop(int64_t now)
{
if (!_running)
if (!_state.running)
return;
_before += now - _started;
_running = false;
_state.before = elapsed(now);
_state.running = false;
}
// Back to 0, stopped
void reset()
void reset() { _state = State(); }
// Counts from this moment (in the past) on, running; false (nothing changed) when it is
// in the future
bool setStart(int64_t start, int64_t now)
{
_running = false;
_before = 0;
if (start > now)
return false;
_state.running = true;
_state.started = start;
_state.before = 0;
return true;
}
bool running() const { return _running; }
uint32_t elapsed(uint32_t now) const { return _before + (_running ? now - _started : 0); }
bool running() const { return _state.running; }
// Never negative (the clock set back)
uint64_t elapsed(int64_t now) const
{
int64_t ms = _state.before;
if (_state.running && now > _state.started)
ms += now - _state.started;
return ms > 0 ? (uint64_t)ms : 0;
}
const State &state() const { return _state; }
void restore(const State &state) { _state = state; }
private:
bool _running = false;
uint32_t _started = 0;
uint32_t _before = 0; // ms counted before the last start
State _state;
};
+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
{
+41
View File
@@ -0,0 +1,41 @@
#include "system/stopwatch_store.h"
#include <Preferences.h>
static const char *NAMESPACE = "flipdot";
static const char *KEY = "stopwatch";
// Increase when Stopwatch::State changes; records of other versions are ignored
static const uint16_t VERSION = 1;
struct StoredStopwatch
{
uint16_t version;
uint16_t size;
Stopwatch::State state;
};
void loadStopwatch(Stopwatch &stopwatch)
{
stopwatch.reset();
StoredStopwatch stored;
Preferences prefs;
prefs.begin(NAMESPACE, true);
bool ok = prefs.isKey(KEY) && prefs.getBytesLength(KEY) == sizeof(stored) &&
prefs.getBytes(KEY, &stored, sizeof(stored)) == sizeof(stored);
prefs.end();
if (ok && stored.version == VERSION && stored.size == sizeof(Stopwatch::State) && stored.state.before >= 0 &&
stored.state.started >= 0)
stopwatch.restore(stored.state);
}
void saveStopwatch(const Stopwatch &stopwatch)
{
StoredStopwatch stored;
stored.version = VERSION;
stored.size = sizeof(Stopwatch::State);
stored.state = stopwatch.state();
Preferences prefs;
prefs.begin(NAMESPACE, false);
prefs.putBytes(KEY, &stored, sizeof(stored));
prefs.end();
}
+8
View File
@@ -0,0 +1,8 @@
#pragma once
#include "logic/stopwatch.h"
// The stopwatch in NVS (namespace "flipdot", key "stopwatch"), so it keeps counting over a
// restart. A missing, outdated or invalid record gives a stopwatch at 0.
void loadStopwatch(Stopwatch &stopwatch);
void saveStopwatch(const Stopwatch &stopwatch);
+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);
+57 -36
View File
@@ -108,9 +108,11 @@ details{margin-top:10px}summary{cursor:pointer;color:var(--dim);font-size:13px;m
<section id="t-stopwatch"><div class="card"><h2>Stopwatch</h2>
<div class="row"><b id="swtime" style="font-size:32px;font-variant-numeric:tabular-nums">0:00</b></div>
<div class="row"><span id="swsince" class="hint"></span></div>
<div class="row"><button class="b" onclick="stopwatch('start')">Start</button><button class="s" onclick="stopwatch('stop')">Stop</button>
<button class="s" onclick="stopwatch('reset')">Reset</button></div>
<p class="hint">Shown by pages with a stopwatch element (e.g. the Stopwatch page). Also in Home Assistant: the Stopwatch switch and the Stopwatch reset button.</p></div></section>
<div class="row"><label>Counting since <input type="datetime-local" id="swstart"></label><button class="s" onclick="swSetStart()">Set start</button></div>
<p class="hint">Shown by pages with a stopwatch element (e.g. the Stopwatch page). It counts in real time from its start, also while the display is off or restarting. Stop pauses it, Start continues. Set start: counts from that date and time on (e.g. days since an event). Also in Home Assistant: the Stopwatch switch and the Stopwatch reset button.</p></div></section>
<section id="t-bitmaps"><div class="card"><h2>Bitmaps</h2><div class="grid" id="bitmaps"></div>
<details id="bitmaps_used_box"><summary></summary><div class="grid" id="bitmaps_used"></div></details>
@@ -169,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>
@@ -214,7 +217,7 @@ details{margin-top:10px}summary{cursor:pointer;color:var(--dim);font-size:13px;m
</main><div id="msg"></div>
<script>
const W=84,H=19,RB=11,$=id=>document.getElementById(id);
let settings=null,status=null,bitmapList=[],iconList=[],pageList=[],fontList=[],sched=null,schedDirty=false;
let settings=null,status=null,bitmapList=[],iconList=[],pageList=[],fontList=[],storageOk=true,sched=null,schedDirty=false;
const tabs=[['show','Show'],['pages','Pages'],['schedule','Schedule'],['stopwatch','Stopwatch'],['bitmaps','Bitmaps'],['icons','Icons'],['draw','Draw / Live'],['settings','Settings'],['ha','Home Assistant'],['system','System']];
tabs.forEach(([id,name],i)=>{const b=document.createElement('button');b.textContent=name;b.onclick=()=>tab(id);b.id='b-'+id;$('tabs').appendChild(b)});
function tab(id){if(!$('t-'+id))id='show';tabs.forEach(([t])=>{$('t-'+t).classList.toggle('on',t==id);$('b-'+t).classList.toggle('on',t==id)});location.hash=id}
@@ -267,15 +270,27 @@ function usedBitmaps(){const u=new Set(),add=n=>n&&u.add(n.toLowerCase());
else if(e.text)bitmapList.forEach(b=>{if(b.name.toLowerCase().startsWith(e.text.toLowerCase()))add(b.name)})})}
if(sched)(sched.rules||[]).forEach(r=>add(r.page));return u}
// The bitmaps and icons a page shows (backgrounds, fixed images, the names of images by state)
function pageImages(page){const u=new Set(),add=n=>n&&u.add(n.toLowerCase());(page.slots||[]).forEach(s=>add(s.bitmap));
function pageImages(page,extra=[]){const u=new Set(),add=n=>n&&u.add(n.toLowerCase()),icons=iconList.concat(extra);(page.slots||[]).forEach(s=>add(s.bitmap));
(page.elements||[]).forEach(e=>{if(e.type=='life'&&e.start=='pattern')add(e.text);
if(e.type=='life'&&(e.start=='rotate'||e.start=='shuffle'))iconList.forEach(b=>{if(b.name.toLowerCase().startsWith((e.text||'').toLowerCase()))add(b.name)});
if(e.type=='life'&&(e.start=='rotate'||e.start=='shuffle'))icons.forEach(b=>{if(b.name.toLowerCase().startsWith((e.text||'').toLowerCase()))add(b.name)});
if(e.type!='image')return;if(!e.entity)add(e.text);
else if(e.text)bitmapList.concat(iconList).forEach(b=>{if(b.name.toLowerCase().startsWith(e.text.toLowerCase()))add(b.name)})});return u}
else if(e.text)bitmapList.concat(icons).forEach(b=>{if(b.name.toLowerCase().startsWith(e.text.toLowerCase()))add(b.name)})});return u}
function subsection(id,n){$(id+'_box').style.display=n?'':'none';$(id+'_box').querySelector('summary').textContent='Used by pages and rules ('+n+')'}
async function loadLists(){const[b,p,f,sc,ic]=await Promise.all([getList('/api/bitmaps','bitmaps'),getList('/api/pages','pages'),getList('/api/fonts','fonts'),getList('/api/schedule','blocks'),getList('/api/icons','icons')]);
bitmapList=b.bitmaps;pageList=p.pages;fontList=f.fonts;iconList=ic.icons;iconList.forEach(x=>x.bits=icFromHex(x.width,x.height,x.data));if(!schedDirty)sched=sc.blocks&&sc.rules?sc:{enabled:true,blocks:[],rules:[]};bitmapList.forEach(bm=>bm.bits=fromHex(bm.data));pageList.forEach(pg=>pg.bits=fromHex(pg.data));
$('storage').textContent=b.storage?'':'Storage not available: install the new flash layout (see README).';
// Pages that must be loaded again (their previews are drawn on the ESP32) when these
// bitmaps or icons change, or when this font changes
const pagesUsing=(...names)=>pageList.some(p=>{const u=pageImages(p.page,names.map(name=>({name})));return names.some(n=>u.has(n.toLowerCase()))})?['pages']:[];
const pagesWithFont=n=>pageList.some(p=>(p.page.elements||[]).some(e=>same(e.font,n)))?['pages']:[];
// Loads the lists named in `only` again (bitmaps, pages, fonts, schedule, icons; all when
// left out) and redraws them all. The ESP32 answers one request at a time, so after a
// change only what changed is fetched.
async function loadLists(only){const want=k=>!only||only.includes(k),get=(k,p,key)=>want(k)?getList(p,key):null;
const[b,p,f,sc,ic]=await Promise.all([get('bitmaps','/api/bitmaps','bitmaps'),get('pages','/api/pages','pages'),get('fonts','/api/fonts','fonts'),get('schedule','/api/schedule','blocks'),get('icons','/api/icons','icons')]);
if(b){bitmapList=b.bitmaps;bitmapList.forEach(bm=>bm.bits=fromHex(bm.data));storageOk=b.storage}
if(p){pageList=p.pages;pageList.forEach(pg=>pg.bits=fromHex(pg.data))}
if(f)fontList=f.fonts;
if(ic){iconList=ic.icons;iconList.forEach(x=>x.bits=icFromHex(x.width,x.height,x.data))}
if(sc&&!schedDirty)sched=sc.blocks&&sc.rules?sc:{enabled:true,blocks:[],rules:[]};
$('storage').textContent=storageOk?'':'Storage not available: install the new flash layout (see README).';
const pages=$('pages'),offs=$('offpages'),bms=$('bitmaps'),dyn=$('dynpages'),used=usedBitmaps();
['pages','offpages','bitmaps','dynpages','pages_used','offpages_used','bitmaps_used'].forEach(id=>$(id).innerHTML='');
offs.appendChild(card('Blank','all dots off',new Uint8Array(W*H),()=>selectOff(''),settings&&!settings.off_page));
@@ -306,22 +321,23 @@ async function loadLists(){const[b,p,f,sc,ic]=await Promise.all([getList('/api/b
function btn(t,f,cls){const b=document.createElement('button');b.className='s '+(cls||'');b.textContent=t;b.onclick=e=>{e.stopPropagation();f()};return b}
function card(name,tag,bits,onclick,cur){const d=mk('div',{className:'item'+(cur?' cur':'')});d.appendChild(mini(bits));
d.append(mk('div',{className:'name',textContent:name}),mk('div',{className:'tag',textContent:tag}));if(onclick)d.onclick=onclick;return d}
async function selectPage(p){await post('/api/page',{page:p});settings.page=p;msg('Page: '+p);loadLists()}
async function selectOff(p){const r=await post('/api/settings',{off_page:p});settings=r.settings;msg('Off image: '+(p||'blank'));loadLists()}
async function delBitmap(n){if(!confirm('Delete '+n+'?'))return;await post('/api/bitmap/delete',{name:n});msg('Deleted');settings=await api('/api/settings');loadLists()}
async function delIcon(n){if(!confirm('Delete icon '+n+'?'))return;await post('/api/icon/delete',{name:n});msg('Deleted');if(ic&&same(ic.orig,n))icClose();loadLists()}
async function toIcon(n){if(!confirm('Make '+n+' an icon? It is then only used on pages, not shown on its own.'))return;await post('/api/bitmap/to_icon',{name:n});msg(n+' is now an icon');loadLists()}
async function toBitmap(n){await post('/api/icon/to_bitmap',{name:n});msg(n+' is now a bitmap');if(ic&&same(ic.orig,n))icClose();loadLists()}
async function resetPage(n){if(!confirm('Reset '+n+' to the original page? Your changes to it are lost.'))return;await post('/api/pages/delete',{name:n});msg(n+' reset');if(pe&&same(pe.orig,n))peClose();loadLists()}
async function delPage(n){if(!confirm('Delete page '+n+'?'))return;await post('/api/pages/delete',{name:n});msg('Deleted');if(pe&&same(pe.orig,n))peClose();settings=await api('/api/settings');loadLists()}
async function delFont(n){if(!confirm('Delete font '+n+'?'))return;await post('/api/fonts/delete',{name:n});msg('Deleted');loadLists()}
function swText(ms){const s=Math.floor(ms/1000),h=Math.floor(s/3600),m=Math.floor(s%3600/60),p=n=>String(n).padStart(2,'0');return(h?h+':'+p(m):m)+':'+p(s%60)}
function swShow(sw){if(sw)$('swtime').textContent=swText(sw.ms)+(sw.running?' (running)':'')}
async function stopwatch(action){swShow(await post('/api/stopwatch',{action}));if(pe)pePreview()}
async function selectPage(p){await post('/api/page',{page:p});settings.page=p;msg('Page: '+p);loadLists([])}
async function selectOff(p){const r=await post('/api/settings',{off_page:p});settings=r.settings;msg('Off image: '+(p||'blank'));loadLists([])}
async function delBitmap(n){if(!confirm('Delete '+n+'?'))return;await post('/api/bitmap/delete',{name:n});msg('Deleted');settings=await api('/api/settings');loadLists(['bitmaps'])}
async function delIcon(n){if(!confirm('Delete icon '+n+'?'))return;await post('/api/icon/delete',{name:n});msg('Deleted');if(ic&&same(ic.orig,n))icClose();loadLists(['icons'])}
async function toIcon(n){if(!confirm('Make '+n+' an icon? It is then only used on pages, not shown on its own.'))return;await post('/api/bitmap/to_icon',{name:n});msg(n+' is now an icon');loadLists(['bitmaps','icons'])}
async function toBitmap(n){await post('/api/icon/to_bitmap',{name:n});msg(n+' is now a bitmap');if(ic&&same(ic.orig,n))icClose();loadLists(['bitmaps','icons'])}
async function resetPage(n){if(!confirm('Reset '+n+' to the original page? Your changes to it are lost.'))return;await post('/api/pages/delete',{name:n});msg(n+' reset');if(pe&&same(pe.orig,n))peClose();loadLists(['pages'])}
async function delPage(n){if(!confirm('Delete page '+n+'?'))return;await post('/api/pages/delete',{name:n});msg('Deleted');if(pe&&same(pe.orig,n))peClose();settings=await api('/api/settings');loadLists(['pages'])}
async function delFont(n){if(!confirm('Delete font '+n+'?'))return;await post('/api/fonts/delete',{name:n});msg('Deleted');loadLists(['fonts'])}
function swText(ms){const s=Math.floor(ms/1000),d=Math.floor(s/86400),h=Math.floor(s%86400/3600),m=Math.floor(s%3600/60),p=n=>String(n).padStart(2,'0');return(d?d+'d '+h+':'+p(m):h?h+':'+p(m):m)+':'+p(s%60)}
function swShow(sw){if(!sw)return;$('swtime').textContent=swText(sw.ms)+(sw.running?' (running)':'');$('swsince').textContent=sw.start?'Counting since '+sw.start.replace('T',' '):sw.ms?'Paused':''}
async function stopwatch(action,extra){swShow(await post('/api/stopwatch',Object.assign({action},extra)));if(pe)pePreview()}
async function swSetStart(){const v=$('swstart').value;if(!v){msg('Pick a date and time first',true);return}await stopwatch('set',{start:v.slice(0,16)});msg('Counting since '+v.replace('T',' '))}
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)'}));
@@ -350,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};
@@ -363,8 +382,8 @@ 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()}
async function scSave(){sched.blocks.sort(bySlot);sched=await post('/api/schedule',schedPayload());schedDirty=false;schedBuild();msg('Schedule saved');loadLists()}
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){}}
// page editor: the ESP32 draws the preview and returns the element boxes
@@ -428,7 +447,7 @@ function peElems(){const d=$('pe_elems');d.innerHTML='';d.append(mk('datalist',{
if(e.type=='countdown'){row(field('Until',inp(e,'target','datetime-local')),field('Format',sel(e,'format',CDF.map((x,k)=>[k,x[e.language=='en'?1:0]]))),
field('Language',sel(e,'language',[['nl','Nederlands'],['en','English']],peElems)));
row(field('Before',inp(e,'text','text',{size:10,maxLength:32})),field('When passed',inp(e,'suffix','text',{size:8,maxLength:16,placeholder:'0'})))}
if(e.type=='stopwatch'){row(field('Format',sel(e,'format',[[0,'4:05 (every second)'],[1,'0:04 (hours, minutes)'],[2,'0:04:05 (every second)']])),
if(e.type=='stopwatch'){row(field('Format',sel(e,'format',[[0,'4:05 (every second)'],[1,'0:04 (hours, minutes)'],[2,'0:04:05 (every second)'],[3,'12d 4:05:09 (days, every second)'],[4,'3w 2d (weeks, days)']])),
field('Before',inp(e,'text','text',{size:8,maxLength:32})),field('After',inp(e,'suffix','text',{size:6,maxLength:16})));
row(btn('Start',()=>stopwatch('start')),btn('Stop',()=>stopwatch('stop')),btn('Reset',()=>stopwatch('reset')))}
if(e.type=='image'){const name=inp(e,'text','text',{size:20,maxLength:24,placeholder:e.entity?'weather ':'name'});name.setAttribute('list','bmnames');
@@ -496,7 +515,7 @@ async function haValue(entity,attribute){for(let i=0;i<25;i++){const r=await api
if(!r.pending)return r.value;await new Promise(f=>setTimeout(f,300))}msg('No answer from Home Assistant',true);throw 0}
async function haTest(e){const v=await haValue(e.entity,e.attribute);msg(e.entity+(e.attribute?' '+e.attribute:'')+' = '+v);pePreview()}
async function peSave(){const n=$('pe_name').value.trim();if(!n){msg('Enter a name',true);return}
await post('/api/pages/save',{name:n,page:pePage()});pe.orig=n;$('pe_title').textContent='Edit '+n;msg('Saved '+n);loadLists()}
await post('/api/pages/save',{name:n,page:pePage()});pe.orig=n;$('pe_title').textContent='Edit '+n;msg('Saved '+n);loadLists(['pages'])}
async function peLive(){if(peData)await live(peData)}
// fonts: a TTF/OTF drawn with the browser, each character cut to its dots (format: src/esp32/logic/font.h)
let fontFam=null,fontData=null;
@@ -524,7 +543,7 @@ function fontPreview(){const b=new Uint8Array(W*H);let x=0,first=true;
for(let y=0;y<fontData.h;y++)for(let i=0;i<gl.w;i++)if(gl.rows[y][i]&&x+i<W)b[y*W+x+i]=1;x+=gl.w}
draw($('f_canvas'),b)}
async function fontSave(){const n=$('f_name').value.trim();if(!n||!fontData){msg('Choose a font file and a name',true);return}
await post('/api/fonts/save',{name:n,data:fontData.bytes.map(v=>v.toString(16).padStart(2,'0')).join('')});msg('Saved font '+n);loadLists()}
await post('/api/fonts/save',{name:n,data:fontData.bytes.map(v=>v.toString(16).padStart(2,'0')).join('')});msg('Saved font '+n);loadLists(['fonts',...pagesWithFont(n)])}
// backup: everything in one JSON file; the import posts the chosen parts to the normal endpoints
const SGROUPS=[['schedule','Schedule',s=>({schedule:s.schedule})],
['display','Shown page, off image, No WiFi screen',s=>({page:s.page,off_page:s.off_page,clock:s.clock})],
@@ -617,9 +636,9 @@ function edClear(){ed.set(new Uint8Array(W*H));changed()}
function edInvert(){ed.set(ed.bits.map(v=>1-v));changed()}
async function sendLive(){await live(ed.bits)}
async function saveBitmap(){const n=$('savename').value.trim();if(!n){msg('Enter a name',true);return}
await post('/api/bitmap',{name:n,data:toHex(ed.bits)});msg('Saved '+n);loadLists()}
await post('/api/bitmap',{name:n,data:toHex(ed.bits)});msg('Saved '+n);loadLists(['bitmaps',...pagesUsing(n)])}
async function saveAsIcon(){const n=$('savename').value.trim();if(!n){msg('Enter a name',true);return}
const c=cropBits(ed.bits,W,H);await post('/api/icon',{name:n,width:c.w,height:c.h,data:icToHex(c.bits,c.w,c.h)});msg('Saved icon '+n+' ('+c.w+' x '+c.h+')');loadLists()}
const c=cropBits(ed.bits,W,H);await post('/api/icon',{name:n,width:c.w,height:c.h,data:icToHex(c.bits,c.w,c.h)});msg('Saved icon '+n+' ('+c.w+' x '+c.h+')');loadLists(['icons',...pagesUsing(n)])}
// image conversion: w x h dots, dark parts on
$('file').onchange=e=>{const f=e.target.files[0];if(!f)return;const img=new Image();img.onload=()=>{srcImg=img;$('imgopts').style.display='flex';convert()};img.src=URL.createObjectURL(f)};
['thr','inv','dith','fit'].forEach(id=>$(id).oninput=convert);
@@ -650,9 +669,9 @@ function rleBits(rle){const p=[];let x=0,y=0,w=1,n='';for(const c of rle){if(c>=
function lifeLib(){const d=$('lifepats');d.innerHTML='';for(const l of LIFEPATS){const p=rleBits(l[2]),have=iconList.some(x=>same(x.name,l[0]));
d.append(mk('div',{className:'item'},icCanvas(p.bits,p.w,p.h),mk('div',{className:'name',textContent:l[0]}),mk('div',{className:'tag',textContent:p.w+' x '+p.h+', '+l[1]}),
mk('div',{className:'row'},have?mk('span',{className:'hint',textContent:'added'}):btn('Add',()=>lifeAdd([l])))))}}
async function lifeAdd(list){let k=0,bad=0;for(const[n,,r]of list){if(iconList.some(x=>same(x.name,n)))continue;const p=rleBits(r);
try{await post('/api/icon',{name:n,width:p.w,height:p.h,data:icToHex(p.bits,p.w,p.h)});k++}catch(e){bad++}}
if(!bad)msg(k?'Added '+k+' pattern'+(k>1?'s':''):'All patterns are there');loadLists()}
async function lifeAdd(list){let k=0,bad=0;const added=[];for(const[n,,r]of list){if(iconList.some(x=>same(x.name,n)))continue;const p=rleBits(r);
try{await post('/api/icon',{name:n,width:p.w,height:p.h,data:icToHex(p.bits,p.w,p.h)});k++;added.push(n)}catch(e){bad++}}
if(!bad)msg(k?'Added '+k+' pattern'+(k>1?'s':''):'All patterns are there');loadLists(['icons',...pagesUsing(...added)])}
// icon editor: its own size, drawn like the bitmap editor
let ic=null,icPaint=null,icImg=null;const icc=$('ic_canvas');
function icShow(title){icImg=null;$('ic_imgopts').style.display='none';$('ic_file').value='';$('ic_title').textContent=title;$('ic_name').value=ic.orig;$('ic_w').value=ic.w;$('ic_h').value=ic.h;$('ic').style.display='block';icDraw();$('ic').scrollIntoView({behavior:'smooth'})}
@@ -675,7 +694,7 @@ $('ic_file').onchange=e=>{const f=e.target.files[0];if(!f||!ic)return;const img=
['ic_thr','ic_inv','ic_dith'].forEach(id=>$(id).oninput=()=>icConvert());
function icConvert(){if(!icImg||!ic)return;ic.bits=imgBits(icImg,ic.w,ic.h,+$('ic_thr').value,$('ic_inv').checked,$('ic_dith').checked,'contain');icDraw()}
async function icSave(){const n=$('ic_name').value.trim();if(!n){msg('Enter a name',true);return}
await post('/api/icon',{name:n,width:ic.w,height:ic.h,data:icToHex(ic.bits,ic.w,ic.h)});ic.orig=n;$('ic_title').textContent='Edit '+n;msg('Saved '+n);loadLists()}
await post('/api/icon',{name:n,width:ic.w,height:ic.h,data:icToHex(ic.bits,ic.w,ic.h)});ic.orig=n;$('ic_title').textContent='Edit '+n;msg('Saved '+n);loadLists(['icons',...pagesUsing(n)])}
async function icLive(){if(ic)await live(icFull(ic.bits,ic.w,ic.h))}
// test patterns (live mode)
let testTimer=null;
@@ -686,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'}
@@ -699,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')}
+25 -10
View File
@@ -137,6 +137,16 @@ static void handleRoot()
server.send_P(200, "text/html", WEB_PAGE);
}
// {running, ms, start (local, while running)}
static void stopwatchJson(JsonObject sw)
{
sw["running"] = stopwatch.running();
sw["ms"] = stopwatch.elapsed(epochMs());
char start[20];
if (appStopwatchStart(start))
sw["start"] = start;
}
static void handleStatus()
{
JsonDocument doc;
@@ -168,9 +178,7 @@ static void handleStatus()
doc["off_page"] = appSettings().off_page;
doc["power_enabled"] = controller.powerEnabled();
doc["slow_mode"] = controller.slowModeActive();
JsonObject sw = doc["stopwatch"].to<JsonObject>();
sw["running"] = stopwatch.running();
sw["ms"] = stopwatch.elapsed(millis());
stopwatchJson(doc["stopwatch"].to<JsonObject>());
JsonObject load = doc["load"].to<JsonObject>();
load["loops_per_s"] = loopStats.loopsPerSecond();
@@ -632,27 +640,31 @@ static void handleLive()
sendOk();
}
// {action: "start" | "stop" | "reset"}
// {action: "start" | "stop" | "reset" | "set", start: "YYYY-MM-DDTHH:MM" (set, local time)}
static void handleStopwatch()
{
JsonDocument body;
if (!readBody(body))
return;
const char *action = body["action"] | "";
const char *error;
if (strcmp(action, "start") == 0)
appStopwatch(StopwatchAction::Start);
error = appStopwatch(StopwatchAction::Start);
else if (strcmp(action, "stop") == 0)
appStopwatch(StopwatchAction::Stop);
error = appStopwatch(StopwatchAction::Stop);
else if (strcmp(action, "reset") == 0)
appStopwatch(StopwatchAction::Reset);
error = appStopwatch(StopwatchAction::Reset);
else if (strcmp(action, "set") == 0)
error = appStopwatchSetStart(body["start"] | "");
else
error = "Unknown stopwatch action";
if (error)
{
sendError(400, "Unknown stopwatch action");
sendError(400, error);
return;
}
JsonDocument doc;
doc["running"] = stopwatch.running();
doc["ms"] = stopwatch.elapsed(millis());
stopwatchJson(doc.to<JsonObject>());
sendJson(200, doc);
}
@@ -680,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;
@@ -748,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);
+2 -1
View File
@@ -33,7 +33,8 @@
// POST /api/schedule/back end a manual pick
// POST /api/live show now {data}
// POST /api/live/stop
// POST /api/stopwatch {action: "start" | "stop" | "reset"} -> {running, ms}
// POST /api/stopwatch {action: "start" | "stop" | "reset" | "set", start:
// "YYYY-MM-DDTHH:MM" (set, local)} -> {running, ms, start}
// GET /api/settings (the MQTT password and HA token only with ?secrets=1, for
// the export; otherwise only *_set)
// POST /api/settings changed fields; {settings, restart}
+7 -5
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
@@ -49,7 +50,8 @@ Arduino core, EEPROM and the display driver are replaced by fakes in
- **Nothing blocks.** Every frame (also instant ones, `D1`) is flipped from `update()` in
slices of about 1 ms, so `loop()` keeps reading the serial port. A blocking redraw used
to overflow the 64-byte receive buffer; the lost bytes shifted the rest of a bitmap
(the picture moved up and left) and nothing repaired it.
(the picture moved up and left) and nothing repaired it. Bitmap data is drawn as fast as
it arrives too (one hex digit every 87 µs); dense images used to be slower than that.
- **Every 2 minutes** (`I` command, stored in EEPROM, 0 = never) it flips every dot once
more, with one pulse, to fix dots that got stuck. This also runs in slices, only while
no frame is being received or shown, and continues where it was after a frame.
@@ -89,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:
+11 -11
View File
@@ -182,29 +182,29 @@ bool CommandParser::_bitmapStart()
_error(F("Invalid bitmap height (0)"));
return false;
}
_bitmap_nibble = 0;
_bitmap_col = 0;
_bitmap_row = 0;
_bitmap_active = true;
return true;
}
// Runs for every hex digit while the line arrives (one every 87 us at 115200 baud), so it
// must be quick: no divisions, and drawDots() instead of four drawPixel() calls. Slower
// than that, a dense line (all yellow) overflowed the 64 byte receive buffer.
void CommandParser::_bitmapData(char c)
{
if (!isHex(c))
return;
uint16_t pixel = _bitmap_nibble * 4;
if (pixel >= (uint16_t)_bitmap_w * _bitmap_h)
if (_bitmap_row >= _bitmap_h)
return; // more data than the bitmap size, ignore
uint8_t b = hex2dec(c);
for (uint8_t i = 0; i < 4; i++)
_display.drawDots(_bitmap_x + _bitmap_col, _bitmap_y + _bitmap_row, hex2dec(c), _bitmap_color);
_bitmap_col += 4;
if (_bitmap_col >= _bitmap_w)
{
if (b & (0x8 >> i))
{
uint16_t p = pixel + i;
_display.drawPixel(_bitmap_x + p % _bitmap_w, _bitmap_y + p / _bitmap_w, _bitmap_color);
_bitmap_col = 0;
_bitmap_row++;
}
}
_bitmap_nibble++;
}
// Fc (c = 0/1 color)
void CommandParser::_fill()
+1 -1
View File
@@ -33,7 +33,7 @@ private:
bool _bitmap_active = false;
uint8_t _bitmap_x, _bitmap_y, _bitmap_w, _bitmap_h;
bool _bitmap_color;
uint16_t _bitmap_nibble;
uint8_t _bitmap_col, _bitmap_row; // where the next hex digit goes, in the bitmap
void _runLine();
void _error(const __FlashStringHelper *msg);
+8
View File
@@ -27,6 +27,14 @@ public:
void begin() { log("begin"); }
void display(bool force = false, bool instant = false) { log("display", force, instant); }
void drawPixel(int16_t x, int16_t y, uint16_t color) { log(direct ? "directPixel" : "pixel", x, y, color); }
// Recorded as the pixel calls it stands for (the real one is tested in test_driver)
void drawDots(int16_t x, int16_t y, uint8_t bits, bool color)
{
log("dots", x, y, bits);
for (int i = 0; i < 4; i++)
if (bits & (8 >> i))
drawPixel(x + i, y, color);
}
void fillScreen(uint16_t color) { log("fill", color); }
void setDirect(bool d) { direct = d; }
void setTiming(uint16_t t) { log("timing", t); }
+179
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();
@@ -226,16 +367,54 @@ void test_crc_of_equal_images_is_equal()
delete b;
}
// The fast path for B data must give the same image as drawPixel(), also at the right edge
// (B widths are rounded up to 4, so x + 3 can be past it) and below the last row
void test_draw_dots_is_like_draw_pixel()
{
BROSE9323 *a = make(), *b = make();
a->fillScreen(1);
b->fillScreen(1);
for (int y = 0; y <= H; y++)
for (int x = 0; x < W; x += 4)
{
uint8_t bits = (x * 5 + y * 3) & 0xF;
bool color = (x / 4 + y) % 3 == 0;
a->drawDots(x + 2, y, bits, color);
for (int i = 0; i < 4; i++)
if (bits & (8 >> i))
b->drawPixel(x + 2 + i, y, color);
}
TEST_ASSERT_EQUAL_HEX16(b->crc(), a->crc());
for (int x = 0; x < W; x++)
for (int y = 0; y < H; y++)
{
a->drawPixel(x, y, 0);
b->drawPixel(x, y, 0);
}
a->drawDots(-2, 0, 0xF, 1); // dots 0 and 1 of the first row
b->drawPixel(0, 0, 1);
b->drawPixel(1, 0, 1);
TEST_ASSERT_EQUAL_HEX16(b->crc(), a->crc());
delete a;
delete b;
}
int main()
{
UNITY_BEGIN();
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);
RUN_TEST(test_interrupted_first_frame_still_reaches_every_dot);
RUN_TEST(test_crc_of_equal_images_is_equal);
RUN_TEST(test_draw_dots_is_like_draw_pixel);
return UNITY_END();
}
+217 -16
View File
@@ -583,6 +583,38 @@ void test_power_switch_off_keeps_display_off_during_the_day()
TEST_ASSERT_EQUAL(0, power.on_count);
}
// Slow mode had the power off already: the dots still show the clock, so the power goes on
// for the off image, once
void test_power_switch_off_in_slow_mode_draws_the_off_image()
{
slowMode(true);
run(12, 0, POWER_OFF_DELAY + 200);
TEST_ASSERT_FALSE(power.is_on);
controller->setPowerEnabled(false);
run(12, 1);
TEST_ASSERT_TRUE(power.is_on);
TEST_ASSERT_EQUAL_STRING("off", frames.last().c_str());
run(12, 1, CLEAR_BEFORE_OFF_TIME + 200);
TEST_ASSERT_FALSE(power.is_on);
run(12, 2, 60000);
TEST_ASSERT_EQUAL(2, power.on_count);
TEST_ASSERT_EQUAL(2, (int)frames.shown.size());
}
void test_night_in_slow_mode_draws_the_off_image()
{
slowMode(true);
run(23, 15, POWER_OFF_DELAY + 200);
TEST_ASSERT_FALSE(power.is_on);
run(23, 31);
TEST_ASSERT_TRUE(power.is_on);
TEST_ASSERT_EQUAL_STRING("off", frames.last().c_str());
run(23, 31, POWER_OFF_DELAY + 200);
TEST_ASSERT_FALSE(power.is_on);
run(3, 0, 60000);
TEST_ASSERT_EQUAL(2, power.on_count);
}
void test_power_switch_on_again_shows_clock()
{
run(12, 0);
@@ -716,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()
@@ -1475,21 +1566,42 @@ void test_countdown_shows_seconds_only_when_needed()
void test_stopwatch()
{
const int64_t T = 1760000000000LL; // ms since 1970, in 2025
Stopwatch sw;
TEST_ASSERT_EQUAL_UINT32(0, sw.elapsed(5000));
sw.start(1000);
TEST_ASSERT_EQUAL_UINT64(0, sw.elapsed(T));
sw.start(T + 1000);
TEST_ASSERT_TRUE(sw.running());
TEST_ASSERT_EQUAL_UINT32(2000, sw.elapsed(3000));
sw.stop(4000);
TEST_ASSERT_EQUAL_UINT32(3000, sw.elapsed(9000));
sw.start(10000);
sw.start(11000); // already running: no restart
TEST_ASSERT_EQUAL_UINT32(5000, sw.elapsed(12000));
TEST_ASSERT_EQUAL_UINT64(2000, sw.elapsed(T + 3000));
sw.stop(T + 4000);
TEST_ASSERT_EQUAL_UINT64(3000, sw.elapsed(T + 9000));
sw.start(T + 10000);
sw.start(T + 11000); // already running: no restart
TEST_ASSERT_EQUAL_UINT64(5000, sw.elapsed(T + 12000));
TEST_ASSERT_EQUAL_UINT64(3000, sw.elapsed(T + 5000)); // clock set back: never less than before
sw.reset();
TEST_ASSERT_FALSE(sw.running());
TEST_ASSERT_EQUAL_UINT32(0, sw.elapsed(20000));
sw.start(0xFFFFFF00u); // across the millis() overflow
TEST_ASSERT_EQUAL_UINT32(0x200, sw.elapsed(0x100));
TEST_ASSERT_EQUAL_UINT64(0, sw.elapsed(T + 20000));
// Past 49 days (millis() would overflow)
sw.start(T);
TEST_ASSERT_EQUAL_UINT64(60ULL * 86400000ULL, sw.elapsed(T + 60LL * 86400000LL));
// A start date by hand: counts from there, pausing keeps the time
TEST_ASSERT_FALSE(sw.setStart(T + 1000, T)); // in the future
TEST_ASSERT_TRUE(sw.setStart(T - 3 * 86400000LL, T));
TEST_ASSERT_TRUE(sw.running());
TEST_ASSERT_EQUAL_UINT64(3 * 86400000ULL, sw.elapsed(T));
sw.stop(T);
TEST_ASSERT_EQUAL_UINT64(3 * 86400000ULL, sw.elapsed(T + 5000));
// Kept over a restart (system/stopwatch_store stores the state)
Stopwatch copy;
copy.restore(sw.state());
TEST_ASSERT_FALSE(copy.running());
TEST_ASSERT_EQUAL_UINT64(3 * 86400000ULL, copy.elapsed(T + 99999));
sw.start(T + 1000);
copy.restore(sw.state());
TEST_ASSERT_EQUAL_UINT64(3 * 86400000ULL + 1000, copy.elapsed(T + 2000));
PageElement e; // textOf: 65 s on the stopwatch
e.type = ElementType::Stopwatch;
@@ -1502,6 +1614,29 @@ void test_stopwatch()
TEST_ASSERT_EQUAL_STRING("T 0:01:05", textOf(e).c_str());
TEST_ASSERT_TRUE(elementShowsSeconds(e, LocalTime(), true));
TEST_ASSERT_FALSE(elementShowsSeconds(e, LocalTime(), false)); // stopped
strcpy(e.text, "");
// Days and weeks
ElementValues values;
char text[40];
e.format = STOPWATCH_D_H_MM_SS;
values.stopwatch_ms = 65000;
elementText(e, LocalTime(), values, text, sizeof(text));
TEST_ASSERT_EQUAL_STRING("0:01:05", text); // below a day: without the days
values.stopwatch_ms = (12ULL * 86400 + 4 * 3600 + 5 * 60 + 9) * 1000;
elementText(e, LocalTime(), values, text, sizeof(text));
TEST_ASSERT_EQUAL_STRING("12d 4:05:09", text);
TEST_ASSERT_TRUE(elementShowsSeconds(e, LocalTime(), true));
e.format = STOPWATCH_W_D;
elementText(e, LocalTime(), values, text, sizeof(text));
TEST_ASSERT_EQUAL_STRING("1w 5d", text);
TEST_ASSERT_FALSE(elementShowsSeconds(e, LocalTime(), true));
values.stopwatch_ms = 2ULL * 86400000 + 5000;
elementText(e, LocalTime(), values, text, sizeof(text));
TEST_ASSERT_EQUAL_STRING("2d", text);
values.stopwatch_ms = 400ULL * 86400000; // more than a year, past 32 bit ms
elementText(e, LocalTime(), values, text, sizeof(text));
TEST_ASSERT_EQUAL_STRING("57w 1d", text);
}
void test_home_assistant_multiplier()
@@ -1900,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;
@@ -3226,6 +3419,8 @@ int main()
RUN_TEST(test_power_switch_off_clears_and_powers_off_quickly);
RUN_TEST(test_power_switch_off_waits_for_the_refresh_effect);
RUN_TEST(test_power_switch_off_keeps_display_off_during_the_day);
RUN_TEST(test_power_switch_off_in_slow_mode_draws_the_off_image);
RUN_TEST(test_night_in_slow_mode_draws_the_off_image);
RUN_TEST(test_power_switch_on_again_shows_clock);
RUN_TEST(test_redraws_after_power_was_switched_off_elsewhere);
RUN_TEST(test_no_wifi_is_shown_after_a_minute_without_wifi);
@@ -3239,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);
@@ -3297,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);
+85 -1
View File
@@ -193,6 +193,21 @@ void test_full_screen_bitmap_is_streamed()
TEST_ASSERT_EQUAL(84 * 19, display.count("pixel"));
}
// A hex digit arrives every 87 us, so the Nano must draw each one with a single quick
// drawDots() call. Four drawPixel() calls and a division per dot took about 105 us: dense
// images (all yellow) overflowed the receive buffer (2.19.3). The PC can't time the Nano,
// so this checks the way it is drawn; the speed itself: tools/display_smoke_test.py.
void test_bitmap_digits_are_drawn_with_one_quick_call_each()
{
send("B000054131" + std::string(399, 'F') + "\n");
TEST_ASSERT_EQUAL(399, display.count("dots"));
TEST_ASSERT_EQUAL(4 * 399, display.count("pixel")); // only the ones drawDots() stands for
const DisplayCall *last = display.last("dots");
TEST_ASSERT_EQUAL(80, last->a); // the last digit of the last row
TEST_ASSERT_EQUAL(18, last->b);
TEST_ASSERT_EQUAL(0xF, last->c);
}
// The commands the ESP32 driver sends for a frame (lib/BROSE9323/frame_commands.h), run
// through this parser: the drawn dots must give the wanted image.
static const int IMG_BYTES = 11 * 19;
@@ -463,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
@@ -471,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)
{
@@ -559,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
// ---------------------------------------------------------------------------
@@ -711,6 +791,7 @@ int main()
RUN_TEST(test_bitmap_pixels);
RUN_TEST(test_full_screen_bitmap_is_streamed);
RUN_TEST(test_bitmap_digits_are_drawn_with_one_quick_call_each);
RUN_TEST(test_frame_commands_send_only_the_changed_dots);
RUN_TEST(test_frame_commands_full_frame);
RUN_TEST(test_frame_commands_edge_and_nothing_changed);
@@ -734,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);
+105
View File
@@ -0,0 +1,105 @@
"""Checks on the real display that the Nano gets every frame right, also very dense ones.
Run it after changes to the Nano firmware, the driver (lib/BROSE9323) or the frames.
python tools/display_smoke_test.py [ESP32 address, default 10.1.1.198]
It shows a few test images in live mode (all yellow, a dense image, a checkerboard), waits
for the frame check of each (the Nano's checksum of what it received) and then goes back
to normal. It fails when the frame check found a wrong image, a missing answer, a Nano
restart or an ERR reply (e.g. "Line too long": lost bytes). This is the speed test the PC
tests can't do: with 2.19.2 the Nano drew dense images slower than they arrived, which
broke all yellow. The dots flip for about 20 s. Only the Python standard library is used.
"""
import json
import sys
import time
import urllib.error
import urllib.request
ESP = 'http://' + (sys.argv[1] if len(sys.argv) > 1 else '10.1.1.198')
W, H, ROW_BYTES = 84, 19, 11
CHECK_TIMEOUT = 20 # s: the ESP asks every 3 s at most, the answer takes up to 2 s
COUNTERS = ('mismatches', 'no_reply', 'errors', 'restarts', 'repairs')
def request(path, body=None):
data = None if body is None else json.dumps(body).encode()
req = urllib.request.Request(ESP + path, data=data, headers={'Content-Type': 'application/json'})
try:
with urllib.request.urlopen(req, timeout=30) as r:
return json.loads(r.read())
except urllib.error.HTTPError as e:
sys.exit('%s: %s' % (path, e.read().decode(errors='replace')))
def image(dot):
"""Bitmap hex (logic/bitmap_format.h: rows of 11 bytes, MSB = left dot) of dot(x, y)."""
out = []
for y in range(H):
for i in range(ROW_BYTES):
v = 0
for k in range(8):
x = i * 8 + k
if x < W and dot(x, y):
v |= 0x80 >> k
out.append('%02x' % v)
return ''.join(out)
TESTS = [
('all yellow', image(lambda x, y: True)),
# About 90 % of the dots, scattered: like the panda bitmap that failed
('dense image', image(lambda x, y: (x * 7 + y * 13) % 11 != 0)),
('checkerboard', image(lambda x, y: (x + y) % 2 == 0)),
]
def link():
return request('/api/status')['nano_link']
def answered(counts):
return counts['checks'] + counts['mismatches'] + counts['no_reply']
def main():
status = request('/api/status')
if not status['power_enabled']:
sys.exit('The Power switch is off (Home Assistant): live mode is not possible')
effect_s = request('/api/settings')['drive']['effect_time'] / 1000
start = link()
print('Firmware %s, frame check before: %s' % (status['version'], start))
failed = False
try:
for name, data in TESTS:
before = link()
request('/api/live', {'data': data})
deadline = time.time() + CHECK_TIMEOUT
now = before
while answered(now) == answered(before) and time.time() < deadline:
time.sleep(0.5)
now = link()
if answered(now) == answered(before):
print('%-13s no frame check within %d s' % (name, CHECK_TIMEOUT))
failed = True
continue
bad = {c: now[c] - before[c] for c in COUNTERS if now[c] != before[c]}
print('%-13s %s' % (name, 'ok' if not bad else 'FAILED %s %s' % (bad, now['last_error'])))
failed |= bool(bad)
time.sleep(effect_s + 1) # let it finish flipping, so each image can be seen
finally:
request('/api/live/stop', {})
end = link()
bad = {c: end[c] - start[c] for c in COUNTERS if end[c] != start[c]}
if bad:
print('Frame check after: %s, last error: %s' % (bad, end['last_error']))
failed = True
print('FAILED' if failed else 'All frames arrived right')
sys.exit(1 if failed else 0)
if __name__ == '__main__':
main()